diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore index b2f6a11..549e00a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ -### IntelliJ IDEA ### -out/ -!**/src/main/**/out/ -!**/src/test/**/out/ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ -### Eclipse ### +### STS ### .apt_generated .classpath .factorypath @@ -11,9 +12,12 @@ out/ .settings .springBeans .sts4-cache -bin/ -!**/src/main/**/bin/ -!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr ### NetBeans ### /nbproject/private/ @@ -21,9 +25,9 @@ bin/ /dist/ /nbdist/ /.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ -### VS Homework.Code ### +### VS Code ### .vscode/ - -### Mac OS ### -.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 26d3352..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 208e2c3..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 4a57301..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml deleted file mode 100644 index 2b63946..0000000 --- a/.idea/uiDesigner.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/Java2.iml b/Java2.iml deleted file mode 100644 index c3dc060..0000000 --- a/Java2.iml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/example.txt b/example.txt deleted file mode 100644 index 37a5b15..0000000 --- a/example.txt +++ /dev/null @@ -1 +0,0 @@ -Domande \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..0ab4a04 --- /dev/null +++ b/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.5 + + + com.example + jpa + 0.0.1-SNAPSHOT + jpa + Demo project for Spring Boot + + + + + + + + + + + + + + + 23 + 23 + 23 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + com.h2database + h2 + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-devtools + runtime + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + org.springframework.boot + spring-boot-starter-mail + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/AbstractTry/Main.java b/src/AbstractTry/Main.java deleted file mode 100644 index 882113d..0000000 --- a/src/AbstractTry/Main.java +++ /dev/null @@ -1,166 +0,0 @@ -package AbstractTry; -// BankAccount.java - -// Define an abstract class named BankAccount -abstract class BankAccount { - // Declare private variables for account number and balance - private String accountNumber; - private double balance; - - // Constructor that accepts account number and balance, and sets them to the corresponding variables - public BankAccount(String accountNumber, double balance) { - this.accountNumber = accountNumber; - this.balance = balance; - } - - // Getter method for account number - public String getAccountNumber() { - return accountNumber; - } - - // Getter method for balance - public double getBalance() { - return balance; - } - - // Protected setter method for balance - protected void setBalance(double balance) { - this.balance = balance; - } - - // Declare an abstract method for depositing an amount - public abstract void deposit(double amount); - - // Declare an abstract method for withdrawing an amount - public abstract void withdraw(double amount); -} -// SavingsAccount.java - -// Define a subclass named SavingsAccount that extends BankAccount -class SavingsAccount extends BankAccount { - // Constructor that accepts account number and balance, and passes them to the superclass constructor - public SavingsAccount(String accountNumber, double balance) { - super(accountNumber, balance); - } - - // Override the deposit method to add an amount to the balance - @Override - public void deposit(double amount) { - // Update the balance by adding the deposit amount - setBalance(getBalance() + amount); - // Print a message indicating the deposit was successful - System.out.println("Deposit of $" + amount + " successful. Current balance: $" + getBalance()); - } - - // Override the withdraw method to subtract an amount from the balance - @Override - public void withdraw(double amount) { - // Check if the balance is sufficient for the withdrawal - if (getBalance() >= amount) { - // Update the balance by subtracting the withdrawal amount - setBalance(getBalance() - amount); - // Print a message indicating the withdrawal was successful - System.out.println("Withdrawal of $" + amount + " successful. Current balance: $" + getBalance()); - } else { - // Print a message indicating insufficient funds - System.out.println("Insufficient funds. Withdrawal failed."); - } - } -} -// CurrentAccount.java -// Subclass CurrentAccount - -// Define CurrentAccount class that extends BankAccount -class CurrentAccount extends BankAccount { - - // Constructor to initialize account number and balance - public CurrentAccount(String accountNumber, double balance) { - super(accountNumber, balance); // Call superclass constructor with account number and balance - } - - // Override deposit method from BankAccount - @Override - public void deposit(double amount) { - // Add deposit amount to current balance - setBalance(getBalance() + amount); - // Print successful deposit message with updated balance - System.out.println("Deposit of $" + amount + " successful. Current balance: $" + getBalance()); - } - - // Override withdraw method from BankAccount - @Override - public void withdraw(double amount) { - // Check if there are sufficient funds for the withdrawal - if (getBalance() >= amount) { - // Subtract withdrawal amount from current balance - setBalance(getBalance() - amount); - // Print successful withdrawal message with updated balance - System.out.println("Withdrawal of $" + amount + " successful. Current balance: $" + getBalance()); - } else { - // Print insufficient funds message if withdrawal cannot be made - System.out.println("Insufficient funds. Withdrawal failed."); - } - } -} -// Main.java -// Subclass Main - -// Define public class Main -public class Main { - // Define the main method - public static void main(String[] args) { - // Declare double variables for initial balance, deposit amount, and withdrawal amount - double ibal, damt, wamt; - - // Set initial balance for SavingsAccount - ibal = 1000.00; - // Create a new SavingsAccount object with the initial balance - SavingsAccount savingsAccount = new SavingsAccount("SA001", ibal); - // Print initial balance of SavingsAccount - System.out.println("Savings A/c: Initial Balace: $" + ibal); - - // Set deposit amount - damt = 500.00; - // Deposit amount into SavingsAccount - savingsAccount.deposit(damt); - - // Set first withdrawal amount - wamt = 250.00; - // Withdraw amount from SavingsAccount - savingsAccount.withdraw(wamt); - - // Set second withdrawal amount - wamt = 1600.00; - // Print attempt to withdraw larger amount - System.out.println("\nTry to withdraw: $" + wamt); - // Attempt to withdraw larger amount from SavingsAccount - savingsAccount.withdraw(wamt); - - // Print an empty line for separation - System.out.println(); - - // Set initial balance for CurrentAccount - ibal = 5000.00; - // Create a new CurrentAccount object with the initial balance - CurrentAccount currentAccount = new CurrentAccount("CA001", ibal); - // Print initial balance of CurrentAccount - System.out.println("Current A/c: Initial Balace: $" + ibal); - - // Set deposit amount for CurrentAccount - damt = 2500.00; - // Deposit amount into CurrentAccount - currentAccount.deposit(1000.0); - - // Set first withdrawal amount for CurrentAccount - wamt = 1250.00; - // Withdraw amount from CurrentAccount - currentAccount.withdraw(3000.0); - - // Set second withdrawal amount for CurrentAccount - wamt = 6000.00; - // Print attempt to withdraw larger amount from CurrentAccount - System.out.println("\nTry to withdraw: $" + wamt); - // Attempt to withdraw larger amount from CurrentAccount - savingsAccount.withdraw(wamt); - } -} \ No newline at end of file diff --git a/src/Again/Bicycle.java b/src/Again/Bicycle.java deleted file mode 100644 index d9c0d73..0000000 --- a/src/Again/Bicycle.java +++ /dev/null @@ -1,23 +0,0 @@ -package Again; - -public class Bicycle { - public int speed; - public int gear; - - public Bicycle(int speed, int gear) { - this.speed = speed; - this.gear = gear; - } - - public void changeGear(int newGear) { - gear = newGear; - } - - public void speedUp(int increment) { - speed += increment; - } - - public void applyBrake(int decrement) { - speed -= decrement; - } -} diff --git a/src/Again/Boat.java b/src/Again/Boat.java deleted file mode 100644 index b09b44a..0000000 --- a/src/Again/Boat.java +++ /dev/null @@ -1,15 +0,0 @@ -package Again; - -public class Boat { - public double length; - public double weight; - - public Boat(double length, double weight) { - this.length = length; - this.weight = weight; - } - - public void sail() { - System.out.println("The boat is sailing"); - } -} diff --git a/src/Again/Car.java b/src/Again/Car.java deleted file mode 100644 index abf1925..0000000 --- a/src/Again/Car.java +++ /dev/null @@ -1,25 +0,0 @@ -package Again; - -public class Car { - public String make; - public String model; - public int year; - - public Car(String make, String model, int year) { - this.make = make; - this.model = model; - this.year = year; - } - - public void start() { - System.out.println("Car is starting"); - } - - public void stop() { - System.out.println("Car is stopping"); - } - - public void accelerate() { - System.out.println("Car is accelerating"); - } -} \ No newline at end of file diff --git a/src/Again/ElectricCar.java b/src/Again/ElectricCar.java deleted file mode 100644 index 00efb25..0000000 --- a/src/Again/ElectricCar.java +++ /dev/null @@ -1,16 +0,0 @@ -package Again; - -public class ElectricCar extends Car { - public int batteryCapacity; - public int range; - - public ElectricCar(String make, String model, int year, int batteryCapacity, int range) { - super(make, model, year); - this.batteryCapacity = batteryCapacity; - this.range = range; - } - - public void charge() { - System.out.println("Electric car is charging"); - } -} diff --git a/src/Again/FishingBoat.java b/src/Again/FishingBoat.java deleted file mode 100644 index da8e18e..0000000 --- a/src/Again/FishingBoat.java +++ /dev/null @@ -1,16 +0,0 @@ -package Again; - -public class FishingBoat extends Boat { - public int fishCapacity; - public String typeOfNet; - - public FishingBoat(double length, double weight, int fishCapacity, String typeOfNet) { - super(length, weight); - this.fishCapacity = fishCapacity; - this.typeOfNet = typeOfNet; - } - - public void castNet() { - System.out.println("Casting the net"); - } -} diff --git a/src/Again/Main.java b/src/Again/Main.java deleted file mode 100644 index ade4114..0000000 --- a/src/Again/Main.java +++ /dev/null @@ -1,56 +0,0 @@ -package Again; - -public class Main { - public static void main(String[] args) { - Bicycle bike = new Bicycle(10, 1); - bike.speedUp(5); - bike.changeGear(2); - bike.applyBrake(2); - System.out.println("Bicycle speed: " + bike.speed + ", gear: " + bike.gear); - MountainBike mountainBike = new MountainBike(15, 3, "Off-road", "Full"); - mountainBike.speedUp(10); - mountainBike.adjustSuspension("Soft"); - System.out.println("MountainBike speed: " + mountainBike.speed + ", gear: " + mountainBike.gear + ", tire type: " + mountainBike.tireType + ", suspension: " + mountainBike.suspension); - - - Car car = new Car("Toyota", "Corolla", 2020); - car.start(); - car.accelerate(); - car.stop(); - System.out.println("Car make: " + car.make + ", model: " + car.model + ", year: " + car.year); - - ElectricCar electricCar = new ElectricCar("Tesla", "Model S", 2021, 100, 400); - electricCar.start(); - electricCar.charge(); - electricCar.accelerate(); - electricCar.stop(); - System.out.println("ElectricCar make: " + electricCar.make + ", model: " + electricCar.model + ", year: " + electricCar.year + ", battery capacity: " + electricCar.batteryCapacity + ", range: " + electricCar.range); - - Tesla tesla = new Tesla("Tesla", "Model X", 2022, 100, 350, "v10.2"); - tesla.start(); - tesla.enableAutopilot(); - tesla.accelerate(); - tesla.stop(); - System.out.println("Tesla make: " + tesla.make + ", model: " + tesla.model + ", year: " + tesla.year + ", battery capacity: " + tesla.batteryCapacity + ", range: " + tesla.range + ", autopilot version: " + tesla.autopilotVersion); - Boat boat = new Boat(30.5, 5000); - boat.sail(); - System.out.println("Boat length: " + boat.length + ", weight: " + boat.weight); - - SpeedBoat speedBoat = new SpeedBoat(25.0, 3000, 80, "V8"); - speedBoat.sail(); - speedBoat.turboBoost(); - System.out.println("SpeedBoat length: " + speedBoat.length + ", weight: " + speedBoat.weight + ", max speed: " + speedBoat.maxSpeed + ", engine type: " + speedBoat.engineType); - - FishingBoat fishingBoat = new FishingBoat(20.0, 4000, 1000, "Gillnet"); - fishingBoat.sail(); - fishingBoat.castNet(); - System.out.println("FishingBoat length: " + fishingBoat.length + ", weight: " + fishingBoat.weight + ", fish capacity: " + fishingBoat.fishCapacity + ", type of net: " + fishingBoat.typeOfNet); - } -} - - - - - - - diff --git a/src/Again/MountainBike.java b/src/Again/MountainBike.java deleted file mode 100644 index 4d40bd1..0000000 --- a/src/Again/MountainBike.java +++ /dev/null @@ -1,17 +0,0 @@ -package Again; - -public class MountainBike extends Bicycle { - public String tireType; - public String suspension; - - public MountainBike(int speed, int gear, String tireType, String suspension) { - super(speed, gear); - this.tireType = tireType; - this.suspension = suspension; - } - - public void adjustSuspension(String newSuspension) { - suspension = newSuspension; - } -} - diff --git a/src/Again/SpeedBoat.java b/src/Again/SpeedBoat.java deleted file mode 100644 index e393526..0000000 --- a/src/Again/SpeedBoat.java +++ /dev/null @@ -1,16 +0,0 @@ -package Again; - -public class SpeedBoat extends Boat { - public int maxSpeed; - public String engineType; - - public SpeedBoat(double length, double weight, int maxSpeed, String engineType) { - super(length, weight); - this.maxSpeed = maxSpeed; - this.engineType = engineType; - } - - public void turboBoost() { - System.out.println("Turbo boost activated"); - } -} diff --git a/src/Again/Tesla.java b/src/Again/Tesla.java deleted file mode 100644 index 5444036..0000000 --- a/src/Again/Tesla.java +++ /dev/null @@ -1,14 +0,0 @@ -package Again; - -public class Tesla extends ElectricCar { - public String autopilotVersion; - - public Tesla(String make, String model, int year, int batteryCapacity, int range, String autopilotVersion) { - super(make, model, year, batteryCapacity, range); - this.autopilotVersion = autopilotVersion; - } - - public void enableAutopilot() { - System.out.println("Autopilot is enabled"); - } -} diff --git a/src/Chestii_Utile_Futuro/Animale.java b/src/Chestii_Utile_Futuro/Animale.java deleted file mode 100644 index 88201ca..0000000 --- a/src/Chestii_Utile_Futuro/Animale.java +++ /dev/null @@ -1,48 +0,0 @@ -package Chestii_Utile_Futuro; - -class Animalele { - public void sound() { - System.out.println("Sounds of animals..."); - } -} - -class Pisici extends Animalele { - @Override - public void sound() { - System.out.println("Meow"); - } -} -class Catei extends Animalele{ - public void sound() { - System.out.println("Woof"); - } -} - -class Bufnita extends Animalele { - @Override - public void sound() { - System.out.println("Hoot"); - } -} - -class Leu extends Animalele{ - @Override - public void sound() { - System.out.println("Roar"); - } -} - -public class Animale { - public static void main(String args[]) { - - Animalele pisici = new Pisici(); - Animalele catei = new Catei(); - Animalele bufnita = new Bufnita(); - Animalele leu = new Leu(); - - pisici.sound();//pisici make Meow - catei.sound();//catei make Woof - bufnita.sound();//bufnita make Hoot - leu.sound();//leu make Roar - } -} \ No newline at end of file diff --git a/src/Chestii_Utile_Futuro/Main2.java b/src/Chestii_Utile_Futuro/Main2.java deleted file mode 100644 index 8fd35a2..0000000 --- a/src/Chestii_Utile_Futuro/Main2.java +++ /dev/null @@ -1,73 +0,0 @@ -package Chestii_Utile_Futuro; - -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.time.Year; -import javax.swing.JOptionPane; - -class FitnessTracker { - String activity; - int duration; - LocalDate date; - - FitnessTracker() { - setFitnessTracker("Running", 0, LocalDate.of(Year.now().getValue(), 1, 1)); - } - FitnessTracker(String n_activity, int n_duration, LocalDate n_date) { - setFitnessTracker(n_activity, n_duration, n_date); - } - - void setFitnessTracker(String n_activity, int n_duration, LocalDate n_date) { - activity = n_activity; - duration = n_duration; - date = n_date; - } - void setActivity(String n_activity) { setFitnessTracker(n_activity, duration, date); } - void setDuration(int n_duration) { setFitnessTracker(activity, n_duration, date); } - void setDate(LocalDate n_date) { setFitnessTracker(activity, duration, n_date); } - String getActivity() { return activity; } - int getDuration() { return duration; } - LocalDate getDate() { return date; } - - String Print() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, YYYY"); - String formattedDate = date.format(formatter); - return "Activity: " + activity + "\nDuration: " + duration + " min\nDate: " + formattedDate; - } -} - -class Main { - public static void main(String[] args) { - int numTrackers = 3; - FitnessTracker[] trackers = new FitnessTracker[numTrackers]; - - String activity = JOptionPane.showInputDialog(null, "Enter Activity Name: "); - String durationStr = JOptionPane.showInputDialog(null, "Enter Exercise Duration (Minutes): "); - String dateStr = JOptionPane.showInputDialog(null, "Enter Date (MM-DD-YYYY): "); - - int duration = Integer.parseInt(durationStr); - LocalDate date = parseDate(dateStr); - - trackers[0] = new FitnessTracker(activity, duration, date); - JOptionPane.showMessageDialog(null, trackers[0].Print()); - - activity = JOptionPane.showInputDialog(null, "Enter Activity Name: "); - durationStr = JOptionPane.showInputDialog(null, "Enter Exercise Duration (Minutes): "); - dateStr = JOptionPane.showInputDialog(null, "Enter Date (MM-DD-YYYY): "); - - duration = Integer.parseInt(durationStr); - date = parseDate(dateStr); - - trackers[1] = new FitnessTracker(); - trackers[1].setFitnessTracker(activity, duration, date); - JOptionPane.showMessageDialog(null, trackers[1].Print()); - - trackers[2] = new FitnessTracker(); - JOptionPane.showMessageDialog(null, trackers[2].Print()); - } - // Helper Function to format and parse date from user string - static LocalDate parseDate(String dateStr) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy"); - return LocalDate.parse(dateStr, formatter); - } -} \ No newline at end of file diff --git a/src/Chestii_Utile_Futuro/SoundAnimal.java b/src/Chestii_Utile_Futuro/SoundAnimal.java deleted file mode 100644 index 47aa17d..0000000 --- a/src/Chestii_Utile_Futuro/SoundAnimal.java +++ /dev/null @@ -1,49 +0,0 @@ -// Sounds Animal -class Anima { - // sound method for the Animal class - public void sound() { - System.out.println("/nAnimal makes sounds"); - } -} - -// Dog.java -class Dogs extends Anima { - // sound method for the Dog class - @Override - public void sound() { - System.out.println("bark"); - } -} - -// Cat.java -class Cats extends Anima { - // sound method for the Cat class - @Override - public void sound() { - System.out.println("meow"); - } -} - -// Wolf.java -class Wolfs extends Anima { - // sound method for the Wolf class - @Override - public void sound() { - System.out.println("howl"); - } -} - -// TestAnimal.java -public class SoundAnimal { - public static void main(String[] args) { - // Create instances of each animal - Anima dogs = new Dogs(); - Anima cats = new Cats(); - Anima wolfs = new Wolfs(); - - // Call the sound method for each animal - dogs.sound(); // Prints "bark" - cats.sound(); // Prints "meow" - wolfs.sound(); // Prints "howl" - } -} \ No newline at end of file diff --git a/src/Domande_Java_From_All_Course/java domande.txt b/src/Domande_Java_From_All_Course/java domande.txt deleted file mode 100644 index 87741a8..0000000 --- a/src/Domande_Java_From_All_Course/java domande.txt +++ /dev/null @@ -1,16 +0,0 @@ - I.What is casting in Java? - Type casting is a powerful feature in Java that allows us to convert variables from one data type to another. Implicit type casting, also known as widening conversion, -is done automatically by the compiler when there is no loss of data. - -II. What is memory reference? -In Java, references are used to access objects, which are variables that hold the “address” of an area of memory in which the attributes of an object -will be stored. This memory is allocated on the heap area. When you declare a field or local variable, this is only a reference to an object on the heap, -not the object itself. When it comes to creating an object, the required amount of memory is requested from the heap, and this object can then be accessed through the reference variable. - - -III.What are decision constructs in Java? - -Decision Making in programming is similar to decision-making in real life. In programming also face some situations -where we want a certain block of code to be executed when some condition is fulfilled. -A programming language uses control statements to control the flow of execution of a program based on certain conditions. -These are used to cause the flow of execution to advance and branch based on changes to the state of a program. diff --git a/src/Homework/AnimalClass/Mains.java b/src/Homework/AnimalClass/Mains.java deleted file mode 100644 index 2f7d4c1..0000000 --- a/src/Homework/AnimalClass/Mains.java +++ /dev/null @@ -1,66 +0,0 @@ -abstract class Animal { - private String name; - private int age; - - public Animal(String name, int age) { - this.name = name; - this.age = age; - } - - public abstract String makeSound(); - - public String getName() { - return name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } -} - -class Dog extends Animal { - public Dog(String name, int age) { - super(name, age); - } - - public String makeSound() { - return "Bark"; - } -} - -class Cat extends Animal { - public Cat(String name, int age) { - super(name, age); - } - - public String makeSound() { - return "meow"; - } -} - -class Wolf extends Animal { - public Wolf(String name, int age) { - super(name, age); - } - - public String makeSound() { - return "how"; - } -} - -public class Mains { - protected static void main(String[] args) { - Animal dog = new Dog("Lucy", 3); - Animal cat = new Cat("Luna", 4); - Animal wolf = new Wolf("Bursuc", 5); - - System.out.println(dog.getName() + " is a " + dog.getClass().getSimpleName() + " and says " + dog.makeSound()); - System.out.println(cat.getName() + " is a " + cat.getClass().getSimpleName() + " and says " + cat.makeSound()); - System.out.println(wolf.getName() + " is a " + wolf.getClass().getSimpleName() + " and says " + wolf.makeSound()); - - } -} \ No newline at end of file diff --git a/src/Homework/ArrayHomework.java b/src/Homework/ArrayHomework.java deleted file mode 100644 index d1ecc08..0000000 --- a/src/Homework/ArrayHomework.java +++ /dev/null @@ -1,116 +0,0 @@ -package Homework; - -import java.util.ArrayList; -import java.util.Scanner; - -public class ArrayHomework { - public static void main(String[] args) { - System.out.println("===Homework sesion 8!==="); - - //shopList();//EX-1 - //arrayTenOdd();//EX-4 - //cityChose();//EX-5 - //movieSearch();//EX-8 - //christmasPresents();//EX-2 - } - - public static void christmasPresents() { - //5.Create a wishlist for christmas with ArrayList and print the values - System.out.println("Christmas Wishlist:"); - ArrayList wishlist = new ArrayList<>(); - wishlist.add("MacBook"); - wishlist.add("GoPro"); - wishlist.add("Xbox ONE X"); - wishlist.add("New clothes"); - wishlist.add("New Watch"); - for (String item : wishlist) { - System.out.println(item); - } - - } - - public static void movieSearch() { - //4.In an array of strings representing movie titles, implement a linear search method to find whether a given movie title exists. - // If it does, print out its position in the array. - System.out.println("Movie Title searching"); - String[] movies = {"Bad Boy", "Titanic", "Byker Boys", "Kung Fu Panda", "Avatar"}; - String movieToFind = "Byker Boys"; - - int position = linearSearch(movies, movieToFind); - if (position != -1) { - System.out.println("Movie found at position: " + position); - } else { - System.out.println("Movie not found."); - } - - - } - - public static void cityChose() { - //3.Create an ArrayList that stores city names. Add at least five city names initially. Then, prompt the user to add a city name. If the city name is already in the list, - // display a message saying it's a duplicate; otherwise, add it to the list. - System.out.println("City List:"); - ArrayList cityNames = new ArrayList<>(); - cityNames.add("Bucuresti"); - cityNames.add("Milano"); - cityNames.add("Madrid"); - cityNames.add("Genova"); - cityNames.add("Padova"); - - Scanner scanner = new Scanner(System.in); - System.out.print("Enter a city name: "); - String cityName = scanner.nextLine(); - - if (cityNames.contains(cityName)) { - System.out.println("This city name is a duplicate."); - } else { - cityNames.add(cityName); - System.out.println("City added: " + cityName); - } - - System.out.println("Current city names: " + cityNames); - } - - public static void arrayTenOdd() { - //2.Given an array of 10 integers, count how many of them are even numbers and how many are odd. - // Print out both counts. - System.out.println("Count even and odd"); - int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - int n = arr.length; - int countEven = 0, countOdd = 0; - - for (int i = 0; i < n; i++) { - if ((arr[i] % 2) == 0) - countEven += 1; - - else - countOdd += 1; - } - System.out.println("Even Elements count : " + countEven); - System.out.println("Odd Elements count : " + countOdd); - - } - - - public static void shopList() { - //1.Create a shopping list with Array and print the values - - System.out.println("Shopping list!"); - String[] shoppingList = {"Faina", "Oua", "Lapte", "Unt", "Zahar", "Ciocolata"}; - for (String item : shoppingList) { - System.out.println(item); - } - } - - private static int linearSearch(String[] movies, String target) { - for (int i = 0; i < movies.length; i++) { - if (movies[i].equals(target)) { - return i; // Return the index where the movie is found - } - } - return -1; // Return -1 if not found - } - -} - - diff --git a/src/Homework/Code.java b/src/Homework/Code.java deleted file mode 100644 index 5dd404e..0000000 --- a/src/Homework/Code.java +++ /dev/null @@ -1,52 +0,0 @@ -package Homework; - -public class Code { - public static void main(String[] args) { - - class Roman { - int value(char r) { - if (r == 'I') - return 1; - if (r == 'V') - return 5; - if (r == 'X') - return 10; - if (r == 'L') - return 50; - if (r == 'C') - return 100; - if (r == 'D') - return 500; - if (r == 'M') - return 1000; - return -1; - } - - int romanToInt(String s) { - int total = 0; - for (int i = 0; i < s.length(); i++) { - int s1 = value(s.charAt(i)); - if (i + 1 < s.length()) { - int s2 = value(s.charAt(i + 1)); - if (s1 >= s2) { - total = total + s1; - } else { - total = total - s1; - } - } else { - total = total + s1; - } - } - return total; - } - - // Driver code - public static void main(String args[]) { - Roman ob = new Roman(); - String val = "MCMXCIV"; - System.out.println(ob.romanToInt(val)); - } - } - } -} - diff --git a/src/Homework/CollegeManagementSystem.java b/src/Homework/CollegeManagementSystem.java deleted file mode 100644 index 348a8cf..0000000 --- a/src/Homework/CollegeManagementSystem.java +++ /dev/null @@ -1,240 +0,0 @@ -import java.util.ArrayList; -import java.util.List; - -// Class to represent a Student -class Student { - private String firstName; - private String lastName; - private String sex; - private int age; - private String dateOfBirth; - private String cnp; // CNP - Personal Numeric Code - private String address; - - public Student(String firstName, String lastName, String sex, int age, String dateOfBirth, String cnp, String address) { - this.firstName = firstName; - this.lastName = lastName; - this.sex = sex; - this.age = age; - this.dateOfBirth = dateOfBirth; - this.cnp = cnp; - this.address = address; - } - - // Method to display student details - public void displayStudentDetails() { - System.out.println("Student: " + firstName + " " + lastName + ", Sex: " + sex + ", Age: " + age + - ", DOB: " + dateOfBirth + ", CNP: " + cnp + ", Address: " + address); - } -} - -// Class to represent a Professor -class Professor { - public String firstName; - public String lastName; - private String sex; - private int age; - private String dateOfBirth; - private String cnp; - private String address; - - public Professor(String firstName, String lastName, String sex, int age, String dateOfBirth, String cnp, String address) { - this.firstName = firstName; - this.lastName = lastName; - this.sex = sex; - this.age = age; - this.dateOfBirth = dateOfBirth; - this.cnp = cnp; - this.address = address; - } - - // Method to display professor details - public void displayProfessorDetails() { - System.out.println("Professor: " + firstName + " " + lastName + ", Sex: " + sex + ", Age: " + age + - ", DOB: " + dateOfBirth + ", CNP: " + cnp + ", Address: " + address); - } -} - -// Class to represent a Course -class Course { - public String name; - private String schedule; - private String duration; - private String description; - private Professor assignedProfessor; - - public Course(String name, String schedule, String duration, String description) { - this.name = name; - this.schedule = schedule; - this.duration = duration; - this.description = description; - } - - // Method to assign a professor to this course - public void assignProfessor(Professor professor) { - this.assignedProfessor = professor; - } - - // Method to display course details along with assigned professor - public void displayCourseDetails() { - System.out.println("Course: " + name + ", Schedule: " + schedule + ", Duration: " + duration + - ", Description: " + description); - if (assignedProfessor != null) { - System.out.print("Assigned Professor: "); - assignedProfessor.displayProfessorDetails(); - } else { - System.out.println("Assigned Professor: None"); - } - } -} - -// Class to represent the College -class College { - private List students; - private List professors; - private List courses; - - public College() { - this.students = new ArrayList<>(); - this.professors = new ArrayList<>(); - this.courses = new ArrayList<>(); - } - - // Add a new student - public void addStudent(Student student) { - students.add(student); - } - - // Add a new professor - public void addProfessor(Professor professor) { - professors.add(professor); - } - - // Add a new course - public void addCourse(Course course) { - courses.add(course); - } - - // Assign a professor to a course - public void assignProfessorToCourse(String courseName, Professor professor) { - for (Course course : courses) { - if (courseName.equalsIgnoreCase(course.name)) { - course.assignProfessor(professor); - System.out.println("Assigned " + professor.firstName + " " + professor.lastName + " to " + courseName); - return; - } - } - System.out.println("Course not found."); - } - - // Display details of all courses - public void viewCourses() { - for (Course course : courses) { - course.displayCourseDetails(); - } - } - - // Display details of all students - public void viewStudents() { - for (Student student : students) { - student.displayStudentDetails(); - } - } - - // Display details of all professors - public void viewProfessors() { - for (Professor professor : professors) { - professor.displayProfessorDetails(); - } - } -} - -// Main class to run the program -public class CollegeManagementSystem { - public static void main(String[] args) { - // Create an instance of College - College college = new College(); - - // Create some students - Student student1 = new Student("Sorin", "Nastase", "Male", 25, "1999-01-01", "1010199702468", "4 Aurara St."); - Student student2 = new Student("Aura", "Pascale", "Female", 27, "1997-02-02", "2020297796413", "25 Portitei St."); - Student student3 = new Student("Aurel", "Pascale", "Male", 25, "1999-03-03", "1030399874685", "35 Eternitati St."); - Student student4 = new Student("Veronica", "Micle", "Female", 27, "1997-04-04", "2040497873216", "45 Garoafei St."); - Student student5 = new Student("Florian", "Tanase", "Male", 25, "1999-05-05", "2050599678234", "25 Minciuni St."); - Student student6 = new Student("Florica", "Tanase", "Female", 28, "1996-06-06", "1060696874321", "28 Libera St."); - Student student7 = new Student("Bogdan", "Mocanu", "Male", 26, "1998-07-07", "1070798873541", "57 Ocupata St."); - Student student8 = new Student("Mihaela", "Padureanu", "Female", 24, "1998-08-08", "2080898762432", "35 Sovata St."); - - // Add students to the college - college.addStudent(student1); - college.addStudent(student2); - college.addStudent(student3); - college.addStudent(student4); - college.addStudent(student5); - college.addStudent(student6); - college.addStudent(student7); - college.addStudent(student8); - - // Create some professors - Professor professor1 = new Professor("Bogdan", "Petrescu", "Male", 45, "1979-03-03", "3567924678642", " 25 Moldoveanu S. St."); - Professor professor2 = new Professor("Andreea", "Lipovenescu", "Female", 40, "1983-04-04", "2468721647832", "26 Garoafei St."); - Professor professor3 = new Professor("Martina", "Agache", "Female", 50, "1973-05-05", "1356789432545", "29 Eternitati St."); - Professor professor4 = new Professor("Bogdan", "Pascale", "Male", 55, "1968-06-06", "1246783216579", "38 Aurora St."); - Professor professor5 = new Professor("Nicolae", "Ion", "Male", 52, "1971-07-07", "2346789412562", "60 Dobrogeanu Ghe. St."); - Professor professor6 = new Professor("Petrica", "Pascale", "Male", 48, "1976-08-08", "1327856743259", "54 Pascale I. St."); - Professor professor7 = new Professor("David", "Florian", "Male", 60, "1963-09-09", "1325796435824", "23 Apelor St."); - Professor professor8 = new Professor("Ancuta", "Moldoveanu", "Female", 43, "1980-10-10", "23465876354126", "3 Eterna St."); - - // Add professors to the college - college.addProfessor(professor1); - college.addProfessor(professor2); - college.addProfessor(professor3); - college.addProfessor(professor4); - college.addProfessor(professor5); - college.addProfessor(professor6); - college.addProfessor(professor7); - college.addProfessor(professor8); - - // Create some courses - Course course1 = new Course("Math", "Mon/Wed/Fri 9-10am", "3 months", "Advanced Calculus"); - Course course2 = new Course("Computer Science", "Tue/Thu 2-4pm", "4 months", "Intro to Programming"); - Course course3 = new Course("Physics", "Mon/Wed/Fri 10-11am", "3 months", "Mechanics and Waves"); - Course course4 = new Course("Chemistry", "Tue/Thu 9-11am", "4 months", "Organic Chemistry"); - Course course5 = new Course("Biology", "Mon/Wed 1-2pm", "3 months", "Genetics and Evolution"); - Course course6 = new Course("Geography", "Tue/Thu 10-11:30am", "4 months", "Physical Geography"); - Course course7 = new Course("English", "Mon/Wed/Fri 11am-12pm", "3 months", "Shakespearean Literature"); - Course course8 = new Course("History", "Tue/Thu 1-3pm", "4 months", "World History"); - - // Add courses to the college - college.addCourse(course1); - college.addCourse(course2); - college.addCourse(course3); - college.addCourse(course4); - college.addCourse(course5); - college.addCourse(course6); - college.addCourse(course7); - college.addCourse(course8); - - // Assign professors to courses - college.assignProfessorToCourse("Math", professor1); - college.assignProfessorToCourse("Computer Science", professor2); - college.assignProfessorToCourse("Physics", professor3); - college.assignProfessorToCourse("Chemistry", professor4); - college.assignProfessorToCourse("Biology", professor5); - college.assignProfessorToCourse("Geography", professor6); - college.assignProfessorToCourse("English", professor7); - college.assignProfessorToCourse("History", professor8); - - // Display all courses - System.out.println("\n--- Courses Offered ---"); - college.viewCourses(); - - // Display all students - System.out.println("\n--- Student List ---"); - college.viewStudents(); - - // Display all professors - System.out.println("\n--- Professor List ---"); - college.viewProfessors(); - } -} \ No newline at end of file diff --git a/src/Homework/First Homework b/src/Homework/First Homework deleted file mode 100644 index 63a4deb..0000000 --- a/src/Homework/First Homework +++ /dev/null @@ -1,361 +0,0 @@ -package Homework; - -import java.util.Scanner; - -public class Homework { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); -//Write a Java program to take two numbers as input and display the result -// of addition, subtraction, multiplication, division, and modulus. - - System.out.print("Enter first number: "); - int num1 = scanner.nextInt(); - System.out.print("Enter the second number: "); - int num2 = scanner.nextInt(); - - System.out.println("Addition: " + (num1 + num2)); - System.out.println("Substraction: " + (num1 - num2)); - System.out.println("Multiplication: " + (num1 * num2)); - System.out.println("Division: " + (num1 / num2)); - System.out.println("Modulus: " + (num1 % num2)); - - - } -} - -package Homework; - -import java.util.Scanner; - -public class Homework2 { -public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); -//Create a Java program where you increment and decrement the same variable. -// Display the value of the variable after each operation. - - int x = 20; - System.out.println("Initiale value: " + x); - - x++; - System.out.println("After increment: " + x); - - x--; - System.out.println("After decrement: " + x); -} -} - -package Homework; - -import java.util.Scanner; - -public class Homework3 { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); -//Write a program to check if a number is positive or negative using logical complement operator. - - System.out.print("Enter a number"); - int num = scanner.nextInt(); - - boolean isPositive = (num > 0); - - if (isPositive) { - System.out.println("The number is positive."); - } else { - System.out.println("The number is negative."); - - - } - } -} -package Homework; - -import java.util.Scanner; - -public class Homework4 { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); -//Write a Java program that uses both the increment (++) and decrement (--) -// operators in a loop to count up to 10 and then back down to 1. - - for (int a = 1; a <= 10; a++) { - System.out.println("A value up is: " + a); - - } - - for (int a = 10; a >= 1; a--) { - - System.out.println("A value down is: " + a); - - } - } -} -package Homework; - -public class Homework5 { -public static void main(String[] args){ - -//Create a Java program that demonstrates the use of each compound -// assignment operator with integers. - - - int s = 16; - - s += 5; //s = s + 5; - System.out.println("s + 5 = " + s); - s -= 5; //s = s - 5; - System.out.println("s - 5 = " + s); - s *= 5; // s = s * 5; - System.out.println("s * 5 = " + s); - s /= 5; // s = s / 5; - System.out.println("s / 5 = " + s); - s %= 5; // s = s % 5: - System.out.println("s % 5 = " + s); - -} -} -package Homework; - -import java.util.Scanner; - -public class Homework6 { -public static void main(String[] args){ - Scanner scanner = new Scanner(System.in); -//Write a Java program that takes two numbers from the user and uses relational operators to display whether the first -// number is greater than, less than, or equal to the second number. - - System.out.print("Enter first number:"); - int num1 = scanner.nextInt(); - System.out.print("Enter second number:"); - int num2 = scanner.nextInt(); - - - if (num1 < num2) { - - System.out.println("First number is less than second number."); - } else if (num1 > num2) { - System.out.println("First number is grater than second number."); - } else { - System.out.println("First number is equal to second number."); - } -} -} -package Homework; - -public class Homework7 { - public static void main(String[] args) { - //Write a program where you perform operations between an integer and a double. - - int s = 8; - double a = 3.5; - - double result = s + a; - System.out.println("Integer + Double: " + result); - - result = s - a; - System.out.println("Integer - Double: " + result); - - result = s * a; - System.out.println("Integer * Double: " + result); - - result = s / a; - System.out.println("Integer / Double: " + result); - } - - } -package Homework; - -public class Homework8 { - public static void main(String[] args){ -//Create a program that takes two byte values, adds them together, -// and stores the result in a byte variable. - - byte firstByte = 100; - byte secondByte = 126; - - int sum; - - sum = firstByte + secondByte; - System.out.println("Result of the two bytes: " + sum); - - - } -} -package Homework; - -import java.util.Scanner; - -public class Homework9 { -public static void main(String[] args){ - -//. Write a program that calculates the area of a rectangle. -// Take the length and breadth as inputs - double length = 0.0; - double width = 0.0; - double area = 0.0; - - Scanner reader = new Scanner(System.in); - System.out.print("Enter lenght of the rectangle: "); - length = reader.nextDouble(); - System.out.print("Enter the width of the rectangle: "); - width = reader.nextDouble(); - area = length * width; - System.out.println("Area of rectangle: " + area); - reader.close(); -} -} -package Homework; - -import java.util.Scanner; - -public class Homework10 { - public static void main(String[] args) { -//Write a program that reverses the sign of an entered integer using unary minus operator. - Scanner scanner = new Scanner(System.in); -// -// int aNumber; -// aNumber = 10; -// System.out.println(aNumber++); -// System.out.println(++aNumber); -// System.out.println(aNumber--); -// System.out.println(--aNumber); - - System.out.print("Enter an integer: "); - int sum = scanner.nextInt(); - - sum = -sum; - System.out.println("The reversed sign value is: " + sum); - - - - } -} -package Homework; - -import java.util.Scanner; - -public class Homework11 { - public static void main(String[] args) { - //Write a Java program that takes two boolean inputs from a user. - // Apply the logical negation operator (!) to each and print the result. - Scanner scanner = new Scanner(System.in); - int count = 6; - - System.out.println(!(count > 2)); // prints true - System.out.println(!(count <= 2)); // prints false - boolean x = true; - boolean y = false; - - System.out.println(!(x && y)); // prints true - System.out.println(!(x || y)); // prints false - } -} -package Homework; - -import java.util.Scanner; - -public class Homework12 { - public static void main(String[] args) { - -//Create a program that takes an integer as input and then increments -// and decrements it by 1, displaying the output at each stage - Scanner scanner = new Scanner(System.in); - - int num = 15; - System.out.println("Original value of the num: " + num); - num++; - System.out.println("variable++ = " + num); - ++num; - System.out.println("++variable = " + num); - - int num2 = 20; - System.out.println("Original value of the num: " + num2); - num2--; - System.out.println("Integer num = " + num2); - --num2; - System.out.println("Integer num = " + num2); - } -} -package Homework; - -import java.util.Scanner; - -public class Homework13 { - public static void main(String[] args) { -// Write a program to calculate the price after discount. Take the original price and discount -// percentage as input. Use compound assignment operator to perform the calculation. - - Scanner sc = new Scanner(System.in); - - int price; - int discount; - System.out.println("Enter price of the product: "); - price = sc.nextInt(); - - System.out.println("Enter the discount(%) of the product: "); - discount = sc.nextInt(); - - - int discountPrice = (price * discount ) / 100; - int finalPrice = price - discountPrice; - - System.out.println("Discount price is: " + discountPrice); - System.out.println("Final price is: " + finalPrice); - - } -} -package Homework; - -import java.util.Scanner; - -public class Homework14 { - public static void main(String[] args) { -//Create a program that checks if a user entered number is within a -// specific range (e.g., 1-100). Use relational operators for the checks. - - Scanner sc = new Scanner(System.in); - - System.out.print("Enter a number: "); - int num = sc.nextInt(); - if ( num >= 1 && num <= 100) { - System.out.println("The number is within the range of 1 to 100."); - } else { - System.out.println("The number is not in range of 1-100."); - } - } -} -package Homework; -import java.util.Scanner; -public class HomeWorses5 { - // System.out.println("Incercarile mele"); - - public static void main(String[] args) { -//17*sesion4 - String Username; - String Password; - - Password = "8989"; - Username = "Veronica"; - - Scanner input1 = new Scanner(System.in); - System.out.println("Enter Username : "); - String username = input1.next(); - - Scanner input2 = new Scanner(System.in); - System.out.println("Enter Password : "); - String password = input2.next(); - - if (username.equals(Username) && password.equals(Password)) { - - System.out.println("Access Granted! Welcome!"); - } else if (username.equals(Username)) { - System.out.println("Invalid Password!"); - } else if (password.equals(Password)) { - System.out.println("Invalid Username!"); - } else { - System.out.println("Invalid Username & Password!"); - } - - - } - -} \ No newline at end of file diff --git a/src/Homework/Main_Homeworks.java b/src/Homework/Main_Homeworks.java deleted file mode 100644 index 2550034..0000000 --- a/src/Homework/Main_Homeworks.java +++ /dev/null @@ -1,71 +0,0 @@ -package Homework; - -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.Year; -import java.time.format.DateTimeFormatter; -import java.util.Calendar; -import java.util.Date; - -public class Main_Homeworks { - public static void main(String[] args){ -//Homework UtilityClasses - - //Date(); - //DateDecomposition(); - //SpecificDateReturns(); - //CurentTime(); - } - //Write a method named displayCurrentTime that prints the current time to the console. - //Expected Output: The current time in the format HH:MM:SS. - public static void CurentTime(){ - - DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("dd MMMM yyyy HH:mm:ss"); - SimpleDateFormat parsedDateTime; - // System.out.println("New format date time: " + parsedDateTime.format(newFormat)); - - } - //Write a method named createSpecificDate that returns a date object representing 19th August 2025. - //Expected Output: A date object for 2025-8-19. - public static void SpecificDateReturns(){ - - - } - - //Write a method named displayDateComponents that accepts a date as an argument and prints its year, month, and day components separately. - //Input: A date in the format YYYY-MM-DD. - //Expected Output: - //makefile - //Copy code - //Year: YYYY - //Month: MM - //Day: DD - public static void DateDecomposition(){ - Date date1 = new Date("YYYY-MM-dd"); - SimpleDateFormat formatNowYear = new SimpleDateFormat("YYYY"); - SimpleDateFormat formatNowMonth = new SimpleDateFormat("MM"); - SimpleDateFormat formatNowDay = new SimpleDateFormat("dd"); - - String currentDay = formatNowDay.format(date1); - String currentMonth = formatNowMonth.format(date1); - String currentYear = formatNowYear.format(date1); - System.out.println("Dte:" + date1); - //inca in incercari - } - //Write a method named displayTodaysDate that, when called, prints the current date to the console. - //Expected Output: Today's date in the format YYYY-MM-DD. - public static void Date(){ - - - SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd"); - Date date = new Date(); - System.out.println(formatter.format(date)); - - - } - - - -} diff --git a/src/Homework/MatrixMultiplication.java b/src/Homework/MatrixMultiplication.java deleted file mode 100644 index 869081b..0000000 --- a/src/Homework/MatrixMultiplication.java +++ /dev/null @@ -1,71 +0,0 @@ -package Homework; - -import java.util.Arrays; - -public class MatrixMultiplication { - public static void main(String[] args) { - int size = 500; - double[][] A = generateRandomMatrix(size, size); - double[][] B = generateRandomMatrix(size, size); - double[][] C = new double[size][size]; - - int numThreads = 4; - Thread[] threads = new Thread[numThreads]; - int rowsPerThread = size / numThreads; - - for (int i = 0; i < numThreads; i++) { - int startRow = i * rowsPerThread; - int endRow = (i == numThreads - 1) ? size : startRow + rowsPerThread; - threads[i] = new Thread(new Worker(A, B, C, startRow, endRow)); - threads[i].start(); - } - - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - System.out.println("Matrix multiplication completed."); - } - - private static double[][] generateRandomMatrix(int rows, int cols) { - double[][] matrix = new double[rows][cols]; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - matrix[i][j] = Math.random(); - } - } - return matrix; - } -} - -class Worker implements Runnable { - private final double[][] A; - private final double[][] B; - private final double[][] C; - private final int startRow; - private final int endRow; - - public Worker(double[][] A, double[][] B, double[][] C, int startRow, int endRow) { - this.A = A; - this.B = B; - this.C = C; - this.startRow = startRow; - this.endRow = endRow; - } - - @Override - public void run() { - for (int i = startRow; i < endRow; i++) { - for (int j = 0; j < B[0].length; j++) { - C[i][j] = 0; - for (int k = 0; k < A[0].length; k++) { - C[i][j] += A[i][k] * B[k][j]; - } - } - } - } -} diff --git a/src/Homework/TeM.java b/src/Homework/TeM.java deleted file mode 100644 index 0d0dc8c..0000000 --- a/src/Homework/TeM.java +++ /dev/null @@ -1,136 +0,0 @@ -package Homework; - -import java.util.HashSet; - -public class TeM { - public static void main(String[] args) { - ReverseString();//Ex.1beglev - ConcatenateStrings();//Ex.3Beglevel - remVowel();//Ex.4Beglev - CapitalizeWordsExample();//Ex.5Beglev - toggledString();//Ex.6Explev - ReplaceLineBreaks();//Ex.4Explev - removeDuplicates();//Ex.2 Mediumlevel - } -//EX:1/Begginer Level - public static void ReverseString() { - //Write a program to reverse an input string using StringBuilder - // Create a StringBuilder object with the input string - StringBuilder str = new StringBuilder("Salutare, lume!"); - - // Reverse the string - StringBuilder reversedStr = str.reverse(); - - // Print the reversed string - System.out.println("Reversed String: " + reversedStr.toString()); - } -//Ex:3/Begginer Level - public static void ConcatenateStrings() { - //Efficiently concatenate multiple strings into one using StringBuilder. - StringBuilder stringBuilder = new StringBuilder(100); - stringBuilder.append("In aceasta"); - stringBuilder.append("zi mare"); - stringBuilder.append(" este sarbatoare!"); - String result = stringBuilder.toString(); - System.out.println(stringBuilder); - } -//Ex:4/Begginer Level - public static void remVowel() { - // Remove all vowels from a string using StringBuilder. - String s = "Prepinsta"; - String s1 = ""; - s1 = s.replace("[aeiou]", ""); - System.out.println("String after removing vowel: " + s1); - - } -//Ex:5/Begginer Level - public static void CapitalizeWordsExample() { -//Capitalize the first letter of every word in a sentence using StringBuilder. - // input string - String input = "welcome to las vegas!"; - - // call the capitalizeWords function and store the result - String result = capitalizeWords(input); - - // print the original and modified strings - System.out.println("Input: " + input); - System.out.println("Output: " + result); - } - - // function to capitalize the first letter of each word - public static String capitalizeWords(String input) { - // split the input string into an array of words - String[] words = input.split("\\s"); - - // StringBuilder to store the result - StringBuilder result = new StringBuilder(); - - // iterate through each word - for (String word : words) { - - // capitalize the first letter, append the rest of the word, and add a space - - result.append(Character.toTitleCase(word.charAt(0))) - .append(word.substring(1)) - .append(" "); - } - - // convert StringBuilder to String and trim leading/trailing spaces - return result.toString().trim(); - } -//Ex:6/ExpertLevel - public static void toggledString() { - // Toggle the case of every character in a string using StringBuilder. - StringBuilder string = new StringBuilder("VIVA LA PATATA!"); - int ln = string.length(); - - for (int i = 0; i < ln; i++) { - Character ch = string.charAt(i); - if (Character.isLowerCase(ch)) - - string.replace(i, i + 1, Character.toUpperCase(ch) + ""); - - else - string.replace(i, i + 1, Character.toLowerCase(ch) + ""); - - System.out.println(string); - } - } - //Replace line breaks from string.//Ex4ExpLevel - public static void ReplaceLineBreaks() { - String a = "Replace\n" - + " all\n" - + " line\n" - + " breaks\n" - + " from\n" - + " strings!"; - System.out.println("Original String line breaks! - " + a); - - - a = a.replace("\n", ""); - System.out.println("String after replacing line breaks - " + a); - } -//Remove duplicate characters from a string using StringBuilder.//Ex:2/Medium - public static void removeDuplicates() { - - String inputString = "Programming"; - System.out.println("Original String: " + inputString); - - - HashSet uniqueChars = new HashSet<>(); - StringBuilder result = new StringBuilder(); - - for (char ch : inputString.toCharArray()) { - if (uniqueChars.add(ch)) { - result.append(ch); - } - System.out.println("String after removing duplicates: " + result); - } - } - -} - - - - - diff --git a/src/Sesion7_APis_UtilityClasses/Main.java b/src/Sesion7_APis_UtilityClasses/Main.java deleted file mode 100644 index 115f3e0..0000000 --- a/src/Sesion7_APis_UtilityClasses/Main.java +++ /dev/null @@ -1,154 +0,0 @@ -package Sesion7_APis_UtilityClasses; - -import javax.swing.*; -import java.io.File; -import java.io.FileNotFoundException; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; - -public class Main { - public static void main(String[] args){ - //demonstrateDateTimeOperations(); - //demonstrationRandomNumberGenerator(); - // demoMath(); - //readFromFileWithScanner(); - //gui(); - } - - public static void gui(){ //interfata grafica - JFrame frame = new JFrame("Gui Example"); - frame.setSize(300, 200); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - JButton button = new JButton("Click me!"); - JLabel label = new JLabel(""); - - button.addActionListener(e-> label.setText("Salut Angelo!")); - - frame.getContentPane().add(button,"North"); - frame.getContentPane().add(label,"Center"); - - frame.setVisible(true); - - - - } - - - - -private static void readFromFileWithScanner(){ - try { - Scanner scanner = new Scanner(new File("example.txt")); - - while (scanner.hasNextLine()){ - - System.out.println("Text: " + scanner.nextLine()); - - } - - scanner.close(); - - } catch(FileNotFoundException e) { - System.out.println("File was not found!!!"); - - } - -} - private static void demoMath(){ - double a = 5.3; - double b = 8.2; - - double max = Math.max(a, b); - System.out.println("Max: " + max); - - long roundedB = Math.round(b); - System.out.println("B rounded:: " + roundedB); - - - } - - - private static void demonstrationRandomNumberGenerator(){ - - System.out.println("=== Random Number Generator ==="); - - Random random = new Random(); - - int randomInt = random.nextInt(100) + 1; //1 to 100 - System.out.println("Random int: " + randomInt); - - double randomDouble = random.nextDouble(); - System.out.println("Random Double: " + randomDouble);// (0-1) - - String[] names = {"Sam", "Ion", "Dan", "Ilie"}; - String theChosen = names[random.nextInt(names.length)]; - System.out.println("Random name: " + theChosen); - - boolean randomBoolean = random.nextBoolean(); - System.out.println("Random bollean: " + randomBoolean); - - List numbers = Arrays.asList(1,2,3,4,5); - Collections.shuffle(numbers, random); - System.out.println("List: " + numbers); - - } - - - - - private static void demonstrateDateTimeOperations(){ - System.out.println("===Date and Time Operations==="); - - LocalDate today = LocalDate.now(); - System.out.println("Today`s date: " + today); - LocalDate tenDaysLater = today.plusDays(10); - System.out.println("Date after 10 days: " + tenDaysLater); - - LocalDateTime currentDateTime = LocalDateTime.now(); - System.out.println("Current date and time: " + currentDateTime); - LocalDateTime futureDateTime = currentDateTime.plusHours(5).plusMinutes(30); - System.out.println("5 hours and 30 min later: " + futureDateTime); - - LocalDateTime futureDate = LocalDateTime.of(2025,1, 1, 10,30); - String result = futureDate.isBefore(LocalDateTime.now()) ? "before" : "after"; - System.out.println(futureDate + " is " + result + " curent date time"); - - //parsing - String dateTimeString = "2025-01-01 10:30"; - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); - LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString,formatter); - System.out.println(" Parsed local date time: " + parsedDateTime); - - DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("dd MMMM yyyy HH:mm:ss"); - System.out.println("New format date time: " + parsedDateTime.format(newFormat)); - - - java.util.Date utilDate = new java.util.Date(); - java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); - - System.out.println("java.util.Date : " + utilDate); - System.out.println("java.sql.Date :" + sqlDate); - - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss"); - String formatedTime = simpleDateFormat.format(utilDate); - System.out.println("Formatted time: " + formatedTime); - - Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis()); - System.out.println("Current Timestamp: " + currentTimestamp); - - Timestamp timestamp1 = Timestamp.valueOf("2024-08-26 18:00:00.123"); - Timestamp timestamp2 = Timestamp.valueOf("2024-08-26 18:03:00.123"); - - long diffInSeconds = (timestamp2.getTime() - timestamp1.getTime()) / 1000; - System.out.println("Diff : " + diffInSeconds); - - - } - - -} diff --git a/src/Sesion_10_OOP_CONCEPTS/Alarm.java b/src/Sesion_10_OOP_CONCEPTS/Alarm.java deleted file mode 100644 index c374e6f..0000000 --- a/src/Sesion_10_OOP_CONCEPTS/Alarm.java +++ /dev/null @@ -1,87 +0,0 @@ -package Sesion_10_OOP_CONCEPTS; - -import java.time.LocalDateTime; - -public sealed class Alarm permits HightVisibilityAlarm, PriotizeAlarm { - private boolean active; - private final String message; - private LocalDateTime snoozeUntil; - - - // Alarm(){ -// message="asdasf"; -// } - - public Alarm(String message) { - this.message = message; - stopSnoozing(); - // this(message,false); - } - - public void setSnoozeUntil(LocalDateTime snoozeUntil) { - this.snoozeUntil = snoozeUntil; - } - - public LocalDateTime getSnoozeUntil() { - return snoozeUntil; - } - - public boolean isActive() { - return active; - } - - public boolean getActive() { - return active; - } - - - public void snoze() { - if (active) - snoozeUntil = LocalDateTime.now().plusSeconds(5); - - } - - public boolean isSnoozing() { - return snoozeUntil.isAfter(LocalDateTime.now()); - } - - - public void stopSnoozing() { - snoozeUntil = LocalDateTime.now().minusSeconds(1); - } - - -// public Alarm(String message,boolean active) { -// this .message = message; -// this.active = active; -// } - - public void turnOn() { - active = true; - } - - public final void turnOff() { - active = false; - stopSnoozing(); - } - - public String getReport() { - - return getReport(false); - - } - - public String getReport(boolean toUppercase) { - if (active && !isSnoozing()) { - if (toUppercase) - return message.toUpperCase(); - else - return message; - } else return ""; - } - - public void sendReport() { - System.out.println(getReport(true)); - } - -} diff --git a/src/Sesion_10_OOP_CONCEPTS/HightVisibilityAlarm.java b/src/Sesion_10_OOP_CONCEPTS/HightVisibilityAlarm.java deleted file mode 100644 index 06268ba..0000000 --- a/src/Sesion_10_OOP_CONCEPTS/HightVisibilityAlarm.java +++ /dev/null @@ -1,37 +0,0 @@ -package Sesion_10_OOP_CONCEPTS; - -public final class HightVisibilityAlarm extends Alarm { - - public HightVisibilityAlarm(String message) { - super(message); - } - - @Override - public String getReport(boolean toUppercase) { -// if (isActive() && !isSnoozing()) { -// if (toUppercase) -// return getMessage().toUpperCase() + "!"; -// else -// return getMessage() + "!"; -// } else return ""; - - String report = super.getReport(toUppercase); - if (report.isEmpty()) - return report; - else - return report + "!"; - - } - - public static void main(String... args) { - HightVisibilityAlarm alarm = new HightVisibilityAlarm("Temperature is to high"); - alarm.turnOn(); - // System.out.println(alarm.getReport(true)); - - alarm.sendReport(); - alarm.turnOff(); - alarm.sendReport(); - } - - -} diff --git a/src/Sesion_10_OOP_CONCEPTS/Main.java b/src/Sesion_10_OOP_CONCEPTS/Main.java deleted file mode 100644 index 7441c1b..0000000 --- a/src/Sesion_10_OOP_CONCEPTS/Main.java +++ /dev/null @@ -1,22 +0,0 @@ -package Sesion_10_OOP_CONCEPTS; - -import java.sql.SQLOutput; - -public class Main { - public static void main(String[] args) throws InterruptedException { - //System.out.println("\nOOP CONCEPTS"); - - Alarm alarm = new Alarm("La fica e tropo calda!"); - // System.out.println(alarm.active); - alarm.turnOn(); - - alarm.snoze(); - // System.out.println("----"); - // alarm.sendReport(); - // Thread.sleep(6000); - // System.out.println(alarm.active); - alarm.sendReport(); - - - } -} diff --git a/src/Sesion_10_OOP_CONCEPTS/PriotizeAlarm.java b/src/Sesion_10_OOP_CONCEPTS/PriotizeAlarm.java deleted file mode 100644 index a445891..0000000 --- a/src/Sesion_10_OOP_CONCEPTS/PriotizeAlarm.java +++ /dev/null @@ -1,22 +0,0 @@ -package Sesion_10_OOP_CONCEPTS; - -public non-sealed class PriotizeAlarm extends Alarm { - private int priority; - - public PriotizeAlarm(String message, int priority) { - super(message); - this.priority = priority; - } - - - public int getPriority() { - return priority; - } - - public static void main(String... args) { - PriotizeAlarm alarm = new PriotizeAlarm("Temperature is to high", 3); - System.out.println(alarm.getPriority()); - - } - -} diff --git a/src/Sesion_12_Abstraction/A.java b/src/Sesion_12_Abstraction/A.java deleted file mode 100644 index a1b782f..0000000 --- a/src/Sesion_12_Abstraction/A.java +++ /dev/null @@ -1,12 +0,0 @@ -package Sesion_12_Abstraction; - -public interface A { - void print(); //public abstract - - default void display(){ - - System.out.println("Default method"); - -} - -} diff --git a/src/Sesion_12_Abstraction/AClass.java b/src/Sesion_12_Abstraction/AClass.java deleted file mode 100644 index 572a59b..0000000 --- a/src/Sesion_12_Abstraction/AClass.java +++ /dev/null @@ -1,14 +0,0 @@ -package Sesion_12_Abstraction; - -public abstract class AClass implements A { - @Override - public void print() { - System.out.println("Salut!"); - } - @Override - public void display(){ - - System.out.println("AClass implementation!"); - } - -} diff --git a/src/Sesion_12_Abstraction/AClassNonabstract.java b/src/Sesion_12_Abstraction/AClassNonabstract.java deleted file mode 100644 index 77d6a42..0000000 --- a/src/Sesion_12_Abstraction/AClassNonabstract.java +++ /dev/null @@ -1,8 +0,0 @@ -package Sesion_12_Abstraction; - -public class AClassNonabstract extends AClass{ - @Override - public void print() { - System.out.println("AClass"); - } -} diff --git a/src/Sesion_12_Abstraction/Animal.java b/src/Sesion_12_Abstraction/Animal.java deleted file mode 100644 index a95d34d..0000000 --- a/src/Sesion_12_Abstraction/Animal.java +++ /dev/null @@ -1,9 +0,0 @@ -package Sesion_12_Abstraction; - -public interface Animal { - - void sound(); - - void eat(); - -} diff --git a/src/Sesion_12_Abstraction/Caine.java b/src/Sesion_12_Abstraction/Caine.java deleted file mode 100644 index d9867ac..0000000 --- a/src/Sesion_12_Abstraction/Caine.java +++ /dev/null @@ -1,20 +0,0 @@ -package Sesion_12_Abstraction; - -public class Caine extends Tetrapods { - - public Caine(String name, int members){ - super(name, members); - } - - @Override - void alearga() { - System.out.println("Alearga pe 4 picioare"); - - } - - @Override - public void sound() { - System.out.println("Face ham ham"); - - } -} diff --git a/src/Sesion_12_Abstraction/Main.java b/src/Sesion_12_Abstraction/Main.java deleted file mode 100644 index f4bf243..0000000 --- a/src/Sesion_12_Abstraction/Main.java +++ /dev/null @@ -1,16 +0,0 @@ -package Sesion_12_Abstraction; - -public class Main { - public static void main(String[] args) { - AClassNonabstract a = new AClassNonabstract(); - a.print(); - a.display(); - - Caine caine = new Caine("Azorel", 4); - caine.alearga(); - caine.eat(); - caine.sound(); - } - - -} diff --git a/src/Sesion_12_Abstraction/Tetrapods.java b/src/Sesion_12_Abstraction/Tetrapods.java deleted file mode 100644 index 496a72c..0000000 --- a/src/Sesion_12_Abstraction/Tetrapods.java +++ /dev/null @@ -1,21 +0,0 @@ -package Sesion_12_Abstraction; - -public abstract class Tetrapods implements Animal { - - private String name; - private int members; - - public Tetrapods(String name, int members) { - this.members = members; - this.name = name; - - } - - @Override - public void eat() { - System.out.println("Eat"); - } - - abstract void alearga(); - -} diff --git a/src/Sesion_13_Polymorphism/Main.java b/src/Sesion_13_Polymorphism/Main.java deleted file mode 100644 index 96cc57c..0000000 --- a/src/Sesion_13_Polymorphism/Main.java +++ /dev/null @@ -1,81 +0,0 @@ -package Sesion_13_Polymorphism; - -public class Main { - public static void main(String... args) { - Animal myAnimal = new Dog();//upcasting ->Animal - //myAnimal.makeSound(); - // myAnimal.sleep(); - - Dog myDog = (Dog) myAnimal;//downcasting Animal-> Dog - myDog.makeSound(5); - - // myDog.fetch(); - // myDog.makeSound(); - doAnimalStuff(myDog); - doAnimalStuff(new Cat()); - - try { - Cat myCat = (Cat) myAnimal; - myCat.makeSound(); - } catch (ClassCastException ex) { - System.out.println("Eroare.Nu putem face downcasting de la caine la pisica "); - } - } - - public static void doAnimalStuff(Animal animal) { - animal.makeSound(); - if (animal instanceof Dog) { - ((Dog) animal).fetch(); - } else if (animal instanceof Cat) { - ((Cat) animal).scratch(); - } - - } - - -} - - -//clasa parinte/superclasa -class Animal { - public void makeSound() { - System.out.println("Generic sound"); - - } - - - public void sleep() { - System.out.println("Sleep"); - } -} -//clasa derivata,(subclasa) - -class Dog extends Animal { - @Override - public void makeSound() { - System.out.println("Cainele face hamham"); - } - public void makeSound(int times) { - for (int i = 0; i < times; i++) - System.out.println("Cainele face ham ham"); - } - - public void fetch() { - System.out.println("cainele aduce mingea"); - } -} - -//clasa derivata/clasa copil/subclasa -class Cat extends Animal { - @Override - public void makeSound() { - System.out.println("pisica face miau miau"); - } -public void makeSound(int times){ -} - - public void scratch() { - System.out.println("pisica zgarie"); - } - -} diff --git a/src/Sesion_13_Polymorphism/PaymentSystem.java b/src/Sesion_13_Polymorphism/PaymentSystem.java deleted file mode 100644 index 8f9f8c9..0000000 --- a/src/Sesion_13_Polymorphism/PaymentSystem.java +++ /dev/null @@ -1,119 +0,0 @@ -package Sesion_13_Polymorphism; - - -//Interfata Payment defineste comportamentele comune pentru toate tipurile de plati -interface Payment { - void processPayment(double amount);//o metoda abstracta pentru procesarea platilor - - void showTransactionDetails(); - -} - -abstract class CardPayment implements Payment { - private String cardNumber; - private String cardHolderName; - - - public CardPayment(String cardNumber, String cardHolderName) { - this.cardNumber = cardNumber; - this.cardHolderName = cardHolderName; - } - - @Override - public void showTransactionDetails() { - System.out.println("Plata realizata cu cardul: " + cardHolderName + "(Card: " + maskCardNumber() + ")"); - - } - - private String maskCardNumber() { - return "**** **** **** " + cardNumber.substring(cardNumber.length() - 4); - - } - - public String getCardHolderName() { - return cardHolderName; - } - -} - -class CreditCardPayment extends CardPayment { - public CreditCardPayment(String cardNumber, String cardHolderName) { - super(cardNumber, cardHolderName); - } - - @Override - public void processPayment(double amount) { - System.out.println("Procesare plata card credit de : " + amount + "pentru " + super.getCardHolderName()); - } -} - -class DebitCardPayment extends CardPayment { - public DebitCardPayment(String cardNumber, String cardHolderName) { - super(cardNumber, cardHolderName); - } - - @Override - public void processPayment(double amount) { - System.out.println("Procesare plata card deb " + amount + "pentru " + super.getCardHolderName()); - } -} - -class BankTransfer implements Payment { - private String iban; - private String bankName; - - public BankTransfer(String iban, String bankName) { - this.iban = iban; - this.bankName = bankName; - } - - @Override - public void processPayment(double amount) { - System.out.println("TransferTransfer bancar de " + amount + "catre IBAN-ul " + iban + "la banca " + bankName); - } - - @Override - public void showTransactionDetails() { - System.out.println("Detalii transfer bancar : Iban " + iban + "Banca: " + bankName); - - } -} - -class CryptoPayment implements Payment { - private String walletAddress; - private String cryptoType; - - public CryptoPayment(String walletAddress, String cryptoType) { - this.cryptoType = cryptoType; - this.walletAddress = walletAddress; - } - - @Override - public void processPayment(double amount) { - System.out.println("Plata de " + amount + " " + cryptoType + " cartre adresa " + walletAddress); - } - - @Override - public void showTransactionDetails() { - System.out.println("Detali plata crypto: " + cryptoType + "wallet: " + walletAddress); - } -} - - -public class PaymentSystem { - public static void main(String... args) { - Payment creditCard = new CreditCardPayment("1234567812345678 ", " Ion Popescu "); - Payment debitCard = new DebitCardPayment("8765432187654321 ", " Maria ionescu "); - Payment bankTransfer = new BankTransfer("RO79btrlro76546789 ", " BT"); - Payment cryptoPayment = new CryptoPayment("ierujsdjf54h32545fh", "Bitcoin "); - - Payment[] payments = {creditCard,debitCard,bankTransfer,cryptoPayment}; - - for(Payment p : payments){ - p.processPayment( 100.0 ); - p.showTransactionDetails(); - System.out.println(); - } - - } -} diff --git a/src/Sesion_14_Recap_OPP/Main.java b/src/Sesion_14_Recap_OPP/Main.java deleted file mode 100644 index bec79ef..0000000 --- a/src/Sesion_14_Recap_OPP/Main.java +++ /dev/null @@ -1,295 +0,0 @@ -package Sesion_14_Recap_OPP; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; - -abstract class Item { - protected String titlu; - protected int anPublicare; - - public Item(String titlu, int anPublicare) { - this.titlu = titlu; - this.anPublicare = anPublicare; - } - - public String getTitlu() { - return titlu; - } - - public int getAnPublicare() { - return anPublicare; - } - - abstract public String getDetalii(); -} - -interface Imprumutabil { - void imprumuta(String numeCititor, LocalDate dataReturnare); - - void returneaza(); - - boolean esteDisponibil(); - - String getNumeCititor(); - - LocalDate getDataReturnare(); -} - -class Carte extends Item implements Imprumutabil { - private String autor; - private boolean disponibil; - private String numeCititor; - private LocalDate dataReturnare; - - public Carte(String titlu, String autor, int anPublicare) { - super(titlu, anPublicare); - this.autor = autor; - this.disponibil = true; - } - - public String getAutor() { - return autor; - } - - @Override - public String getDetalii() { - return "Carte: " + titlu + " de " + autor + " (" + anPublicare + ")"; - } - - @Override - public void imprumuta(String numeCititor, LocalDate dataReturnare) { - this.disponibil = false; - this.numeCititor = numeCititor; - this.dataReturnare = dataReturnare; - } - - @Override - public void returneaza() { - this.disponibil = true; - this.numeCititor = null; - this.dataReturnare = null; - } - - @Override - public boolean esteDisponibil() { - return disponibil; - } - - @Override - public String getNumeCititor() { - return numeCititor; - } - - @Override - public LocalDate getDataReturnare() { - return dataReturnare; - } -} - -class Revista extends Item implements Imprumutabil { - private int numarEditie; - private boolean disponibil; - private String numeCititor; - private LocalDate dataReturnare; - - public Revista(String titlu, int anPublicare, int numarEditie) { - super(titlu, anPublicare); - this.numarEditie = numarEditie; - this.disponibil = true; - } - - public int getNumarEditie() { - return numarEditie; - } - - @Override - public String getDetalii() { - return "Revista: " + titlu + " Nr. " + numarEditie + " (" + anPublicare + ")"; - } - - @Override - public void imprumuta(String numeCititor, LocalDate dataReturnare) { - this.disponibil = false; - this.numeCititor = numeCititor; - this.dataReturnare = dataReturnare; - } - - @Override - public void returneaza() { - this.disponibil = true; - this.numeCititor = null; - this.dataReturnare = null; - } - - @Override - public boolean esteDisponibil() { - return disponibil; - } - - @Override - public String getNumeCititor() { - return numeCititor; - } - - @Override - public LocalDate getDataReturnare() { - return dataReturnare; - } -} - -class Imprumut { - private Imprumutabil item; - private String numeCititor; - private LocalDate dataImprumut; - private LocalDate dataReturnare; - - public Imprumut(Imprumutabil item, String numeCititor, LocalDate dataReturnare) { - this.item = item; - this.numeCititor = numeCititor; - this.dataImprumut = LocalDate.now(); - this.dataReturnare = dataReturnare; - } - - public Imprumutabil getItem() { - return item; - } - - public String getNumeCititor() { - return numeCititor; - } - - public LocalDate getDataImprumut() { - return dataImprumut; - } - - public LocalDate getDataReturnare() { - return dataReturnare; - } - - @Override - public String toString() { - return "Împrumut: " + ((Item) item).getTitlu() + " de către " + numeCititor + - " (Împrumutat: " + dataImprumut + ", Returnare: " + dataReturnare + ")"; - } -} - -class Biblioteca { - private List items; - private List imprumuturi; - - public Biblioteca() { - this.items = new ArrayList<>(); - this.imprumuturi = new ArrayList<>(); - } - - public void adaugaItem(Item item) { - items.add(item); - } - - public void eliminaItem(Item item) { - items.remove(item); - } - - public Item cautaDupaTitlu(String titlu) { - for (Item item : items) { - if (item.getTitlu().equalsIgnoreCase(titlu)) { - return item; - } - } - return null; - } - - public List cautaDupaAutor(String autor) { - List rezultate = new ArrayList<>(); - for (Item item : items) { - if (item instanceof Carte && ((Carte) item).getAutor().equalsIgnoreCase(autor)) { - rezultate.add(item); - } - } - return rezultate; - } - - public void afiseazaToateElementele() { - for (Item item : items) { - System.out.println(item.getDetalii() + " - Disponibil: " + - (item instanceof Imprumutabil ? ((Imprumutabil) item).esteDisponibil() : "N/A")); - } - } - - public void imprumutaItem(Item item, String numeCititor, LocalDate dataReturnare) { - if (item instanceof Imprumutabil) { - Imprumutabil imprumutabil = (Imprumutabil) item; - if (imprumutabil.esteDisponibil()) { - imprumutabil.imprumuta(numeCititor, dataReturnare); - imprumuturi.add(new Imprumut(imprumutabil, numeCititor, dataReturnare)); - System.out.println("Item împrumutat cu succes: " + item.getTitlu()); - } else { - System.out.println("Item-ul nu este disponibil pentru împrumut: " + item.getTitlu()); - } - } else { - System.out.println("Acest item nu poate fi împrumutat: " + item.getTitlu()); - } - } - - public void returneazaItem(Item item) { - if (item instanceof Imprumutabil) { - Imprumutabil imprumutabil = (Imprumutabil) item; - if (!imprumutabil.esteDisponibil()) { - imprumutabil.returneaza(); - imprumuturi.removeIf(imprumut -> imprumut.getItem() == imprumutabil); - System.out.println("Item returnat cu succes: " + item.getTitlu()); - } else { - System.out.println("Acest item nu a fost împrumutat: " + item.getTitlu()); - } - } else { - System.out.println("Acest item nu poate fi returnat: " + item.getTitlu()); - } - } - - public void afiseazaImprumuturi() { - if (imprumuturi.isEmpty()) { - System.out.println("Nu există împrumuturi active."); - } else { - System.out.println("Împrumuturi active:"); - for (Imprumut imprumut : imprumuturi) { - System.out.println(imprumut); - } - } - } -} - -public class Main { - public static void main(String[] args) { - Biblioteca biblioteca = new Biblioteca(); - - Carte carte1 = new Carte("Mândrie și prejudecată", "Jane Austen", 1813); - Carte carte2 = new Carte("1984", "George Orwell", 1949); - Revista revista1 = new Revista("National Geographic", 2023, 1); - - biblioteca.adaugaItem(carte1); - biblioteca.adaugaItem(carte2); - biblioteca.adaugaItem(revista1); - - System.out.println("Toate elementele din bibliotecă:"); - biblioteca.afiseazaToateElementele(); - - System.out.println("\nÎmprumutarea cărții '1984':"); - biblioteca.imprumutaItem(carte2, "Ion Popescu", LocalDate.now().plusWeeks(2)); - - System.out.println("\nÎmprumutarea revistei 'National Geographic':"); - biblioteca.imprumutaItem(revista1, "Maria Ionescu", LocalDate.now().plusWeeks(1)); - - System.out.println("\nToate elementele după împrumut:"); - biblioteca.afiseazaToateElementele(); - - System.out.println("\nAfișarea împrumuturilor active:"); - biblioteca.afiseazaImprumuturi(); - - System.out.println("\nReturnarea cărții '1984':"); - biblioteca.returneazaItem(carte2); - - System.out.println("\nAfișarea împrumuturilor active după returnare:"); - biblioteca.afiseazaImprumuturi(); - } -} \ No newline at end of file diff --git a/src/Sesion_15_CollectionsFramework/ComparatorMunte.java b/src/Sesion_15_CollectionsFramework/ComparatorMunte.java deleted file mode 100644 index f35cf37..0000000 --- a/src/Sesion_15_CollectionsFramework/ComparatorMunte.java +++ /dev/null @@ -1,11 +0,0 @@ -package Sesion_15_CollectionsFramework; - -import java.util.Comparator; - -public class ComparatorMunte implements Comparator { - - @Override - public int compare(Munte o1, Munte o2) { - return o1.getNume().compareTo(o2.getNume()); - } -} diff --git a/src/Sesion_15_CollectionsFramework/Main.java b/src/Sesion_15_CollectionsFramework/Main.java deleted file mode 100644 index 8653979..0000000 --- a/src/Sesion_15_CollectionsFramework/Main.java +++ /dev/null @@ -1,42 +0,0 @@ -package Sesion_15_CollectionsFramework; - -import java.util.*; - -public class Main { - public static void main(String[] args) { - List fructe = new ArrayList<>(Arrays.asList("mar", "banana", "portocala", "pruna")); - - for (String fruct : fructe) { - System.out.println(fruct); - // if(fruct.equals("banana")){ - // fructe.remove(fruct); - // } - } - - //itnterator - Iterator iterator = fructe.iterator(); - - while (iterator.hasNext()) { - String fruct = iterator.next(); - System.out.println("Fruct: " + fruct); - if (fruct.equals("banana")) { - iterator.remove(); - } - } - System.out.println("Lista dupa stergere: " + fructe); - - - List munti = new ArrayList<>(); - munti.add(new Munte("Everest", 8840)); - munti.add(new Munte("K2", 8644)); - munti.add(new Munte("Makalu", 8300)); - - System.out.println("Munti initial: " + munti); - Collections.sort(munti); - - System.out.println("Munti dupa sort: " + munti); - Collections.sort(munti, new ComparatorMunte()); - - System.out.println("Munti dupa sortare nume: " + munti); - } -} diff --git a/src/Sesion_15_CollectionsFramework/MapsExample.java b/src/Sesion_15_CollectionsFramework/MapsExample.java deleted file mode 100644 index dccec13..0000000 --- a/src/Sesion_15_CollectionsFramework/MapsExample.java +++ /dev/null @@ -1,50 +0,0 @@ -package Sesion_15_CollectionsFramework; - -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; - -public class MapsExample { - public static void main(String... args) { - Map hasMap = new HashMap<>(); - Map treeMap = new TreeMap<>(); - - hasMap.put("Romania", 20000000); - hasMap.put("Germania", 85000000); - hasMap.put("Franta", 6600600); - - - treeMap.put("Romania", 2000000); - treeMap.put("Germania", 8500000); - treeMap.put("Franta", 6600600); - - System.out.println("hasMap" + hasMap); - System.out.println("treemap" + treeMap); - - //print contains - System.out.println("Contains Romania: " + hasMap.containsKey("Romania")); - System.out.println("Contains 2000000" + treeMap.containsValue(2000000)); - - - for (String key : hasMap.keySet()) { - System.out.println("Key : " + key + " - value " + hasMap.get(key)); - } - -//+ var mapentri string intiger - for (Map.Entry entry : treeMap.entrySet()) { - System.out.println("Key: " + entry.getKey() + " - value " + entry.getValue()); - } -//update - hasMap.put("Romania", 1980000); - System.out.println(hasMap); - - TreeMap tree = new TreeMap<>(treeMap); - - System.out.println("Prima intrare: " + tree.firstEntry()); - System.out.println("Ultima intrare: " + tree.lastEntry()); - System.out.println("Intrare inferioara Germania: " + tree.lowerEntry("Germania")); - System.out.println("Intrare superioara Germania: " + tree.higherEntry("Germania")); - - - } -} diff --git a/src/Sesion_15_CollectionsFramework/Munte.java b/src/Sesion_15_CollectionsFramework/Munte.java deleted file mode 100644 index fbb2903..0000000 --- a/src/Sesion_15_CollectionsFramework/Munte.java +++ /dev/null @@ -1,31 +0,0 @@ -package Sesion_15_CollectionsFramework; - -public class Munte implements Comparable { - private String nume; - private int inaltime; - - - public Munte(String n, int i) { - this.nume = n; - this.inaltime = i; - } - - public String getInaltime() { - return nume; - - } - - public String getNume() { - return getNume(); - } - - @Override - public int compareTo(Munte o) { - return Integer.compare(this.inaltime, o.inaltime); - } - - @Override - public String toString() { - return nume + " (" + inaltime + "m)"; - } -} diff --git a/src/Sesion_15_CollectionsFramework/SetExamples.java b/src/Sesion_15_CollectionsFramework/SetExamples.java deleted file mode 100644 index db844a1..0000000 --- a/src/Sesion_15_CollectionsFramework/SetExamples.java +++ /dev/null @@ -1,51 +0,0 @@ -package Sesion_15_CollectionsFramework; - -import java.util.HashSet; -import java.util.Set; -import java.util.TreeSet; - -public class SetExamples { - public static void main(String[] args) { - Set hashSet = new HashSet<>(); - Set treeSet = new TreeSet<>(); - - addElement(hashSet, " Ion"); - addElement(hashSet, " Sam"); - addElement(hashSet, " Dan"); - addElement(hashSet, " Bob"); - addElement(hashSet, " Ion"); - - - //========================================= - - addElement(treeSet, " Ion"); - addElement(treeSet, " Sam"); - addElement(treeSet, " Dan"); - addElement(treeSet, " Bob"); - addElement(treeSet, " Ion"); - - - //display sets - System.out.println("HashSet: " + hashSet); - System.out.println("TreeSet: " + treeSet); - - String nume = "Ion"; - System.out.println("HashMap contains: " + nume + "?" + hashSet.contains(nume)); - System.out.println("Treset contains: " + nume + "?" + treeSet.contains(nume)); - - - boolean removed = hashSet.remove(nume); - System.out.println("Removeing: " + nume + " - " + (removed ? " success " : "not fund")); - - boolean removed1 = hashSet.remove(nume); - System.out.println("Removeing: " + nume + " - " + (removed1 ? " success " : " not fund")); - - } - - private static void addElement(Set set, String element) { - boolean added = set.add(element); - System.out.println(set.getClass().getSimpleName() + " : Adding" + element + " " + (added ? "Succes " : " Duplicate")); - } - - -} diff --git a/src/Sesion_16_Equals_HasCodeGenericsEnum/Animal.java b/src/Sesion_16_Equals_HasCodeGenericsEnum/Animal.java deleted file mode 100644 index 1815756..0000000 --- a/src/Sesion_16_Equals_HasCodeGenericsEnum/Animal.java +++ /dev/null @@ -1,5 +0,0 @@ -package Sesion_16_Equals_HasCodeGenericsEnum; - -public interface Animal { - void sound(); -} diff --git a/src/Sesion_16_Equals_HasCodeGenericsEnum/Cat.java b/src/Sesion_16_Equals_HasCodeGenericsEnum/Cat.java deleted file mode 100644 index 47c3eaa..0000000 --- a/src/Sesion_16_Equals_HasCodeGenericsEnum/Cat.java +++ /dev/null @@ -1,13 +0,0 @@ -package Sesion_16_Equals_HasCodeGenericsEnum; - -public class Cat implements Animal { - @Override - public void sound() { - System.out.println("miau miau"); - } - - @Override - public String toString() { - return "pisica face miau miau"; - } -} diff --git a/src/Sesion_16_Equals_HasCodeGenericsEnum/Dog.java b/src/Sesion_16_Equals_HasCodeGenericsEnum/Dog.java deleted file mode 100644 index e5b2b9f..0000000 --- a/src/Sesion_16_Equals_HasCodeGenericsEnum/Dog.java +++ /dev/null @@ -1,13 +0,0 @@ -package Sesion_16_Equals_HasCodeGenericsEnum; - -public class Dog implements Animal { - @Override - public void sound() { - System.out.println("ham ham"); - } - - @Override - public String toString() { - return "Cainele face ham ham"; - } -} diff --git a/src/Sesion_16_Equals_HasCodeGenericsEnum/IntegerPrinter.java b/src/Sesion_16_Equals_HasCodeGenericsEnum/IntegerPrinter.java deleted file mode 100644 index 2846665..0000000 --- a/src/Sesion_16_Equals_HasCodeGenericsEnum/IntegerPrinter.java +++ /dev/null @@ -1,13 +0,0 @@ -package Sesion_16_Equals_HasCodeGenericsEnum; - -public class IntegerPrinter { - private int thingToPrint; - - public IntegerPrinter(int thingToPrint) { - this.thingToPrint = thingToPrint; - } - - public void print() { - System.out.println(thingToPrint); - } -} diff --git a/src/Sesion_16_Equals_HasCodeGenericsEnum/Main.java b/src/Sesion_16_Equals_HasCodeGenericsEnum/Main.java deleted file mode 100644 index aaa0b5e..0000000 --- a/src/Sesion_16_Equals_HasCodeGenericsEnum/Main.java +++ /dev/null @@ -1,82 +0,0 @@ -package Sesion_16_Equals_HasCodeGenericsEnum; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class Main { - public static void main(String... args) { -// equalsExamples(); - genericExamples(); - } - - public static void genericExamples() { - IntegerPrinter integerPrinter = new IntegerPrinter(5); - integerPrinter.print(); - - StringPrinter stringPrinter = new StringPrinter("bla bal"); - stringPrinter.print(); - -// Printer intPrinter = new Printer<>(52); -// Printer strPrinter = new Printer<>("ha ha"); -// intPrinter.print(); -// strPrinter.print(); - - Printer catPrinter = new Printer<>(new Cat()); - catPrinter.print(); - - Printer dogPrinter = new Printer<>(new Dog()); - dogPrinter.print(); - - - ArrayList catList = new ArrayList<>(); - catList.add(new Cat()); - -// Cat cat = catList.get(0); - - print(2, "hihi"); - - List intList = new ArrayList<>(); - intList.add(6); - -// printList(intList); - printListWhildcard(intList); - printListWhildcard(catList); - - printListWhildcard2(catList); - } - - //metoda generica cu 2 parametrii - public static void print(T p1, E p2) { - System.out.println("p1: " + p1 + " p2: " + p2); - } - - public static void printList(List list) { - System.out.println(list); - } - - public static void printListWhildcard(List list) { - System.out.println(list); - } - - public static void printListWhildcard2(List list) { - System.out.println(list); - } - - public static void equalsExamples() { - Persoana p1 = new Persoana("Ion", 30); - Persoana p2 = new Persoana("Ion", 30); - Persoana p3 = new Persoana("Maria", 25); - - System.out.println("p1 equals p2: " + p1.equals(p2)); - System.out.println("p1 equals p3: " + p1.equals(p3)); - - Set set = new HashSet<>(); - System.out.println("Adauga p1: " + set.add(p1)); - System.out.println("Adauga p2: " + set.add(p2)); - System.out.println("Adauga p3: " + set.add(p3)); - - System.out.println("Set size: " + set.size()); - } -} diff --git a/src/Sesion_16_Equals_HasCodeGenericsEnum/Persoana.java b/src/Sesion_16_Equals_HasCodeGenericsEnum/Persoana.java deleted file mode 100644 index a9ebaa5..0000000 --- a/src/Sesion_16_Equals_HasCodeGenericsEnum/Persoana.java +++ /dev/null @@ -1,39 +0,0 @@ -package Sesion_16_Equals_HasCodeGenericsEnum; - -import java.util.Objects; - -public class Persoana { - private String nume; - private int age; - //ce se intampla daca am si o adresa de tip Adresa??? - - - public Persoana(String name, int age) { - this.nume = name; - this.age = age; - } - - @Override - public boolean equals(Object o) { - //Verificam daca parametrul metodei este null - if (o == null) { - return false; - } - //Verificam daca referintele sunt egale - if (o == this) { - return true; - } - //Verificam tipul obiectului sa fie persoana - if (!(o instanceof Persoana)) - return false; - //Facem un cast de la Object la Persoana - Persoana persoana = (Persoana) o; - - return persoana.age == this.age && Objects.equals(this.nume, persoana.nume); - } - - @Override - public int hashCode() { - return Objects.hash(nume, age); - } -} diff --git a/src/Sesion_16_Equals_HasCodeGenericsEnum/Printer.java b/src/Sesion_16_Equals_HasCodeGenericsEnum/Printer.java deleted file mode 100644 index 060ca98..0000000 --- a/src/Sesion_16_Equals_HasCodeGenericsEnum/Printer.java +++ /dev/null @@ -1,15 +0,0 @@ -package Sesion_16_Equals_HasCodeGenericsEnum; - - -public class Printer { - private T thingToPrint; - - public Printer(T thingToPrint) { - this.thingToPrint = thingToPrint; - } - - public void print() { - thingToPrint.sound(); - System.out.println(thingToPrint); - } -} diff --git a/src/Sesion_16_Equals_HasCodeGenericsEnum/StringPrinter.java b/src/Sesion_16_Equals_HasCodeGenericsEnum/StringPrinter.java deleted file mode 100644 index 1d3856b..0000000 --- a/src/Sesion_16_Equals_HasCodeGenericsEnum/StringPrinter.java +++ /dev/null @@ -1,13 +0,0 @@ -package Sesion_16_Equals_HasCodeGenericsEnum; - -public class StringPrinter { - private String thingToPrint; - - public StringPrinter(String thingToPrint) { - this.thingToPrint = thingToPrint; - } - - public void print() { - System.out.println(thingToPrint); - } -} diff --git a/src/Sesion_1_JavaSetup_JavaBasic/Calc.java b/src/Sesion_1_JavaSetup_JavaBasic/Calc.java deleted file mode 100644 index 4032233..0000000 --- a/src/Sesion_1_JavaSetup_JavaBasic/Calc.java +++ /dev/null @@ -1,27 +0,0 @@ -package Sesion_1_JavaSetup_JavaBasic; - -public class Calc { - public static void main(String[] args) { - - int val1 = 10; - int val2 = 5; - int rez; - char op = 'M'; - - if (op == 'A') - rez = val1 + val2; - else if (op == 'S') - rez = val1 - val2; - else if (op == 'D') { - rez = val1 / val2; - } else if (op == 'M') { - rez = val1 * val2; - } else { - System.out.println("else"); - rez = 0; - - System.out.println("REZ = " + rez); - } - } - -} \ No newline at end of file diff --git a/src/Sesion_1_JavaSetup_JavaBasic/Code2.java b/src/Sesion_1_JavaSetup_JavaBasic/Code2.java deleted file mode 100644 index 4f9c111..0000000 --- a/src/Sesion_1_JavaSetup_JavaBasic/Code2.java +++ /dev/null @@ -1,45 +0,0 @@ -package Sesion_1_JavaSetup_JavaBasic; - -public class Code2 { - public static void main(String[] args) { - -// -// float floatVal = 1.0f; -// double doubleVal = 4.0; -// byte byteVal = 7; -// short shortVal = 7; -// long longVal = 5; -// long longVal2 = 513157145134615l; -// -// short rez1 = byteVal; -// -// //byte -> short -> int -> long -// // float -> double -// -// short rez2 = (short) longVal; -// short rez3 = (short) longVal2; -// System.out.println("rez3 = " + rez3); -// -// long rez4 = (long) (longVal - floatVal);// float la inceput -// System.out.println("rez4 = " + rez4); - - - int a = 2; - int b = 3; - int c = 4; - -// a += b; //9 -// a += b * 2; // 14 -// a += c * b - 5; -// System.out.println(" A = " + a); - - a *= c * 2 + 2; // 48 fara 2 dupa 56 prima 12+2 -14*4 =56 - System.out.println("a = " + a); - -// b *= a-- + ++c * 2; -// System.out.println("b = " + b); // 36 - - - - } -} \ No newline at end of file diff --git a/src/Sesion_1_JavaSetup_JavaBasic/Code3.java b/src/Sesion_1_JavaSetup_JavaBasic/Code3.java deleted file mode 100644 index af26af9..0000000 --- a/src/Sesion_1_JavaSetup_JavaBasic/Code3.java +++ /dev/null @@ -1,31 +0,0 @@ -package Sesion_1_JavaSetup_JavaBasic; - -public class Code3 { - public static void main (String[] args){ - - boolean bollVal = false; - System.out.println("bollVal = " + bollVal); - System.out.println(!bollVal); - - - //var = bool exp ? rez adevarat : rez neg ; - - int a = !(3 < 5) ? 4 : 5; - - String name = "Sam"; - - int age = name.equals("Sam") ? 30: 40; - System.out.println("Sam has " + age + "years"); - - int valA = 3; - int valB = 3; - - if(valA < valB) { - System.out.println("First number is less then second one"); - valB++; - }else if (valB < valA) - System.out.println("Second number is less than first one"); - else - System.out.println("Numbers are equals!"); - } -} diff --git a/src/Sesion_1_JavaSetup_JavaBasic/Main.java b/src/Sesion_1_JavaSetup_JavaBasic/Main.java deleted file mode 100644 index fc3622b..0000000 --- a/src/Sesion_1_JavaSetup_JavaBasic/Main.java +++ /dev/null @@ -1,9 +0,0 @@ -package Sesion_1_JavaSetup_JavaBasic; - -public class Main { - public static void main(String[] args) { - - - System.out.println("Salve!"); - } -} \ No newline at end of file diff --git a/src/Sesion_1_JavaSetup_JavaBasic/clasrom.java b/src/Sesion_1_JavaSetup_JavaBasic/clasrom.java deleted file mode 100644 index 92e2858..0000000 --- a/src/Sesion_1_JavaSetup_JavaBasic/clasrom.java +++ /dev/null @@ -1,22 +0,0 @@ -package Sesion_1_JavaSetup_JavaBasic; - -public class clasrom { - public static void main(String[] args){ - int students = 150; - int rooms = 0;//4 - - - - //& && - - if(rooms != 0 && students / rooms > 30) - System.out.println("Crowded!"); - - - System.out.println("*** end of program ***"); - - - - } - -} diff --git a/src/Sesion_3_JavaOperators/Challenge b/src/Sesion_3_JavaOperators/Challenge deleted file mode 100644 index 8f8b724..0000000 --- a/src/Sesion_3_JavaOperators/Challenge +++ /dev/null @@ -1,54 +0,0 @@ -1. Write a Java program where you create two String objects named stringOne and stringTwo with the same value "OpenAI". Check and print whether they refer to the same object. - -2. Write a Java program to declare two integer variables firstNumber and secondNumber with any values. Use an equality operator to compare these two numbers and print the result. Do the same for two String objects firstString and secondString with the same value, but use the equals() method for comparison. Print the result. - -3. Write a Java program that declares an integer variable age with a value of 20. Print a statement saying "I am adult" if age is 18 or more, else print "I am not an adult". - -4. Write a Java program where you declare two integer variables heightOne and heightTwo with any values. Use a ternary operator to determine the greater height and assign it to a variable maximumHeight. Print the result. - -5. Write a Java program to print the numbers from 1 to 10 using a for loop. As a next step, modify your program to print only the even numbers from 1 to 10. - -6. Write a Java program where you declare an integer variable temperature. Assign a value to it and print "Hot" if the temperature is more than 30, "Warm" if the temperature is between 20 and 30, and "Cold" if it's less than 20. - -7. Write a Java program that determines the type of a triangle based on its sides. Declare three variables sideOne, sideTwo and sideThree to represent the sides of the triangle. Use the ternary operator to determine and print whether the triangle is "Equilateral", "Isosceles", or "Scalene". - -8. Write a Java program to calculate the factorial of a number using a for loop. Declare an integer variable number and assign a value to it. Then calculate and print the factorial of number. - -9. Write a Java program to create two String variables, countryOne with the value "USA" and countryTwo with the value "USA". Check if countryOne and countryTwo are equal using the equals() method and print the result. Then change the value of countryTwo to "UK" and check for equality again. Print the result. - - -10. Write a Java program that creates two distinct ArrayList objects, listOne and listTwo. Add some elements to listOne and assign listOne to listTwo. Now modify listOne by adding a new element. Print both lists and observe the output. - -11. Write a Java program where you declare four integer variables: a, b, c, and d. Assign them values of 10, 20, 30, and 40 respectively. Create two more variables additionResult and multiplicationResult. Set additionResult to the sum of a and b and multiplicationResult to the product of c and d. Print the values of additionResult and multiplicationResult. - -12. Write a Java program where you declare an integer variable number with a value of 25. Use unary minus operator to change the sign of number and assign it to a variable negativeNumber. Print the values of number and negativeNumber. - -13. Write a Java program where you declare two boolean variables isRaining and isSunny with values of true and false, respectively. Use the logical complement operator to negate the values of both variables and print the new values. - -14. Write a Java program where you declare an integer variable counter with a value of 0. Use the increment operator to increase the value of counter by 1 and then print the value. After that, use the decrement operator to decrease the value of counter by 1 and then print the value. - -15. Write a Java program where you declare an integer variable total with a value of 100. Use the compound assignment operator to decrease the total by 20 and then print the value. Next, use another compound assignment operator to multiply the total by 2 and then print the value. - -16. Write a Java program where you use unary operators to perform a series of transformations on an integer variable number initialized to 50. First, negate number, then take the absolute value, and finally increment it by 1. Print the result at each step. - -17. Write a Java program that simulates a simple authentication system. Declare a boolean variable hasUsername and hasPassword. Set up a series of logical conditions using these two variables that will check the following conditions: - - -If both hasUsername and hasPassword are true, print "Authentication successful". - -If either hasUsername or hasPassword is false, print "Authentication failed". - -If hasUsername is true but hasPassword is false, print "Password is incorrect". - -18. Write a Java program where you declare an integer array with 5 elements. Use a for loop to initialize the array such that each element is equal to its index incremented by 1. Then use another for loop to decrement each element by 1. Print the array before and after the decrement operation using a for-each loop. - -19. Write a Java program that takes an integer variable age as input. Use a ternary operator to classify the person into one of the following categories: "Child" (age < 12), "Teenager" (age between 12 and 17), "Adult" (age between 18 and 64), and "Senior" (age 65 and above). Print the resulting classification. - -20. Write a Java program that takes three integer variables a, b, and c as input. Use nested ternary operators to find and print the largest number among the three. - -21. Write a Java program that takes a double variable score representing a student’s score on a test. Use a ternary operator to classify the score into letter grades A, B, C, D, or F according to the following scale: - - -A: 90-100 - -B: 80-89 - -C: 70-79 - -D: 60-69 - -F: 0-59 - -Print the resulting letter grade. diff --git a/src/Sesion_3_JavaOperators/Homework.java b/src/Sesion_3_JavaOperators/Homework.java deleted file mode 100644 index c29a06c..0000000 --- a/src/Sesion_3_JavaOperators/Homework.java +++ /dev/null @@ -1,15 +0,0 @@ -package Sesion_3_JavaOperators; - -public class Homework { - public static void main(String [] args) { - //Number 1 - String stringOne = "OpenAI"; - String stringTwo = "OpenAI"; - - // Check if they refer to the same object - boolean areSameObject = (stringOne == stringTwo); - - System.out.println("Are stringOne and stringTwo the same object? " + areSameObject); - } -} - diff --git a/src/Sesion_3_JavaOperators/Questions b/src/Sesion_3_JavaOperators/Questions deleted file mode 100644 index aa7a214..0000000 --- a/src/Sesion_3_JavaOperators/Questions +++ /dev/null @@ -1,11 +0,0 @@ -I.What is a Stack and a Queue? Ho do they work and when are used? -Stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. - Queue is a container of objects (a linear collection) that are inserted and removed according to - the first-in first-out (FIFO) principle. - - - - -II.What is the difference between for and for enhanced? When I should use one or another? -Use the traditional for loop when you need explicit control over the iteration, need to modify the elements, or do not iterate over an array or collection. -Use the enhanced for loop for simplicity and readability when you simply need to access each element of an array or collection without modifying them. \ No newline at end of file diff --git a/src/Sesion_4_Java_op_decision/Main.java b/src/Sesion_4_Java_op_decision/Main.java deleted file mode 100644 index 4b05900..0000000 --- a/src/Sesion_4_Java_op_decision/Main.java +++ /dev/null @@ -1,64 +0,0 @@ -package Sesion_4_Java_op_decision; - -import java.util.Scanner; - -public class Main { - public static void main(String[] args) { - // Commented out unused methods for now -// sum(5, 6); -// Chestii_Utile_Futuro.Main main = new Chestii_Utile_Futuro.Main(); -// int x = main.sum2(3, 6); -// equality(); - -// objectEquality(); // Commented out object equality example - - Scanner scanner = new Scanner(System.in); - System.out.println("Nr:"); // Nr is likely a typo for "Number" - int x = scanner.nextInt(); - ex3(x); - } - - private static void ex3(int x) { - // Replaced if-else with ternary operator for cleaner syntax - String result = (x > 0) ? "positive" : (x == 0) ? "0" : "negative"; - System.out.println("result = " + result); - } - - private static void objectEquality() { - // Demonstrates how object reference comparison works - Person pers1 = new Person("Sam"); - Person pers2 = new Person("Ion"); - - Person pers3 = pers1; // pers3 now points to the same object as pers1 - - System.out.println(pers1 == pers2); //false - different objects - System.out.println(pers1 == pers3); //true - both point to the same object - } - - private static void equality() { - // Demonstrates basic comparison operators - int a = 5; - int b = 10; - - System.out.println(a == b); //false - checks if values are equal - System.out.println(a != b); //true - checks if values are not equal - } - - private static void sum(int a, int b) { - System.out.println("Sum: " + (a + b)); - } - - public int sum2(int a, int b) { - // This method returns the sum of a and b - return a + b; - } -} - -class Person { - String name; - - Person(String name) { - this.name = name; - } -} - diff --git a/src/Sesion_5_AdvanceFlowControl/IfAndSwitch.java b/src/Sesion_5_AdvanceFlowControl/IfAndSwitch.java deleted file mode 100644 index c0dd58c..0000000 --- a/src/Sesion_5_AdvanceFlowControl/IfAndSwitch.java +++ /dev/null @@ -1,81 +0,0 @@ -package Sesion_5_AdvanceFlowControl; - -import java.util.Scanner; - - public class IfAndSwitch { - - public static void main(String[] args) { - daysOfWeekWithIf(); - dayOfWeekWithSwitch(); - -// for (ZileleSaptamani zi : ZileleSaptamani.values()) { -// System.out.println(zi); -// } - - -// ZileleSaptamani duminica = ZileleSaptamani.DUMINICA; -// -// switch (duminica) { -// case LUNI, MARTI, MIERCURI, JOI, VINERI -> System.out.println("Nu e weekend!"); -// default -> System.out.println("E weekend!"); -// } - -// int age = 25; -// if (age < 7) { -// System.out.println("Child"); -// } else if (age < 18) { -// System.out.println("Teenager"); -// } else System.out.println("Adult"); - - int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - for (int i : array) { - if (i % 2 == 0) - continue; - System.out.println("NR: " + i); - } - } - - - public static void daysOfWeekWithIf() { - Scanner scanner = new Scanner(System.in); - System.out.println("Introduce day of week (1-7):"); - int day = scanner.nextInt(); - - if (day == 1) { - System.out.println("Luni"); - } else if (day == 2) { - System.out.println("Marti"); - } else if (day == 3) { - System.out.println("Miercuri"); - } else if (day == 4) { - System.out.println("Joi"); - } else if (day == 5) { - System.out.println("Vineri"); - } else if (day == 6) { - System.out.println("Sambata"); - } else if (day == 7) { - System.out.println("Duminica"); - } else { - System.out.println("Numar invalid!"); - } - } - - public static void dayOfWeekWithSwitch() { - Scanner scanner = new Scanner(System.in); - System.out.println("Introduce day of week (1-7):"); - int day = scanner.nextInt(); - - switch (day) { - case 1 -> System.out.println("Luni"); - case 2 -> System.out.println("Marti"); - case 5 -> System.out.println("Vineri"); - case 4 -> System.out.println("Joi"); - default -> System.out.println("Numar invalid!"); - case 6 -> System.out.println("Sambata"); - case 3 -> System.out.println("Miercuri"); - case 7 -> System.out.println("Duminica"); - } - - } - - } \ No newline at end of file diff --git a/src/Sesion_5_AdvanceFlowControl/Main.java b/src/Sesion_5_AdvanceFlowControl/Main.java deleted file mode 100644 index c4de359..0000000 --- a/src/Sesion_5_AdvanceFlowControl/Main.java +++ /dev/null @@ -1,93 +0,0 @@ -package Sesion_5_AdvanceFlowControl; - -public class Main { -// public static void main(String[] args) { -// -// // whileExampleWithContinue(); -// //nestedForExample(); -//// nestedForExampleWIthoutLbel(); -//// boolean bol = nestedForExampleWithReturn(); -//// if(bol) { -//// System.out.println("Found it!"); -//// } else System.out.println("Value not found!"); -// doWhileExample(); -// -// System.out.println("DONE!"); -// } -// -// private static void doWhileExample() { -// Scanner scanner = new Scanner(System.in); -// int number; -// do { -// System.out.println("Introduce a positive number:"); -// number = scanner.nextInt(); -// -// } while (number <= 0); -// } -// -// private static void whileExampleWithContinue(){ -// int i = 0; -// int sum = 0; -// -// while(i<=4){ -// if(i == 3){ -// i++; -// continue; -// } -// sum += i; -// i++; -// } -// System.out.println("Sum = " + sum); -// } -//private static void nestedForExample(){ -// int[][] matrix = {{1, 2, 3},{4 , 5, 6},{7 ,8 , 9}}; -// int searchval = 5; -// SEARCH: -// for(int i = 0; i arrayList = new ArrayList<>(); - arrayList.add("Sam"); - arrayList.add("Ion"); - arrayList.add("Bob"); - arrayList.add("Iov"); - - List linkedList = new LinkedList<>(); - linkedList.add("Sam"); - linkedList.add("Ion"); - linkedList.add("Bob"); - linkedList.add("Iov"); - - //get element - System.out.println(arrayList.get(2));//bob - System.out.println(linkedList.get(2)); - - //add value - arrayList.add(1, "Sara"); - linkedList.add(1, "Sara"); - - //{Sam,Ion,Bob,Ion} - //{Sam,Sara,Ion,Bob,Ion} - - //remove - arrayList.remove(1); - linkedList.remove("Sara"); - - //stack implementation(Lifo) - LinkedList stack = new LinkedList<>(); - stack.push("A"); - stack.push("B"); - stack.push("C"); - stack.pop(); - - //offer() / poll() - - System.out.println(stack); - - - arrayListVsLinkedList(); - //conversions(); - - - } -private static void conversions() { - ArrayList arrayList = new ArrayList<>(); - arrayList.add("A"); - arrayList.add("B"); - arrayList.add("C"); - - // String[] arrayFromArrayList = (String[]) arrayList.toArray(); - String[] arrayFromArrayList = arrayList.toArray(new String[0]); - System.out.println(arrayList); - System.out.println(Arrays.toString(arrayFromArrayList)); - -//v1 - List fromArray = Arrays.asList(arrayFromArrayList);//can change the value ,cannot delete/add - fromArray.set(0, "Z"); - System.out.println(fromArray); - System.out.println(fromArray); - - //v2 - List fromArray2 = List.of(arrayFromArrayList); //lista imutabila - // fromArray2.set(1, "ewe"); - - //v3 - List fromArray3 = new ArrayList<>(Arrays.asList(arrayFromArrayList)); - System.out.println(fromArray3); - System.out.println(Arrays.toString(arrayFromArrayList)); - - fromArray3.set(1, "T"); - System.out.println(fromArray3); - System.out.println(Arrays.toString(arrayFromArrayList)); - - - -} - public static void arrayListVsLinkedList() { - //declareation - List arrayList = new ArrayList<>(); - List linkedList = new LinkedList<>(); - - - //add ellements - - for (int i = 0; i < 500000; i++) { - arrayList.add(String.valueOf(i)); - linkedList.add(String.valueOf(i)); - - } - long startArrayTime = System.currentTimeMillis(); - for (int i = 0; i < 10000; i++) { - // arrayList.add(0, String.valueOf(i)); - arrayList.get(250000); - } - long endArrayTime = System.currentTimeMillis(); - - System.out.println("ArrayList time: " + (endArrayTime - startArrayTime)); - - long startLinkedListTime = System.currentTimeMillis(); - for (int i = 0; i < 10000; i++) { - // linkedList.add(0, String.valueOf(1)); - linkedList.get(250000); - } - long endLinkedListTime = System.currentTimeMillis(); - - System.out.println("LinkedList time: " + (endLinkedListTime - startLinkedListTime)); - } - -} - diff --git a/src/Sesion_8_Arrays_and__ArrayList/ArrayVsArrayList.java b/src/Sesion_8_Arrays_and__ArrayList/ArrayVsArrayList.java deleted file mode 100644 index 63f4482..0000000 --- a/src/Sesion_8_Arrays_and__ArrayList/ArrayVsArrayList.java +++ /dev/null @@ -1,47 +0,0 @@ -package Sesion_8_Arrays_and__ArrayList; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class ArrayVsArrayList { - public static void main(String[] args){ - System.out.println("===Arrays vs ArrayList and Wrapper Classes==="); - - - //declare - String[] friendArray = {"Sam", "Dan","Ion", "Bob"}; - - List friendArrayList = new ArrayList<>(Arrays.asList("Sam", "Dan" ,"Ion", "Bob")); - //[0][1][2][3] - //get value - System.out.println(friendArray[1]); - System.out.println(friendArrayList.get(1)); - - //size - System.out.println(friendArray.length);//campul lenght - System.out.println(friendArrayList.size());//metoda size - - //add value - friendArrayList.add("Pavel"); - System.out.println(friendArrayList.get(4)); - - //set value - friendArray[1] = "Maia"; - System.out.println(friendArray[1]); - friendArrayList.set(1,"Maia"); - System.out.println(friendArrayList.get(1)); - - //remove - friendArrayList.remove("Maia"); - System.out.println(friendArrayList.get(1)); - - //print all - System.out.println(Arrays.toString(friendArray)); - System.out.println(friendArrayList); - - - - - } -} diff --git a/src/Sesion_9_RecapItuLaRe/Main.java b/src/Sesion_9_RecapItuLaRe/Main.java deleted file mode 100644 index 6e77af4..0000000 --- a/src/Sesion_9_RecapItuLaRe/Main.java +++ /dev/null @@ -1,44 +0,0 @@ -package Sesion_9_RecapItuLaRe; - -//public class Main { - // public static void main(String[] args) { - // System.out.println("\nRecapitulare a sesiunilor anterioare, 1-8!=="); - -// //EX..1 -// int x = 5; -// System.out.println(x++ + ++x);//12rez 5 + 7 -// //EX..2 -// String str = "Hello"; -// str.concat(" World");// -// System.out.println(str);//Just Hello -// //EX..3 -// int[] numbers = {1, 2, 3, 4, 5}; -// System.out.println(numbers[5]);//array indexoutofboundexception -// //EX..4 -// LocalTime time = LocalTime.of(23, 59); -// System.out.println(time.plusMinutes(1));//00 -// //EX..5 -// ArrayList list = new ArrayList<>(); -// list.add(1); -// list.add(2); -// list.add(1, 3); -// System.out.println(list);//1,3,2 -// //EX..6 -// int x = 5; -// System.out.println(x > 3 ? x < 4 ? "A" : "B" : "C");//b -// //EX..7 -// int[] arr = {1, 2, 3, 4, 5}; -// for (int i = 0; i < arr.length - 2; i += 2) { -// System.out.println(arr[i] + " ");////1-3rez -// //EX..8 -// String s = "1"; -// s += 2; -// s += 3.0; -// -// System.out.println(s); -// 123.0 -// -// -// } -// -// } diff --git a/src/Session_11_Encapsulation_vs_Inheritance/Appliance.java b/src/Session_11_Encapsulation_vs_Inheritance/Appliance.java deleted file mode 100644 index 93ddc28..0000000 --- a/src/Session_11_Encapsulation_vs_Inheritance/Appliance.java +++ /dev/null @@ -1,45 +0,0 @@ -package Session_11_Encapsulation_vs_Inheritance; - -public class Appliance { - String brand = "Generic"; - - Appliance() { - System.out.println("Appliance is created"); - } - - void function() { - System.out.println("Appliance is functioning"); - } -} - -class Refrigerator extends Appliance { - String brand = "Arctic"; - - Refrigerator() { - super(); - System.out.println("Refrigerator is created"); - } - - void function() { - System.out.println("Refrigerator is cooling"); - } - - void work() { - function(); - super.function(); - } - - void displayBrand() { - System.out.println("Refrigerator brand: " + brand); - System.out.println("Appliance brand: " + super.brand); - } - -} - -class TestRefrigerator { - public static void main(String... args) { - Refrigerator ref = new Refrigerator(); - ref.displayBrand(); - ref.work(); - } -} \ No newline at end of file diff --git a/src/Session_11_Encapsulation_vs_Inheritance/Main.java b/src/Session_11_Encapsulation_vs_Inheritance/Main.java deleted file mode 100644 index 93cbeaf..0000000 --- a/src/Session_11_Encapsulation_vs_Inheritance/Main.java +++ /dev/null @@ -1,16 +0,0 @@ -package Session_11_Encapsulation_vs_Inheritance; - -public class Main { - public static void main(String[] args) { - Person person = new Person(); - person.setFirstName("John"); - person.setLastName("Doe"); - person.setAge(25); - - System.out.println("Name: " + person.getFirstName() + " " + person.getLastName()); - System.out.println("Age: " + person.getAge()); - - person.setAge(-20); - - } -} \ No newline at end of file diff --git a/src/Session_11_Encapsulation_vs_Inheritance/Person.java b/src/Session_11_Encapsulation_vs_Inheritance/Person.java deleted file mode 100644 index b15b403..0000000 --- a/src/Session_11_Encapsulation_vs_Inheritance/Person.java +++ /dev/null @@ -1,35 +0,0 @@ -package Session_11_Encapsulation_vs_Inheritance; - -public class Person { - private String firstName; - private String lastName; - private int age; - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - if (age < 0) { - System.out.println("Age cannot be negative or 0"); - } else { - this.age = age; - } - } -} \ No newline at end of file diff --git a/src/Session_11_Encapsulation_vs_Inheritance/TrickyClass.java b/src/Session_11_Encapsulation_vs_Inheritance/TrickyClass.java deleted file mode 100644 index 0ba040d..0000000 --- a/src/Session_11_Encapsulation_vs_Inheritance/TrickyClass.java +++ /dev/null @@ -1,29 +0,0 @@ -package Session_11_Encapsulation_vs_Inheritance; - -public class TrickyClass { - int x; - - TrickyClass(int x) { - this.x = x; - } - - TrickyClass(TrickyClass other) { - this(other.x); - } - - void method(int x) { - this.x += x; - } - - void method(TrickyClass other) { - method(other.x); - } - - public static void main(String... args){ - TrickyClass obj1 = new TrickyClass(5); - TrickyClass obj2 = new TrickyClass(obj1); - obj1.method(3); - obj2.method(obj1); - System.out.println(obj1.x + " " + obj2.x); - } -} \ No newline at end of file diff --git a/src/Session_17_lambda/Animal.java b/src/Session_17_lambda/Animal.java deleted file mode 100644 index a1031df..0000000 --- a/src/Session_17_lambda/Animal.java +++ /dev/null @@ -1,7 +0,0 @@ -package Session_17_lambda; - -public class Animal { - public void makeSound() { - System.out.println("bla bla bla"); - } -} diff --git a/src/Session_17_lambda/AnonimousClassEx.java b/src/Session_17_lambda/AnonimousClassEx.java deleted file mode 100644 index c1bba4d..0000000 --- a/src/Session_17_lambda/AnonimousClassEx.java +++ /dev/null @@ -1,21 +0,0 @@ -package Session_17_lambda; - -public class AnonimousClassEx { - public static void main(String... args) { - Animal animal = new Animal(); - animal.makeSound(); - - - //clasa anonima, in cazul asta va fi o clasa fara nume dar va reprezenta un caine - Animal anonimAnimal = new Animal(){ - @Override - public void makeSound() { - System.out.println("ham ham"); - } - }; - - anonimAnimal.makeSound(); - - - } -} diff --git a/src/Session_17_lambda/AnonymousVsLambda.java b/src/Session_17_lambda/AnonymousVsLambda.java deleted file mode 100644 index 624a735..0000000 --- a/src/Session_17_lambda/AnonymousVsLambda.java +++ /dev/null @@ -1,34 +0,0 @@ -package Session_17_lambda; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -public class AnonymousVsLambda { - public static void main(String... args) { - List list = new ArrayList<>(); - list.add("a"); - list.add("d"); - list.add("b"); - list.add("c"); - - Collections.sort(list, new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.compareTo(o2); - } - }); - - System.out.println("Sorted list: " + list); - Collections.shuffle(list); - System.out.println("Shuffled list: " + list); - - Comparator com = (o1, o2) -> o1.compareTo(o2); - - Collections.sort(list, com); - - System.out.println("Sorted list: " + list); - - } -} diff --git a/src/Session_17_lambda/Calculator.java b/src/Session_17_lambda/Calculator.java deleted file mode 100644 index 9f9063a..0000000 --- a/src/Session_17_lambda/Calculator.java +++ /dev/null @@ -1,5 +0,0 @@ -package Session_17_lambda; - -public interface Calculator { - double calculate(double a, double b, char operator); -} diff --git a/src/Session_17_lambda/LambdaExamples.java b/src/Session_17_lambda/LambdaExamples.java deleted file mode 100644 index 68475e3..0000000 --- a/src/Session_17_lambda/LambdaExamples.java +++ /dev/null @@ -1,42 +0,0 @@ -package Session_17_lambda; - -public class LambdaExamples { - public static void main(String... args) { - Printable printable = s -> { - System.out.println("salut"); - return "ciau" + s; - }; - - printThing(printable); -// printThing(() -> System.out.println("salut")); - - StringProcessor removeWhitespaces = str -> str.replace(" ", ""); - StringProcessor toUpperCase = str -> str.toUpperCase(); - - StringProcessor combined = removeWhitespaces.andThen(toUpperCase); - - System.out.println(combined.process("hello world")); - - - Calculator calculator = (a, b, operator) -> calcImpl(a,b,operator); - - System.out.println(calculator.calculate(3, 5, '+')); - } - - public static double calcImpl(double a, double b, char op){ - switch (op) { - case '+': - return a + b; - case '-': - return a - b; - case '*': - return a * b; - default: - return a / b; - } - } - - public static void printThing(Printable print) { - System.out.println(print.print("!")); - } -} diff --git a/src/Session_17_lambda/Printable.java b/src/Session_17_lambda/Printable.java deleted file mode 100644 index d075fe6..0000000 --- a/src/Session_17_lambda/Printable.java +++ /dev/null @@ -1,10 +0,0 @@ -package Session_17_lambda; - -@FunctionalInterface -public interface Printable { - String print(String p1); - - default void faAltceva(){ - System.out.println("fa altceva!"); - } -} diff --git a/src/Session_17_lambda/StringProcessor.java b/src/Session_17_lambda/StringProcessor.java deleted file mode 100644 index 2d0e42f..0000000 --- a/src/Session_17_lambda/StringProcessor.java +++ /dev/null @@ -1,10 +0,0 @@ -package Session_17_lambda; - -@FunctionalInterface -public interface StringProcessor { - String process(String str); - - default StringProcessor andThen(StringProcessor after) { - return input -> after.process(this.process(input)); - } -} diff --git a/src/Session_18_JavaStreams/Main.java b/src/Session_18_JavaStreams/Main.java deleted file mode 100644 index d73f93e..0000000 --- a/src/Session_18_JavaStreams/Main.java +++ /dev/null @@ -1,7 +0,0 @@ -package Session_18_JavaStreams; - -public class Main { - public static void main (String[] args){ - - } -} diff --git a/src/Session_18_JavaStreams/OptionalExamples.java b/src/Session_18_JavaStreams/OptionalExamples.java deleted file mode 100644 index 5c6922c..0000000 --- a/src/Session_18_JavaStreams/OptionalExamples.java +++ /dev/null @@ -1,43 +0,0 @@ -package Session_18_JavaStreams; - -import java.util.Optional; - -public class OptionalExamples { - public static void main(String... args) { - Person person = getPersonByName("Ion"); - - if (person != null) - System.out.println("age: " + person.getAge()); - else - System.out.println("age: " + 0); - - - Optional optionalPerson = getOptionalPersonByName("Dana"); - if (optionalPerson.isPresent()) - System.out.println("age: " + optionalPerson.get().getAge()); - else - System.out.println("age: " + 0); - - - int age = optionalPerson.map(Person::getAge).orElse(0); - System.out.println("age: " + age); - - Person pers = optionalPerson.orElseGet(() -> new Person("UNKNOWN", 0)); - System.out.println("Pers age: " + pers.getAge()); - - //daca vrem exceptie cand nu este valoare do this -// optionalPerson.orElseThrow() - - - } - - public static Person getPersonByName(String name) { -// return new Person(name, 25); - return null; - } - - public static Optional getOptionalPersonByName(String name) { - return Optional.ofNullable(null); - } - -} \ No newline at end of file diff --git a/src/Session_18_JavaStreams/Person.java b/src/Session_18_JavaStreams/Person.java deleted file mode 100644 index 3505d3d..0000000 --- a/src/Session_18_JavaStreams/Person.java +++ /dev/null @@ -1,32 +0,0 @@ -package Session_18_JavaStreams; - -import java.util.List; - -public class Person { - private String name; - private int age; - private List hobbies; - - - public Person(String name, int age) { - this.name = name; - this.age = age; - } - - public Person(String name, List hobbies) { - this.name = name; - this.hobbies = hobbies; - } - - public int getAge() { - return age; - } - - public String getName() { - return name; - } - - public List getHobbies() { - return hobbies; - } -} \ No newline at end of file diff --git a/src/Session_18_JavaStreams/StreamExamples.java b/src/Session_18_JavaStreams/StreamExamples.java deleted file mode 100644 index 4a2f758..0000000 --- a/src/Session_18_JavaStreams/StreamExamples.java +++ /dev/null @@ -1,44 +0,0 @@ -package Session_18_JavaStreams; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -public class StreamExamples { - public static void main(String... args) { - List strignList = Arrays.asList("a", "b", "c"); - Stream stringListStream = strignList.stream(); - - Map map = new HashMap<>(); - map.put("Ana", 25); - map.put("Ion", 30); - - Stream keyStream = map.keySet().stream(); - Stream valStream = map.values().stream(); - - //----------------------------------------------------------------------- - - int[] nr = {1, 2, 3, 4, 5}; - IntStream nrStream = Arrays.stream(nr); - - //------------------------------------------------------------------------- - - Stream customStream = Stream.of("a", "b", "c"); - - //------------------------------------------------------------------------- - - try (Stream lines = Files.lines(Path.of("example.txt"))) { - lines.forEach(System.out::println); - } catch (IOException ex) { - ex.printStackTrace(); - } - - - } -} \ No newline at end of file diff --git a/src/Session_18_JavaStreams/StreamImplExamples.java b/src/Session_18_JavaStreams/StreamImplExamples.java deleted file mode 100644 index 0d26e35..0000000 --- a/src/Session_18_JavaStreams/StreamImplExamples.java +++ /dev/null @@ -1,68 +0,0 @@ -package Session_18_JavaStreams; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class StreamImplExamples { - public static void main(String... args) { - filterOddNumbers(); - flatMapExample(); - concatenateListOfStrings(); - calculateAVG(); - } - - private static void calculateAVG() { - List numbers = Arrays.asList(10, 20, 30, 40); - - double avg = numbers.stream() - .mapToInt(Integer::intValue) - .average() - .orElse(0); - - System.out.println(avg); - } - - private static void concatenateListOfStrings() { - List words = Arrays.asList("apple", "banana", "orange"); - - String result = words.stream() - .collect(Collectors.joining(", ")); - - System.out.println(result); - } - - private static void flatMapExample() { - List people = Arrays.asList( - new Person("Bob", Arrays.asList("cititul", "mancatul")), - new Person("Ana", Arrays.asList("plimbare", "gaming")) - ); - - //Obtinem un stream cu liste de hobiuri - Stream> hobbyList = people.stream().map(Person::getHobbies); - // Apelam streamu-ul de liste si il concatenam intr-un stream de strings cu flatMap - Stream hobbies = hobbyList.flatMap(List::stream); - hobbies.forEach(System.out::println); - } - - public static void filterOddNumbers() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - //before - - List oddNumbers = new ArrayList<>(); - for (Integer nr : numbers) { - if (nr % 2 == 0) - oddNumbers.add(nr); - } - - System.out.println("Odd numbers: " + oddNumbers); - - //@formatter:off - List streamOddList = numbers.stream() - .filter(n -> n % 2 == 0) - .toList(); - //@formatter:on - } -} \ No newline at end of file diff --git a/src/Studi/AgeValidation.java b/src/Studi/AgeValidation.java deleted file mode 100644 index ce8a80d..0000000 --- a/src/Studi/AgeValidation.java +++ /dev/null @@ -1,48 +0,0 @@ -package Studi; - -import java.util.Scanner; - -// Custom checked exception for invalid age -class InvalidAgeException extends Exception { - public InvalidAgeException(String message) { - super(message); - } -} - -public class AgeValidation { - - // Method to validate age - public static void validateAge(int age) throws InvalidAgeException { - if (age < 0 || age > 110) { - throw new InvalidAgeException("Age must be between 0 and 110."); - } - } - - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - - try { - // Prompt the user to enter their age - System.out.print("Enter your age: "); - int age = Integer.parseInt(scanner.nextLine()); - - // Validate the age - validateAge(age); - - // Display a success message if no exception is thrown - System.out.println("Age is valid."); - - } catch (InvalidAgeException e) { - // Handle the InvalidAgeException - System.out.println("Error: " + e.getMessage()); - } catch (NumberFormatException e) { - // Handle invalid number format - System.out.println("Invalid input. Please enter a valid number."); - } catch (Exception e) { - // Handle any other unexpected exceptions - System.out.println("An unexpected error occurred: " + e.getMessage()); - } - - scanner.close(); - } -} diff --git a/src/Studi/Calculator.java b/src/Studi/Calculator.java deleted file mode 100644 index 651dddc..0000000 --- a/src/Studi/Calculator.java +++ /dev/null @@ -1,60 +0,0 @@ -package Studi; - -import java.util.Scanner; - -public class Calculator { - - // Method to perform the calculation - public static double calculate(double operand1, double operand2, char operator) { - switch (operator) { - case '+': - return operand1 + operand2; - case '-': - return operand1 - operand2; - case '*': - return operand1 * operand2; - case '/': - if (operand2 == 0) { - throw new ArithmeticException("Division by zero is not allowed."); - } - return operand1 / operand2; - default: - throw new IllegalArgumentException("Invalid operator: " + operator); - } - } - - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - - try { - // Prompt the user to enter the first number - System.out.print("Enter the first number: "); - double num1 = Double.parseDouble(scanner.nextLine()); - - // Prompt the user to enter the second number - System.out.print("Enter the second number: "); - double num2 = Double.parseDouble(scanner.nextLine()); - - // Prompt the user to enter the operator - System.out.print("Enter the operator (+, -, *, /): "); - char operator = scanner.nextLine().charAt(0); - - // Perform the calculation - double result = calculate(num1, num2, operator); - - // Display the result - System.out.println("The result is: " + result); - - } catch (NumberFormatException e) { - System.out.println("Invalid number format. Please enter valid numbers."); - } catch (ArithmeticException e) { - System.out.println("Error: " + e.getMessage()); - } catch (IllegalArgumentException e) { - System.out.println("Error: " + e.getMessage()); - } catch (Exception e) { - System.out.println("An unexpected error occurred: " + e.getMessage()); - } - - scanner.close(); - } -} diff --git a/src/Studi/FileCopyUtility.java b/src/Studi/FileCopyUtility.java deleted file mode 100644 index 9e9992d..0000000 --- a/src/Studi/FileCopyUtility.java +++ /dev/null @@ -1,52 +0,0 @@ -package Studi; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Scanner; -import java.io.FileNotFoundException; - -public class FileCopyUtility { - - // Method to copy the contents of the source file to the destination file - public static void copyFile(String sourcePath, String destinationPath) { - try (FileInputStream fis = new FileInputStream(sourcePath); - FileOutputStream fos = new FileOutputStream(destinationPath)) { - - byte[] buffer = new byte[1024]; - int bytesRead; - - // Read from source and write to destination - while ((bytesRead = fis.read(buffer)) != -1) { - fos.write(buffer, 0, bytesRead); - } - - } catch (FileNotFoundException e) { - System.out.println("Source file not found: " + e.getMessage()); - } catch (IOException e) { - System.out.println("Error occurred while copying the file: " + e.getMessage()); - } - } - - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - - try { - // Prompt the user to enter the source file path - System.out.print("Enter the source file path: "); - String sourcePath = scanner.nextLine(); - - // Prompt the user to enter the destination file path - System.out.print("Enter the destination file path: "); - String destinationPath = scanner.nextLine(); - - // Call the copyFile method - copyFile(sourcePath, destinationPath); - - } catch (Exception e) { - System.out.println("An unexpected error occurred: " + e.getMessage()); - } - - scanner.close(); - } -} diff --git a/src/Studi/probs.java b/src/Studi/probs.java deleted file mode 100644 index b91dcdd..0000000 --- a/src/Studi/probs.java +++ /dev/null @@ -1,20 +0,0 @@ -package Studi; - -import java.time.DateTimeException; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Date; - -public class probs { - public static void main(String[] args) { - //System.out.println("Incercari de depasire a cunostintei! "); - tim(); - } - public static void tim(){ - Date curentDate = new Date(); - System.out.println("Date " + curentDate ); - - - } - -} diff --git a/src/TeamWorks/DoNotGamble.java b/src/TeamWorks/DoNotGamble.java deleted file mode 100644 index 2dfefd9..0000000 --- a/src/TeamWorks/DoNotGamble.java +++ /dev/null @@ -1,73 +0,0 @@ -package TeamWorks; - -import java.util.DoubleSummaryStatistics; -import java.util.Random; -import java.util.Scanner; - -public class DoNotGamble { - static private final double HIGH_MATCH = 51.0; - static private final double LOW_MATCH = 49.0; - - private static class Game { - private final Random rng = new Random(); - private final Scanner inputScanner = new Scanner(System.in); - private int pocketChange = 5_00; // In cents - private int bankBalance = 100_00; - DoubleSummaryStatistics playerStats = new DoubleSummaryStatistics(); - DoubleSummaryStatistics bankStats = new DoubleSummaryStatistics(); - - private void exitTheCasino() { - System.out.println("========================="); - System.out.println("Felicitari!!! Ai plecat din cazino cu bani!!@#$!"); - System.out.printf("Balans: %.2f %n", moneyToDouble(pocketChange)); - System.out.printf("Player Stats; \t\t Maini Jucate: %d, Medie Balans: %.2f, Suma Jucata: %.2f, Top Balance: %.2f %n", playerStats.getCount(), playerStats.getAverage(), playerStats.getSum(), playerStats.getMax()); - System.out.printf("Bank Stats: \t\t Maini Jucate: %d, Medie Balans: %.2f, Suma Jucata: %.2f, Top Balance: %.2f %n", bankStats.getCount(), bankStats.getAverage(), bankStats.getSum(), bankStats.getMax()); - System.exit(1); - } - - private double moneyToDouble(int value) { - return value / 100.0; - } - - private void run() { - while (pocketChange > 0) { - boolean choice = false; - System.out.printf("Balans$: %.2f Ce alegi? +(mare) -(mic) X(exit) [+/-/X]: ", moneyToDouble(pocketChange)); - String line = inputScanner.nextLine().trim().toLowerCase(); - - switch (line) { - case "+" -> choice = true; - case "x" -> exitTheCasino(); - } - - double luckyNumber = rng.nextDouble(100.0); - boolean isWin = (luckyNumber > HIGH_MATCH && choice) || (luckyNumber < LOW_MATCH && !choice); - System.out.printf("Alegerea ta: %s \t\t\t Numarul Norocos: %.2f %n", choice ? "MARE" : "mic", luckyNumber); - - if (isWin) { - pocketChange += 1_00; - bankBalance -= 1_00; - System.out.printf("Ai CASTIGAT 1 credit.\t\t Ramas: %.2f Bank: %.2f %n", moneyToDouble(pocketChange), moneyToDouble(bankBalance)); - } else { - pocketChange -= 1_00; - bankBalance += 1_00; - System.out.printf("Ai PIERDUT 1 credit. \t\t Ramas: %.2f Bank: %.2f %n", moneyToDouble(pocketChange), moneyToDouble(bankBalance)); - } - playerStats.accept(moneyToDouble(pocketChange)); - bankStats.accept(moneyToDouble(pocketChange)); - } - System.out.println("========================="); - System.out.println("Ai pierdut, du-te la ATM!"); - System.out.printf("Player Stats; \t\t Maini Jucate: %d, Medie Balans: %.2f, Suma Jucata: %.2f, Top Balance: %.2f %n", playerStats.getCount(), playerStats.getAverage(), playerStats.getSum(), playerStats.getMax()); - System.out.printf("Bank Stats: \t\t Maini Jucate: %d, Medie Balans: %.2f, Suma Jucata: %.2f, Top Balance: %.2f %n", bankStats.getCount(), bankStats.getAverage(), bankStats.getSum(), bankStats.getMax()); - - } - } - - - public static void main(String[] args) { - new Game().run(); - } - -} - diff --git a/src/TeamWorks/GuessTheNumber.java b/src/TeamWorks/GuessTheNumber.java deleted file mode 100644 index 6622fb4..0000000 --- a/src/TeamWorks/GuessTheNumber.java +++ /dev/null @@ -1,68 +0,0 @@ -import java.util.*; - -public class GuessTheNumber { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - Random random = new Random(); - Map playerScores = new HashMap<>(); - boolean playAgain; - - do { - System.out.print(" Introdu numele tău: "); - String playerName = scanner.next(); - - int maxAttempts = 10; - int numberToGuess = random.nextInt(100) + 1; - int userGuess = 0; - int attempts = 0; - int score = maxAttempts; - - System.out.println("Am generat un număr între 1 și 100. Încearcă să-l ghicești!"); - System.out.println("Ai " + maxAttempts + " încercări."); - - while (userGuess != numberToGuess && attempts < maxAttempts) { - System.out.print(" Introdu un număr: "); - userGuess = scanner.nextInt(); - attempts++; - - if (userGuess < numberToGuess) { - System.out.println("Prea mic! Încearcă un număr mai mare."); - } else if (userGuess > numberToGuess) { - System.out.println("Prea mare! Încearcă un număr mai mic."); - } else { - System.out.println("Felicitări! Ai ghicit numărul în " + attempts + " încercări."); - score = maxAttempts - attempts + 1; - } - - if (userGuess != numberToGuess) { - int attemptsLeft = maxAttempts - attempts; - System.out.println("Încercări rămase: " + attemptsLeft); - } - } - - if (userGuess == numberToGuess) { - System.out.println("Scorul tău pentru această rundă este: " + score); - } else { - System.out.println("Ai epuizat toate încercările. Numărul corect era: " + numberToGuess); - System.out.println("Mai mult noroc data viitoare!"); - score = 0; // Scor 0 dacă nu a ghicit numărul - } - - // Adăugare scor la scorul total al jucătorului - playerScores.put(playerName, playerScores.getOrDefault(playerName, 0) + score); - - // Afișare clasament actualizat - System.out.println("\nClasamentul actual:"); - playerScores.entrySet().stream() - .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) - .forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue() + " puncte")); - - System.out.print("\nVrei să joci din nou? (da/nu): "); - String response = scanner.next(); - playAgain = response.equalsIgnoreCase("da"); - - } while (playAgain); - - System.out.println("Mulțumim că ai jucat!"); - } -} \ No newline at end of file diff --git a/src/TeamWorks/Joc.java b/src/TeamWorks/Joc.java deleted file mode 100644 index be4a775..0000000 --- a/src/TeamWorks/Joc.java +++ /dev/null @@ -1,43 +0,0 @@ -package TeamWorks; - -import java.util.Random; -import java.util.Scanner; - -public class Joc { - public static void main(String[] args) { - System.out.println("Jocul"); - - Scanner scanner = new Scanner(System.in); - String alegere; - do { - Joc(scanner); - System.out.println("Daca vrei sa mai joci scrie Da."); - alegere = scanner.nextLine(); - } while (alegere.equals("Da")); - - - } - - public static void Joc(Scanner scanner) { - Random random = new Random(); - int number = random.nextInt(100) + 1; - boolean guessedNumber = false; - while (!guessedNumber) { - System.out.println("Guess Number: "); - int userNumber = scanner.nextInt(); - if (userNumber == number) { - guessedNumber = true; - continue; - } - - if (userNumber < number) - System.out.println("Numarul este mai mare!"); - else - System.out.println("Numarul este mai mic!"); - - - } - System.out.println("Felicitari"); - } - -} diff --git a/src/TemeAbstraction/AbstractClass.java b/src/TemeAbstraction/AbstractClass.java deleted file mode 100644 index 55438e1..0000000 --- a/src/TemeAbstraction/AbstractClass.java +++ /dev/null @@ -1,19 +0,0 @@ -package TemeAbstraction; - -abstract class AbstractClass { - public AbstractClass() { - System.out.println("This is constructor of abstract class!"); - } - - abstract void a_method(); - - void normal_method() { - System.out.println("This is a normal method of abstract class!"); - } -} - -class SubClass extends AbstractClass { - void a_method() { - System.out.println("This is abstract method!"); - } -} diff --git a/src/TemeAbstraction/Ani.java b/src/TemeAbstraction/Ani.java deleted file mode 100644 index 1e503fa..0000000 --- a/src/TemeAbstraction/Ani.java +++ /dev/null @@ -1,32 +0,0 @@ -package TemeAbstraction; - -abstract class Ani { - abstract void cats(); - - abstract void dogs(); -} - -class Cat extends Ani { - @Override - void cats() { - System.out.println("Cats meow"); - } - - @Override - void dogs() { - - } -} - - -class Dog extends Ani { - @Override - void dogs() { - System.out.println("Dogs bark"); - } - - @Override - void cats() { - - } -} diff --git a/src/TemeAbstraction/BankAccount.java b/src/TemeAbstraction/BankAccount.java deleted file mode 100644 index a4a649a..0000000 --- a/src/TemeAbstraction/BankAccount.java +++ /dev/null @@ -1,29 +0,0 @@ -package TemeAbstraction; - -abstract class Bank { - abstract int getBalance(); -} - -class BankA extends Bank { - @Override - int getBalance() { - return 100; - } -} - -class BankB extends Bank { - @Override - int getBalance() { - return 150; - } -} - -class BankC extends Bank { - @Override - int getBalance() { - - return 200; - - } -} - diff --git a/src/TemeAbstraction/Main.java b/src/TemeAbstraction/Main.java deleted file mode 100644 index be2a230..0000000 --- a/src/TemeAbstraction/Main.java +++ /dev/null @@ -1,72 +0,0 @@ -package TemeAbstraction; - -public class Main { - public static void runParentExample() { - Parent obj1 = new FirstSubClass(); - obj1.message(); - - - - Parent obj2 = new FirstSubClass(); - obj2.message(); - } - - public static void main(String[] args) { - System.out.println("\nRun Parent example!"); - runParentExample(); - System.out.println("\nRun Bank example!"); - runBankExample(); - System.out.println("Run Animal(Ani) example!"); - runAniExample(); - System.out.println("\nRun Marks example!"); - runMarksExample(); - System.out.println("\nRun Abstract example!"); - abstractClass(); - System.out.println("\nRun Shape example!"); - } - - public static void runBankExample() { - Bank bankA = new BankA(); - System.out.println("Balance in Bank A: $" + bankA.getBalance()); - - Bank bankB = new BankB(); - System.out.println("Balance in Bank B: $" + bankB.getBalance()); - - Bank bankC = new BankC(); - System.out.println("Balance in Bank C: $" + bankC.getBalance()); - } - - public static void runAniExample() { - Ani cat = new Cat(); - cat.cats(); - Ani dog = new Dog(); - dog.dogs(); - - } - - public static void runMarksExample() { - a studentA = new a(85, 90, 80); - System.out.println("Percentage of Student A: " + studentA.getPercentage() + "%"); - - b studentB = new b(75, 85, 90, 88); - System.out.println("Percentage of Student B: " + studentB.getPercentage() + "%"); - } - - public static void abstractClass() { - SubClass obj = new SubClass(); - obj.a_method(); - obj.normal_method(); - } - - public static void shapeClass() { - Area area = new Area(); - double length = 5; - double breadth = 3; - double side = 4; - double radius = 2; - System.out.println("Area of Rectangle: " + area.rectangleArea(length, breadth)); - System.out.println("Area of Square: " + area.squareArea(side)); - System.out.println("Area of Circle: " + area.circleArea(radius)); - } - -} diff --git a/src/TemeAbstraction/Marks.java b/src/TemeAbstraction/Marks.java deleted file mode 100644 index c8e8222..0000000 --- a/src/TemeAbstraction/Marks.java +++ /dev/null @@ -1,41 +0,0 @@ -package TemeAbstraction; - -abstract class Marks { - abstract double getPercentage(); -} - -class a extends Marks { - - private int mark1, mark2, mark3; - - public a(int mark1, int mark2, int mark3) { - this.mark1 = mark1; - this.mark2 = mark2; - this.mark3 = mark3; - - } - - @Override - double getPercentage() { - - int total = mark1 + mark2 + mark3; - return (total / 300.0) * 100; - } -} - -class b extends Marks { - private int mark1, mark2, mark3, mark4; - - public b(int mark1, int mark2, int mark3, int mark4) { - this.mark1 = mark1; - this.mark2 = mark2; - this.mark3 = mark3; - this.mark4 = mark4; - } - - @Override - double getPercentage() { - int total = mark1 + mark2 + mark3 + mark4; - return (total / 400.0) * 100; - } -} diff --git a/src/TemeAbstraction/Parent.java b/src/TemeAbstraction/Parent.java deleted file mode 100644 index 62a6047..0000000 --- a/src/TemeAbstraction/Parent.java +++ /dev/null @@ -1,20 +0,0 @@ -package TemeAbstraction; - -public abstract class Parent { - abstract void message(); -} - -class FirstSubClass extends Parent { - @Override - void message() { - System.out.println("This is first subclass!"); - } - - class SecondSubClass extends Parent { - @Override - void message() { - System.out.println("This is second subclass!"); - } - } -} - diff --git a/src/TemeAbstraction/Shape.java b/src/TemeAbstraction/Shape.java deleted file mode 100644 index 435d0af..0000000 --- a/src/TemeAbstraction/Shape.java +++ /dev/null @@ -1,28 +0,0 @@ -package TemeAbstraction; - -abstract class Shape { - - abstract double rectangleArea(double length, double breadth); - - abstract double squareArea(double side); - - abstract double circleArea(double radius); -} - -class Area extends Shape { - @Override - double rectangleArea(double length, double breadth) { - return length * breadth; - } - - @Override - double squareArea(double side) { - return side * side; - - } - - @Override - double circleArea(double radius) { - return Math.PI * radius * radius; - } -} diff --git a/src/main/java/com/example/jpa/ExceptionsExample.java b/src/main/java/com/example/jpa/ExceptionsExample.java new file mode 100644 index 0000000..941d66d --- /dev/null +++ b/src/main/java/com/example/jpa/ExceptionsExample.java @@ -0,0 +1,64 @@ +package com.example.jpa; + +import java.util.InputMismatchException; +import java.util.Scanner; +public class ExceptionsExample { + public static void main(String... args) { +// scannerExample1(); +// scannerExample2(); + stringExample(); + } + + private static void stringExample() { + String s = "Salut"; + int validIndex = 2; + int invalidIndex = 8; + printCharAt(s, validIndex); + printCharAt(s, invalidIndex); + + } + + private static void printCharAt(String text, int index) { + try { + System.out.println("Char at index " + index + " is " + text.charAt(index)); + } catch (IndexOutOfBoundsException e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private static void scannerExample2() { + try (Scanner scanner = new Scanner(System.in)) { + System.out.println("Enter two numbers: "); + int num1 = scanner.nextInt(); + int num2 = scanner.nextInt(); + + int result = num1 / num2; + System.out.println("Result: " + result); + } catch (ArithmeticException ex) { // 4/0 + System.out.println("Error: cannot divide by 0!"); + } catch (InputMismatchException ex) { + System.out.println("Error: Please insert a valid number!"); + } finally { + System.out.println("End of program"); + } + + } + + private static void scannerExample1() { + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter 2 integers:"); + int num1 = scanner.nextInt(); + int num2 = scanner.nextInt(); + + try { + int rez = num1 / num2; // pt a obtine exceptia 4/0 + System.out.println("Result = " + rez); + } catch (ArithmeticException e) { + System.out.println("Error: cannot divide by 0!"); + } + + scanner.close(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/JpaApplication.java b/src/main/java/com/example/jpa/JpaApplication.java new file mode 100644 index 0000000..24b2a13 --- /dev/null +++ b/src/main/java/com/example/jpa/JpaApplication.java @@ -0,0 +1,17 @@ +package com.example.jpa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; + +@SpringBootApplication +@EnableScheduling +@EnableWebSecurity +public class JpaApplication { + + public static void main(String[] args) { + SpringApplication.run(JpaApplication.class, args); + } + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/controllers/InstrumentController.java b/src/main/java/com/example/jpa/controllers/InstrumentController.java new file mode 100644 index 0000000..03d6d9b --- /dev/null +++ b/src/main/java/com/example/jpa/controllers/InstrumentController.java @@ -0,0 +1,36 @@ +package com.example.jpa.controllers; + +import com.example.jpa.models.Instrument; +import com.example.jpa.services.InstrumentService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/instruments") +public class InstrumentController { + private final InstrumentService instrumentService; + + public InstrumentController(InstrumentService service) { + this.instrumentService = service; + } + + @GetMapping + public ResponseEntity> getAllInstruments() { + return ResponseEntity.ok(instrumentService.getAllInstruments()); + } + + @GetMapping("/{id}") + public ResponseEntity getInstrumentById(@PathVariable Long id) { + return ResponseEntity.ok(instrumentService.findInstrumentById(id)); + } + + @PostMapping + public ResponseEntity createInstrument(@RequestBody Instrument instrument) { + Instrument createdInstrument = instrumentService.createInstrument(instrument); + return ResponseEntity.status(HttpStatus.CREATED).body(createdInstrument); + } + +} diff --git a/src/main/java/com/example/jpa/controllers/OrderController.java b/src/main/java/com/example/jpa/controllers/OrderController.java new file mode 100644 index 0000000..2281b79 --- /dev/null +++ b/src/main/java/com/example/jpa/controllers/OrderController.java @@ -0,0 +1,36 @@ +package com.example.jpa.controllers; + + +import com.example.jpa.dtos.RequestOrderDto; +import com.example.jpa.models.Order; +import com.example.jpa.services.OrderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/orders") +public class OrderController { + @Autowired + private OrderService service; + + @PostMapping + public ResponseEntity placeOrder(@RequestBody RequestOrderDto orderDto) { + System.out.println("Sunt in placeOrder"); + Order order = service.placeOrder(orderDto.getUserId(), orderDto.getItems()); + return ResponseEntity.ok(order); + } + + @GetMapping + public ResponseEntity> ordersWithPagination(@RequestParam Long userId, @RequestParam int page, @RequestParam int size) { + List orders = service.getOrdersWithPagination(userId, page, size); + return ResponseEntity.ok(orders); + } + + @PutMapping + public ResponseEntity cancelOrder(@RequestParam Long orderId) { + return ResponseEntity.ok(service.cancelOrder(orderId)); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/controllers/ReviewController.java b/src/main/java/com/example/jpa/controllers/ReviewController.java new file mode 100644 index 0000000..d4215d3 --- /dev/null +++ b/src/main/java/com/example/jpa/controllers/ReviewController.java @@ -0,0 +1,24 @@ +package com.example.jpa.controllers; + +import com.example.jpa.dtos.CreateReviewDto; +import com.example.jpa.models.Review; +import com.example.jpa.services.ReviewService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/reviews") +public class ReviewController { + @Autowired + private ReviewService reviewService; + + @PostMapping + public ResponseEntity addReview(@RequestBody CreateReviewDto dto) { + return ResponseEntity.ok(reviewService.addReview(dto)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/controllers/UserController.java b/src/main/java/com/example/jpa/controllers/UserController.java new file mode 100644 index 0000000..2643f45 --- /dev/null +++ b/src/main/java/com/example/jpa/controllers/UserController.java @@ -0,0 +1,72 @@ +package com.example.jpa.controllers; + +import com.example.jpa.dtos.CreateUserDto; +import com.example.jpa.exceptions.UserServiceException; +import com.example.jpa.models.Instrument; +import com.example.jpa.models.User; +import com.example.jpa.services.UserService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * Represents a REST controller for handling user-related operations. + */ +@RestController +@RequestMapping("/api/users") +public class UserController { + private final UserService service; + + public UserController(UserService userService) { + this.service = userService; + } + + @PostMapping("/all") + public ResponseEntity> createUsers(@RequestBody List users) { + Iterable createdUsers = service.saveAll(users); + return ResponseEntity.status(HttpStatus.CREATED).body(createdUsers); + } + + @GetMapping + public ResponseEntity> getAllUsers() { + Iterable users = service.findAllUsers(); + return ResponseEntity.status(HttpStatus.OK).body(users); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteUser(@PathVariable Long id) { + service.deleteUser(id); + return ResponseEntity.noContent().build(); + } + + @GetMapping("/{username}") + public ResponseEntity findByUsername(@PathVariable String username) { + Optional user = service.findUserByUsername(username); + + return user.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + } + + @PostMapping + public ResponseEntity addUser(@RequestBody User user) { + User savedUser = service.addUser(user); + return ResponseEntity.ok(savedUser); + } + + @PostMapping("/create-from-dto") + public ResponseEntity createUserFromDto(@RequestBody CreateUserDto userDto) { + User user = new User(); + try { + user = service.createUserFromDto(userDto); + } catch (UserServiceException ex) { + System.out.println(ex.getMessage()); + System.out.println(ex.getErrorCode()); + } + return ResponseEntity.ok(user); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/dtos/AddressDto.java b/src/main/java/com/example/jpa/dtos/AddressDto.java new file mode 100644 index 0000000..8849dd3 --- /dev/null +++ b/src/main/java/com/example/jpa/dtos/AddressDto.java @@ -0,0 +1,16 @@ +package com.example.jpa.dtos; + +import lombok.Data; +import lombok.ToString; + +import java.io.Serializable; + +@Data +@ToString +public class AddressDto implements Serializable { + + private String city; + private String street; + private String country; + private Integer numberOfStreet; +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/dtos/CreateReviewDto.java b/src/main/java/com/example/jpa/dtos/CreateReviewDto.java new file mode 100644 index 0000000..5613c44 --- /dev/null +++ b/src/main/java/com/example/jpa/dtos/CreateReviewDto.java @@ -0,0 +1,16 @@ +package com.example.jpa.dtos; + +import lombok.Data; +import lombok.NoArgsConstructor; + +@NoArgsConstructor +@Data + +public class CreateReviewDto { + private Long userId; + private Long instrumentId; + private Integer rating; + private String comment; + + +} diff --git a/src/main/java/com/example/jpa/dtos/CreateUserDto.java b/src/main/java/com/example/jpa/dtos/CreateUserDto.java new file mode 100644 index 0000000..6b3fce2 --- /dev/null +++ b/src/main/java/com/example/jpa/dtos/CreateUserDto.java @@ -0,0 +1,21 @@ +package com.example.jpa.dtos; + +import com.example.jpa.models.Order; +import lombok.Data; +import lombok.ToString; + +import java.io.Serializable; +import java.time.LocalDate; +import java.util.List; +@Data +@ToString +public class CreateUserDto implements Serializable { + private String name; + private Integer age; + private LocalDate registrationDate; + private String email; + private String username; + private boolean active; + private AddressDto address; + private List orders; +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/dtos/MonthlyIncomeReport.java b/src/main/java/com/example/jpa/dtos/MonthlyIncomeReport.java new file mode 100644 index 0000000..6ab422d --- /dev/null +++ b/src/main/java/com/example/jpa/dtos/MonthlyIncomeReport.java @@ -0,0 +1,19 @@ +package com.example.jpa.dtos; + +import lombok.Data; +import lombok.ToString; + +import java.math.BigDecimal; +import java.time.Month; + +@Data +@ToString +public class MonthlyIncomeReport { +private Month month; +private int year; +private BigDecimal totalIncome; +private BigDecimal averageOrderValue; +private int totalOrderCount; + + +} diff --git a/src/main/java/com/example/jpa/dtos/OrderDto.java b/src/main/java/com/example/jpa/dtos/OrderDto.java new file mode 100644 index 0000000..5a3eed6 --- /dev/null +++ b/src/main/java/com/example/jpa/dtos/OrderDto.java @@ -0,0 +1,17 @@ +package com.example.jpa.dtos; + +import lombok.Data; +import lombok.ToString; + +import java.io.Serializable; +import java.time.LocalDate; + +@Data +@ToString +public class OrderDto implements Serializable { + + private String product; + private Double price; + private LocalDate orderDate; + +} diff --git a/src/main/java/com/example/jpa/dtos/OrderWeeklyReport.java b/src/main/java/com/example/jpa/dtos/OrderWeeklyReport.java new file mode 100644 index 0000000..93183ec --- /dev/null +++ b/src/main/java/com/example/jpa/dtos/OrderWeeklyReport.java @@ -0,0 +1,20 @@ +package com.example.jpa.dtos; + +import com.example.jpa.enums.OrderStatus; +import lombok.Data; +import lombok.ToString; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.Map; + +@Data//pentru getere si setere! +@ToString +public class OrderWeeklyReport { + private int totalOrders; + private LocalDate startDate; + private LocalDate endDate; + private BigDecimal totalRevenue; + private Map orderStatus; + +} diff --git a/src/main/java/com/example/jpa/dtos/RequestOrderDto.java b/src/main/java/com/example/jpa/dtos/RequestOrderDto.java new file mode 100644 index 0000000..8040cd3 --- /dev/null +++ b/src/main/java/com/example/jpa/dtos/RequestOrderDto.java @@ -0,0 +1,16 @@ +package com.example.jpa.dtos; + +import com.example.jpa.models.OrderItem; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@NoArgsConstructor +@AllArgsConstructor +@Data +public class RequestOrderDto { + private Long userId; + private List items; +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/enums/InstrumentCategory.java b/src/main/java/com/example/jpa/enums/InstrumentCategory.java new file mode 100644 index 0000000..e71a784 --- /dev/null +++ b/src/main/java/com/example/jpa/enums/InstrumentCategory.java @@ -0,0 +1,6 @@ +package com.example.jpa.enums; + +public enum InstrumentCategory { +STRINGS,WIND,PERCUSSION,KEYBOARD + +} diff --git a/src/main/java/com/example/jpa/enums/OrderStatus.java b/src/main/java/com/example/jpa/enums/OrderStatus.java new file mode 100644 index 0000000..e720c0a --- /dev/null +++ b/src/main/java/com/example/jpa/enums/OrderStatus.java @@ -0,0 +1,7 @@ +package com.example.jpa.enums; + +public enum OrderStatus { + PENDING,PROCESSING,SHIPPED,DELIVERED,CANCELLED + + +} diff --git a/src/main/java/com/example/jpa/exceptions/EmailSendingException.java b/src/main/java/com/example/jpa/exceptions/EmailSendingException.java new file mode 100644 index 0000000..8ef7214 --- /dev/null +++ b/src/main/java/com/example/jpa/exceptions/EmailSendingException.java @@ -0,0 +1,10 @@ +package com.example.jpa.exceptions; + +public class EmailSendingException extends Exception { + +public EmailSendingException(String message){ + super(message); + +} + +} diff --git a/src/main/java/com/example/jpa/exceptions/UserServiceException.java b/src/main/java/com/example/jpa/exceptions/UserServiceException.java new file mode 100644 index 0000000..2570981 --- /dev/null +++ b/src/main/java/com/example/jpa/exceptions/UserServiceException.java @@ -0,0 +1,16 @@ +package com.example.jpa.exceptions; + +public class UserServiceException extends RuntimeException { + private String errorCode; + + public UserServiceException(String message, String codeError) { + super(message); + this.errorCode = codeError; + } + + public String getErrorCode() { + + return errorCode; + } + +} diff --git a/src/main/java/com/example/jpa/models/Address.java b/src/main/java/com/example/jpa/models/Address.java new file mode 100644 index 0000000..dda4950 --- /dev/null +++ b/src/main/java/com/example/jpa/models/Address.java @@ -0,0 +1,28 @@ +package com.example.jpa.models; + +import com.fasterxml.jackson.annotation.JsonBackReference; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "addresses") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Address { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String city; + private String street; + private String country; + private Integer numberOfStreet; + + @OneToOne(mappedBy = "address") + @JsonBackReference + private User user; + +} diff --git a/src/main/java/com/example/jpa/models/Instrument.java b/src/main/java/com/example/jpa/models/Instrument.java new file mode 100644 index 0000000..6d2a7bf --- /dev/null +++ b/src/main/java/com/example/jpa/models/Instrument.java @@ -0,0 +1,43 @@ +package com.example.jpa.models; + +import com.example.jpa.enums.InstrumentCategory; +import com.fasterxml.jackson.annotation.JsonManagedReference; +import jakarta.persistence.*; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Represents an instrument entity with details such as ID, name, price, category, manufacturer, and stock quantity. + */ +@Entity +@Table(name = "instrument") +@Data +@NoArgsConstructor +public class Instrument { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + @Column(nullable = false) + private BigDecimal price; + @Enumerated(EnumType.STRING) + private InstrumentCategory category; + private String manufacturer; + @Column(nullable = false) + private int stockQuantity; + + @JsonManagedReference + @OneToMany(mappedBy = "instrument", cascade = CascadeType.ALL) + private List reviews = new ArrayList<>(); + + @ManyToMany(mappedBy = "wishlist") + private Set users = new HashSet<>(); +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/models/Order.java b/src/main/java/com/example/jpa/models/Order.java new file mode 100644 index 0000000..9c33876 --- /dev/null +++ b/src/main/java/com/example/jpa/models/Order.java @@ -0,0 +1,57 @@ +package com.example.jpa.models; + +import com.example.jpa.enums.OrderStatus; +import com.example.jpa.models.OrderItem; +import com.example.jpa.models.User; +import com.fasterxml.jackson.annotation.JsonBackReference; +import com.fasterxml.jackson.annotation.JsonManagedReference; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.List; +@Entity +@Table(name = "orders") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Order { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @OneToMany(mappedBy = "order", cascade = CascadeType.ALL) + @JsonManagedReference + private List items; + private LocalDate orderDate; + @Enumerated(EnumType.STRING) + private OrderStatus status; + private BigDecimal totalAmount; + + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "user_id", referencedColumnName = "id") + @JsonBackReference + private User user; + + public Order(List items, OrderStatus status, LocalDate orderDate, User user) { + this.items = items; + this.status = status; + this.orderDate = orderDate; + this.user = user; + } + + public void calculateTotalAmount() { + this.totalAmount = items.stream().map(OrderItem::getSubtotal).reduce(BigDecimal.ZERO, BigDecimal::add); + } + + public void updateStatus() { + if (items.isEmpty()) { + this.status = OrderStatus.CANCELLED; + } else if (status == OrderStatus.PENDING) { + this.status = OrderStatus.PROCESSING; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/models/OrderItem.java b/src/main/java/com/example/jpa/models/OrderItem.java new file mode 100644 index 0000000..1f91ebb --- /dev/null +++ b/src/main/java/com/example/jpa/models/OrderItem.java @@ -0,0 +1,57 @@ +package com.example.jpa.models; + +import com.example.jpa.models.Instrument; +import com.example.jpa.models.Order; +import com.fasterxml.jackson.annotation.JsonBackReference; +import jakarta.persistence.*; +import lombok.Data; + +import java.math.BigDecimal; + +@Entity +@Table(name = "order_item") +@Data +public class OrderItem { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne + @JoinColumn(name = "instrument_id", nullable = false) + private Instrument instrument; + + @Column(nullable = false) + private Integer quantity; + + @ManyToOne + @JoinColumn(name = "order_id", nullable = false) + @JsonBackReference + private Order order; + + public OrderItem() { + } + + public OrderItem(Order order, Instrument instrument, Integer quantity) { + this.order = order; + this.quantity = quantity; + this.instrument = instrument; + } + + public BigDecimal getSubtotal() { + return instrument.getPrice().multiply(BigDecimal.valueOf(quantity)); + } + + public void setQuantity(Integer quantity) { + if (quantity <= 0) + throw new IllegalArgumentException("Quantity must be positive!"); +// if (quantity > instrument.getStockQuantity()) +// throw new IllegalStateException("Insufficient stock for this instrument!"); + + this.quantity = quantity; + } + + public void updateInstrumentStock() { + this.instrument.setStockQuantity(this.instrument.getStockQuantity() - this.quantity); + } + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/models/Review.java b/src/main/java/com/example/jpa/models/Review.java new file mode 100644 index 0000000..5cf773d --- /dev/null +++ b/src/main/java/com/example/jpa/models/Review.java @@ -0,0 +1,32 @@ +package com.example.jpa.models; + +import com.fasterxml.jackson.annotation.JsonBackReference; +import com.fasterxml.jackson.annotation.JsonManagedReference; +import jakarta.persistence.*; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; +@Entity +@Table(name = "reviews") +@Data +@NoArgsConstructor +public class Review { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "user_id", referencedColumnName = "id") + @JsonBackReference + private User user; + + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "instrument_id", referencedColumnName = "id") + @JsonBackReference + private Instrument instrument; + private Integer rating; + private String comment; + private LocalDateTime reviewDate; + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/models/User.java b/src/main/java/com/example/jpa/models/User.java new file mode 100644 index 0000000..482476e --- /dev/null +++ b/src/main/java/com/example/jpa/models/User.java @@ -0,0 +1,52 @@ +package com.example.jpa.models; + +import com.fasterxml.jackson.annotation.JsonManagedReference; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Entity +@Table(name = "users") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String name; + private Integer age; + private LocalDate registrationDate; + private String email; + private String username; + private boolean active; + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "address_id", referencedColumnName = "id") + @JsonManagedReference + private Address address; + + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) + @JsonManagedReference + private List orders = new ArrayList<>(); + + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) + @JsonManagedReference + private List reviews = new ArrayList<>(); + + @ManyToMany + @JoinTable( + name = "wishlist", + joinColumns = @JoinColumn(name = "user_id"), + inverseJoinColumns = @JoinColumn(name = "instrument_id") + ) + private Set wishlist = new HashSet<>(); + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/otherStuff/recap/Abstractizare.java b/src/main/java/com/example/jpa/otherStuff/recap/Abstractizare.java new file mode 100644 index 0000000..6417eb5 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/Abstractizare.java @@ -0,0 +1,65 @@ +package com.example.jpa.otherStuff.recap; + +public class Abstractizare { + public static void main(String[] args){ + PremiumUser premiumUser = new PremiumUser("s", 25,10); + StandardUser standardUser = new StandardUser("p", 26,18); + } +} + +abstract class User{ + protected String name; + protected int age; + + public User(String name,int age){ + this.age = age; + this.name=name; + + } + public abstract double calculateDiscount(); + + + public void displayInfo(){ + System.out.println("Name : "+ name + "age" + age); + + } +} + +class StandardUser extends User{ + private int numberOfPurchases; + + + public StandardUser(String name,int age, int numberOfPurchases){ + super(name,age); + this.numberOfPurchases = numberOfPurchases; + + + } + + + @Override + public double calculateDiscount() { + return numberOfPurchases > 10 ? 0.1 : 0.0; + } +} +class PremiumUser extends User{ + private int numberOfPurchases; + + + public PremiumUser(String name,int age, int numberOfPurchases){ + super(name,age); + this.numberOfPurchases = numberOfPurchases; + + + } + + + @Override + public double calculateDiscount() { + return numberOfPurchases > 10 ? 0.1 : 0.0; + } +} + + + + diff --git a/src/main/java/com/example/jpa/otherStuff/recap/ExceptionDemo.java b/src/main/java/com/example/jpa/otherStuff/recap/ExceptionDemo.java new file mode 100644 index 0000000..1b9aedd --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/ExceptionDemo.java @@ -0,0 +1,67 @@ +package com.example.jpa.otherStuff.recap; + +import com.example.jpa.exceptions.EmailSendingException; + +public class ExceptionDemo { + //checked exceptions + static class InsuficientFoundsException extends Exception { + public InsuficientFoundsException(String message) { + super(message); + } + + } + + //uncheked except + static class AccountNotActiveException extends RuntimeException { + public AccountNotActiveException(String message) { + super(message); + } + } + + static class BankAccount { + private long balance = 1000L; + private boolean isActive = false; + + + public void transfer(long amount) throws InsuficientFoundsException { + if (amount > balance) + throw new InsuficientFoundsException("Fonduri insuficiente. Sold curent: " + balance); + + balance -= amount; + + + } + + public void withdraw(long amount) { + if (!isActive) + throw new AccountNotActiveException("Cont inactiv!"); + + if (amount < 0) + throw new IllegalArgumentException("Suma de retragere trebuie sa fie pozitiva!"); + + balance -= amount; + } + } + + public static void main(String... args) { + BankAccount account = new BankAccount(); + + + try { + account.transfer(900L); + } catch (InsuficientFoundsException ex) { + ex.printStackTrace(); + } + + + try { + account.withdraw(-5); + } catch (IllegalArgumentException e) { + System.out.println("Suma gresita! " + e.getMessage()); + } catch (AccountNotActiveException e) { + System.out.println("Exceptie: " + e.getMessage()); + + + } + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/Polimorfism.java b/src/main/java/com/example/jpa/otherStuff/recap/Polimorfism.java new file mode 100644 index 0000000..55aa97d --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/Polimorfism.java @@ -0,0 +1,49 @@ +package com.example.jpa.otherStuff.recap; + +public class Polimorfism { + public static void main(String[] args) { + Food pizza = new Pizza(); + Food salad = new Salad(); + + System.out.println(pizza.getPrice()); + System.out.println(salad.getPrice()); + + pizza.preparare(); + salad.preparare(); + + } + +} + + +interface Food{ + void preparare(); + double getPrice(); + +} + +class Pizza implements Food{ + + @Override + public void preparare() { + System.out.println("Prepara pizza!"); + } + + @Override + public double getPrice() { + return 12; + } + +} +class Salad implements Food{ + + @Override + public void preparare() { + System.out.println("Preparam salata!"); + } + + @Override + public double getPrice() { + return 10; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/otherStuff/recap/UserService.java b/src/main/java/com/example/jpa/otherStuff/recap/UserService.java new file mode 100644 index 0000000..46eac8f --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/UserService.java @@ -0,0 +1,4 @@ +package com.example.jpa.otherStuff.recap; + +public interface UserService { +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/AtomicExamples.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/AtomicExamples.java new file mode 100644 index 0000000..993b8d1 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/AtomicExamples.java @@ -0,0 +1,18 @@ +package com.example.jpa.otherStuff.recap.concurancy; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +public class AtomicExamples { + private static AtomicInteger atomicInteger = new AtomicInteger(0); + + public static void main(String... args) { + ExecutorService executorService = Executors.newFixedThreadPool(5); + for (int i = 0; i < 10; i++) { + executorService.submit(() -> System.out.println(atomicInteger.incrementAndGet() + " TreadId: " + Thread.currentThread().getId())); + } + + executorService.shutdown(); + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CollectionExample.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CollectionExample.java new file mode 100644 index 0000000..88832ca --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CollectionExample.java @@ -0,0 +1,22 @@ +package com.example.jpa.otherStuff.recap.concurancy; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class CollectionExample { + public static void main(String... args) { + Map stringStringMap = new ConcurrentHashMap<>(); + stringStringMap.put("Sam", "Java"); + stringStringMap.put("Daniel", "typeScript"); + +// Set keys = new HashSet<>(stringStringMap.keySet()); + + for (String k : stringStringMap.keySet()) { + System.out.println(k + " loves coding in: " + stringStringMap.get(k)); + stringStringMap.remove(k); + } + + System.out.println("Size: " + stringStringMap.size()); + + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/Count.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/Count.java new file mode 100644 index 0000000..eb701a8 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/Count.java @@ -0,0 +1,19 @@ +package com.example.jpa.otherStuff.recap.concurancy; + +public class Count { + public static int count = 0; + + public static synchronized void incrementCounter() { + int current = count; + System.out.println("Before: " + current + " ThreadId: " + Thread.currentThread().getId()); + count = current + 1; + System.out.println("After: " + count + " ThreadId: " + Thread.currentThread().getId()); + } + + public static void main(String... args) { + for (int i = 0; i < 10; i++) { + Thread t = new Thread(Count::incrementCounter); + t.start(); + } + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CountObjectSync.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CountObjectSync.java new file mode 100644 index 0000000..6ae67d9 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CountObjectSync.java @@ -0,0 +1,22 @@ +package com.example.jpa.otherStuff.recap.concurancy; + +public class CountObjectSync { + public static int count = 0; + public static Object lock = new Object(); + + public static void incrementCounter() { + synchronized (lock) { + int current = count; + System.out.println("Before: " + current + " ThreadId: " + Thread.currentThread().getId()); + count = current + 1; + System.out.println("After: " + count + " ThreadId: " + Thread.currentThread().getId()); + } + } + + public static void main(String... args) { + for (int i = 0; i < 10; i++) { + Thread t = new Thread(CountObjectSync::incrementCounter); + t.start(); + } + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CountUsingLock.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CountUsingLock.java new file mode 100644 index 0000000..05b4485 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/CountUsingLock.java @@ -0,0 +1,29 @@ +package com.example.jpa.otherStuff.recap.concurancy; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class CountUsingLock { + public static int count = 0; + public static Lock lock = new ReentrantLock(); + + public static void incrementCounter() { + if (lock.tryLock()) { + try { + int current = count; + System.out.println("Before: " + current + " ThreadId: " + Thread.currentThread().getId()); + count = current + 1; + System.out.println("After: " + count + " ThreadId: " + Thread.currentThread().getId()); + } finally { + lock.unlock(); + } + } else System.out.println("Thread failed to increment " + Thread.currentThread().getId()); + } + + public static void main(String... args) { + for (int i = 0; i < 10; i++) { + Thread t = new Thread(CountUsingLock::incrementCounter); + t.start(); + } + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/DeadlockExample.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/DeadlockExample.java new file mode 100644 index 0000000..efc5c23 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/DeadlockExample.java @@ -0,0 +1,48 @@ +package com.example.jpa.otherStuff.recap.concurancy; + +public class DeadlockExample { + public static final Object RESOURCE1 = new Object(); + public static final Object RESOURCE2 = new Object(); + + public static void main(String... args) { + Thread t1 = new Thread(() -> { + System.out.println("T1: incerc sa obtin resursa1"); + synchronized (RESOURCE1) { + System.out.println("T1: am obtinut resursa1"); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + System.out.println("T1: incerc sa obtin resursa2"); + synchronized (RESOURCE2) { + System.out.println("T1: am obtinut resursa2"); + } + } + }); + + Thread t2 = new Thread(() -> { + System.out.println("T2: Incerc sa obtin resursa1"); + synchronized (RESOURCE1) { + System.out.println("T2: Am obtinut resursa1"); + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + System.out.println("T2: incerc sa obtin resursa2"); + synchronized (RESOURCE2) { + System.out.println("T2: am obtinut resursa2"); + } + } + }); + + t1.start(); + t2.start(); + } + +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/MyThread.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/MyThread.java new file mode 100644 index 0000000..83df662 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/MyThread.java @@ -0,0 +1,23 @@ +package com.example.jpa.otherStuff.recap.concurancy; + +public class MyThread extends Thread { + @Override + public void run() { + for (int i = 0; i < 5; i++) { + System.out.println("Thread: " + i); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + } +} + +class Main { + public static void main(String... args) { + MyThread t = new MyThread(); +// t.setDaemon(true); + t.start(); + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/DPrincipleAfter.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/DPrincipleAfter.java new file mode 100644 index 0000000..1b03b2a --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/DPrincipleAfter.java @@ -0,0 +1,50 @@ +package com.example.jpa.otherStuff.recap.concurancy.solid; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +public class DPrincipleAfter { + public static void main(String... a) { + Logger consoleLogger = new ConsoleLogger1(); + Logger fileLogger = new FileLogger1(); + + LoggingService fLoggerService = new LoggingService(fileLogger); + + fLoggerService.processLog("Log to file"); + } +} + +interface Logger { + void log(String message); +} + +class ConsoleLogger1 implements Logger { + @Override + public void log(String message) { + System.out.println(message); + } +} + +class FileLogger1 implements Logger { + public void log(String message) { + File logFile = new File("filename.log"); + try (FileWriter fw = new FileWriter(logFile, true)) { + fw.write(message + "\n"); + } catch (IOException e) { + e.printStackTrace(); + } + } +} + +class LoggingService { + private Logger logger; + + public LoggingService(Logger logger) { + this.logger = logger; + } + + public void processLog(String message) { + logger.log(message); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/DPrincipleBefore.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/DPrincipleBefore.java new file mode 100644 index 0000000..5170fa1 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/DPrincipleBefore.java @@ -0,0 +1,28 @@ +package com.example.jpa.otherStuff.recap.concurancy.solid; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +public class DPrincipleBefore { +} + + +class ConsoleLogger { + public void log(String message) { + System.out.println(message); + } +} + + +class FileLogger { + public void log(String message) { + File logFile = new File("path/filename.log"); + try (FileWriter fw = new FileWriter(logFile, true)){ + fw.write(message + "\n"); + }catch(IOException e ){ + e.printStackTrace(); + } + + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/LPrincipleBefore.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/LPrincipleBefore.java new file mode 100644 index 0000000..7607a78 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/LPrincipleBefore.java @@ -0,0 +1,89 @@ +package com.example.jpa.otherStuff.recap.concurancy.solid; + +public class LPrincipleBefore { + public static void main(String[] a) { + Rectangle1 r = new Rectangle1(0, 0, 4, 5); + r.setWidth(10); + r.setHeight(20); + System.out.println("Arie: " + r.getArea()); + + Rectangle1 r2 = new Square(0, 0, 4); + r2.setWidth(10); + r2.setHeight(20); + System.out.println("Arie: " + r2.getArea()); + } +} + +abstract class Shape1 { + protected int x; + protected int y; + + public Shape1(int x, int y) { + this.x = x; + this.y = y; + } + + public abstract double getArea(); + + public abstract double getPerimeter(); + + public abstract void resize(int x, int y); + +} + +class Rectangle1 extends Shape1 { + protected int width; + protected int height; + + public Rectangle1(int x, int y, int width, int height) { + super(x, y); + this.width = width; + this.height = height; + } + + public void setHeight(int height) { + this.height = height; + } + + public void setWidth(int w) { + this.width = w; + } + + @Override + public double getArea() { + return width * height; + } + + @Override + public double getPerimeter() { + return 2 * (width + height); + } + + @Override + public void resize(int x, int y) { + this.x = x; + this.y = y; + } +} + +class Square extends Rectangle1 { + public Square(int x, int y, int size) { + super(x, y, size, size); + } + + @Override + public void setHeight(int h) { + setSize(h); + } + + @Override + public void setWidth(int w) { + setSize(w); + } + + private void setSize(int size) { + super.setHeight(size); + super.setWidth(size); + } + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/OPrincipleAfter.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/OPrincipleAfter.java new file mode 100644 index 0000000..284ec3f --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/OPrincipleAfter.java @@ -0,0 +1,78 @@ +package com.example.jpa.otherStuff.recap.concurancy.solid; + +public class OPrincipleAfter { + public static void main(String... a) { + ModernDrawingService service = new ModernDrawingService(); + Shape circle = new Circle(10, 10); + Shape rectangle = new Rectangle(5, 10); + + service.drawShape(circle); + service.drawShape(rectangle); + } +} + +interface Shape { + void draw(); + + int getX(); + + int getY(); + +} + +class Circle implements Shape { + private int x; + private int y; + + public Circle(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public void draw() { + System.out.println("Drawing Circle at(" + x + " , " + y + ") "); + } + + @Override + public int getX() { + return x; + } + + @Override + public int getY() { + return y; + } +} + +class Rectangle implements Shape { + private int x; + private int y; + + public Rectangle(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public void draw() { + System.out.println("Drawing Rectangle at(" + x + " , " + y + ") "); + } + + @Override + public int getX() { + return x; + } + + @Override + public int getY() { + return y; + } +} + + +class ModernDrawingService { + public void drawShape(Shape shape) { + shape.draw(); + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/OPrincipleBefore.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/OPrincipleBefore.java new file mode 100644 index 0000000..6d96b4a --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/OPrincipleBefore.java @@ -0,0 +1,18 @@ +package com.example.jpa.otherStuff.recap.concurancy.solid; +// +public class OPrincipleBefore { + +} + + +class DrawingService { + public void drawShape(String type, int x, int y) { + if (type.equals("circle")) { + System.out.println("Drawing Circle at(" + x + " , " + y + ") "); + } else if (type.equals("rectangle")) { + System.out.println("Drawing Rectangle at(" + x + " , " + y + ") "); + } else if (type.equals("triangle")) { + System.out.println("Drawing Triangle at(" + x + " , " + y + ") "); + } + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/SPrincipaleBefore.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/SPrincipaleBefore.java new file mode 100644 index 0000000..fcaadf7 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/SPrincipaleBefore.java @@ -0,0 +1,38 @@ +package com.example.jpa.otherStuff.recap.concurancy.solid; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class SPrincipaleBefore { +} + +class UserRegistration { + public void registerUser(String username, String email, String password) { + + //Validations + if (username == null || username.length() < 2) { + throw new IllegalArgumentException("Username must not be null and should have min 2 chars"); + } + if (!email.contains("@")) { + throw new IllegalArgumentException("Invalid email format"); + } + try (Connection connection = DriverManager.getConnection("bla bka")) { + String sql = "insert into users(username, email,password) values ( ?,?,?)"; + PreparedStatement statement = connection.prepareStatement(sql); + statement.setString(1, username); + statement.setString(2, email); + statement.setString(3, password); + statement.executeUpdate(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + try { + //Email sending implementation + + } catch (Exception e) { + + } + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/SPrincipleAfter.java b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/SPrincipleAfter.java new file mode 100644 index 0000000..c848135 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/concurancy/solid/SPrincipleAfter.java @@ -0,0 +1,71 @@ +package com.example.jpa.otherStuff.recap.concurancy.solid; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class SPrincipleAfter { +} + +class UserValidation { + public void validation(String username, String email, String password) { + if (username == null || username.length() < 2) { + throw new IllegalArgumentException("Username must not be null and should have min 2 chars"); + } + if (!email.contains("@")) { + throw new IllegalArgumentException("Invalid email format"); + } + if (password.length() < 6) { + throw new IllegalArgumentException("Password must have at least 6 caracters!"); + } + } +} + +class UserRepository { + public void saveUser(String username, String email, String password) { + try (Connection connection = DriverManager.getConnection("bla bka")) { + String sql = "insert into users(username, email,password) values ( ?,?,?)"; + PreparedStatement statement = connection.prepareStatement(sql); + statement.setString(1, username); + statement.setString(2, email); + statement.setString(3, password); + statement.executeUpdate(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } +} + +class EmailService { + public void sendWelcomeEmail(String username, String email) { + try { + //Email sending implementation + + } catch (Exception e) { + + } + } +} + +class UserRegistrationService { + private UserValidation userValidation; + private UserRepository userRepository; + private EmailService emailService; + + public UserRegistrationService(UserValidation userValidation, UserRepository userRepository, EmailService emailService) { + this.emailService = emailService; + this.userRepository = userRepository; + this.userValidation = userValidation; + } + + public void registrationUser(String username, String email, String password) { + //validation + userValidation.validation(username, email, password); + //save in db + userRepository.saveUser(username, email, password); + //send email + emailService.sendWelcomeEmail(username, email); + + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Builder.java b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Builder.java new file mode 100644 index 0000000..8c4c821 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Builder.java @@ -0,0 +1,103 @@ +package com.example.jpa.otherStuff.recap.designpatterns; + +import java.util.ArrayList; +import java.util.List; + +class Pizza { + + private String blat; + private String sos; + private List toppings; + + public static class PizzaBuilder { + private Pizza pizza; + + public PizzaBuilder() { + pizza = new Pizza(); + pizza.toppings = new ArrayList<>(); + } + + public PizzaBuilder blat(String blat) { + pizza.blat = blat; + return this; + } + + public PizzaBuilder sos(String sos) { + pizza.sos = sos; + return this; + } + + public PizzaBuilder addTopping(String topping) { + pizza.toppings.add(topping); + return this; + + } + + public Pizza buid() { + return pizza; + } + } + + @Override + public String toString() { + return "Pizza cy blat " + blat + ", sos " + sos + " si toppinguri: " + toppings; + } + +} + +class PizzaB { + private String blat; + private String sos; + private List toppings; + + + public PizzaB withBlat(String blat) { + this.blat = blat; + return this; + + } + + public PizzaB withSos(String sos) { + if (toppings == null) { + toppings = new ArrayList<>(); + } + this.sos = sos; + return this; + + } + + public PizzaB withTopping(String topping) { + toppings.add(topping); + return this; + } + + + @Override + public String toString() { + return "Pizza cy blat " + blat + ", sos " + sos + " si toppinguri: " + toppings; + } + +} + + +public class Builder { + public static void main(String... a) { + Pizza pizza1 = new Pizza.PizzaBuilder() + .blat("subtire") + .sos("rosii") + .addTopping("mozzarela") + .addTopping("busuioc") + .buid(); + + PizzaB pizza2 = new PizzaB() + .withBlat("gros") + .withSos("rosii") + .withTopping("sunca") + .withTopping("mozzarela"); + + + System.out.println(pizza1); + System.out.println(pizza2); + } + +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Facade.java b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Facade.java new file mode 100644 index 0000000..20402f4 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Facade.java @@ -0,0 +1,46 @@ +package com.example.jpa.otherStuff.recap.designpatterns; + +class SistemAudio{ + public void pornesteAudio(){ + System.out.println("Sistem audio pornit!"); + } +} +class SistemLumini{ + public void pornesteLumini(){ + System.out.println("Sistem lumini pornit!"); + } +} + +class SistemVideo{ + public void pornesteVideo(){ + System.out.println("Sistem video pornit!"); + } +} + +class HomeCinemaFacade { + private SistemLumini lumini; + private SistemAudio audio; + private SistemVideo video; + + public HomeCinemaFacade(){ + lumini = new SistemLumini(); + audio = new SistemAudio(); + video = new SistemVideo(); + } + + public void pornesteFilm(){ + lumini.pornesteLumini(); + audio.pornesteAudio(); + video.pornesteVideo(); + } + + +} + + +public class Facade { + public static void main(String... a){ +HomeCinemaFacade facade = new HomeCinemaFacade(); +facade.pornesteFilm(); + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Factory.java b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Factory.java new file mode 100644 index 0000000..a756699 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Factory.java @@ -0,0 +1,61 @@ +package com.example.jpa.otherStuff.recap.designpatterns; + +interface Animal { + void makeSound(); + +} + +class Dog implements Animal { + + + @Override + public void makeSound() { + System.out.println("Ham ham!"); + } + +} + +class Cat implements Animal { + + @Override + public void makeSound() { + System.out.println("Miau!"); + } +} + +class Lion implements Animal { + + @Override + public void makeSound() { + System.out.println("Roar!"); + } +} + +class AnimalFactory { + public Animal createAnimal(String type) { + if (type.equalsIgnoreCase("dog")) { + return new Dog(); + } else if (type.equalsIgnoreCase("cat")) { + return new Cat(); + } else if (type.equalsIgnoreCase("Lion")) { + return new Lion(); + + } + return null; + } +} + + +public class Factory { +public static void main(String... a){ + AnimalFactory factory = new AnimalFactory(); + + Animal dog = factory.createAnimal("dog"); + Animal cat = factory.createAnimal("Cat"); + Animal lion = factory.createAnimal("liOn"); + + dog.makeSound(); + cat.makeSound(); + lion.makeSound(); +} +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Interpreter.java b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Interpreter.java new file mode 100644 index 0000000..9236564 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Interpreter.java @@ -0,0 +1,49 @@ +package com.example.jpa.otherStuff.recap.designpatterns; + +interface Expression { + int interpret(); + +} + +class NumberExpression implements Expression { + private int number; + + public NumberExpression(int number) { + this.number = number; + + } + + @Override + public int interpret() { + return number; + } +} + +class AddExpression implements Expression { + private Expression leftExpression; + private Expression rightExpression; + + public AddExpression(Expression e1, Expression e2) { + leftExpression = e1; + rightExpression = e2; + + } + + + @Override + public int interpret() { + return leftExpression.interpret() + rightExpression.interpret(); + } +} + +public class Interpreter { + public static void main(String... a) { + + Expression sum = new AddExpression(new NumberExpression(5), new NumberExpression(10)); + Expression sum2 = new AddExpression(sum,new NumberExpression(6)); + + + System.out.println("Sum2 " + sum2.interpret()); + System.out.println("Rez: " + sum.interpret()); + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Observer.java b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Observer.java new file mode 100644 index 0000000..29c4a72 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Observer.java @@ -0,0 +1,49 @@ +package com.example.jpa.otherStuff.recap.designpatterns; + + +import java.util.ArrayList; +import java.util.List; + +interface ObserverInt { + void update(String message); +} + +class NewSubscriber implements ObserverInt { + private String name; + + public NewSubscriber(String name) { + this.name = name; + } + + @Override + public void update(String message) { + System.out.println(name + " a primit stirea: " + message); + + } +} + +class NewAgency { + List observers = new ArrayList<>(); + + public void addObserver(ObserverInt o) { + observers.add(o); + } + + public void publishNews(String message) { + for (ObserverInt obs : observers) { + obs.update(message); + } + } +} + +public class Observer { + public static void main(String... a) { + NewAgency agency = new NewAgency(); + NewSubscriber s1 = new NewSubscriber("Sam"); + NewSubscriber s2 = new NewSubscriber("Ion"); + agency.addObserver(s1); + agency.addObserver(s2); + agency.publishNews("Trump a castigat!"); + + } +} diff --git a/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Singletone.java b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Singletone.java new file mode 100644 index 0000000..9cfba00 --- /dev/null +++ b/src/main/java/com/example/jpa/otherStuff/recap/designpatterns/Singletone.java @@ -0,0 +1,38 @@ +package com.example.jpa.otherStuff.recap.designpatterns; + +class DatabaseConnection { + private static DatabaseConnection instance; + private String connectionString; + + + private DatabaseConnection() { + connectionString = "jdbc:myskl://localhost:3306/db"; + + } + + public static synchronized DatabaseConnection getInstance() { + + if (instance == null) + instance = new DatabaseConnection(); + return instance; + } + + public void connect() { + System.out.println("Conecteaza la : " + connectionString); + + } + + +} + + +public class Singletone { + public static void main(String... a) { + DatabaseConnection db = DatabaseConnection.getInstance(); + db.connect(); + System.out.println(db); + + DatabaseConnection db2 = DatabaseConnection.getInstance(); + System.out.println(db2); + } +} diff --git a/src/main/java/com/example/jpa/repositories/AddressRepository.java b/src/main/java/com/example/jpa/repositories/AddressRepository.java new file mode 100644 index 0000000..c72be54 --- /dev/null +++ b/src/main/java/com/example/jpa/repositories/AddressRepository.java @@ -0,0 +1,7 @@ +package com.example.jpa.repositories; + +import com.example.jpa.models.Address; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface AddressRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/jpa/repositories/InstrumentRepository.java b/src/main/java/com/example/jpa/repositories/InstrumentRepository.java new file mode 100644 index 0000000..b1a5c52 --- /dev/null +++ b/src/main/java/com/example/jpa/repositories/InstrumentRepository.java @@ -0,0 +1,19 @@ +package com.example.jpa.repositories; + +import com.example.jpa.enums.InstrumentCategory; +import com.example.jpa.models.Instrument; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.math.BigDecimal; +import java.util.List; + + +@Repository +public interface InstrumentRepository extends JpaRepository { + List findByCategory(InstrumentCategory category); + + List findByPriceBetween(BigDecimal minPrice, BigDecimal maxPrice); + + List findByStockQuantityGreaterThan(int q); +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/repositories/OrderRepository.java b/src/main/java/com/example/jpa/repositories/OrderRepository.java new file mode 100644 index 0000000..83bee92 --- /dev/null +++ b/src/main/java/com/example/jpa/repositories/OrderRepository.java @@ -0,0 +1,17 @@ +package com.example.jpa.repositories; + +import com.example.jpa.models.Order; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.time.LocalDate; +import java.util.List; + + +public interface OrderRepository extends JpaRepository { + List findByUserId(Long userId); + Page findByUserId(Long userId, Pageable pageable); + + List findAllByOrderDateBetween(LocalDate startDate, LocalDate endDate); +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/repositories/ReviewRepository.java b/src/main/java/com/example/jpa/repositories/ReviewRepository.java new file mode 100644 index 0000000..fd4fb28 --- /dev/null +++ b/src/main/java/com/example/jpa/repositories/ReviewRepository.java @@ -0,0 +1,10 @@ +package com.example.jpa.repositories; + +import com.example.jpa.models.Review; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ReviewRepository extends JpaRepository { + + + +} diff --git a/src/main/java/com/example/jpa/repositories/UserJpaRepository.java b/src/main/java/com/example/jpa/repositories/UserJpaRepository.java new file mode 100644 index 0000000..ace10df --- /dev/null +++ b/src/main/java/com/example/jpa/repositories/UserJpaRepository.java @@ -0,0 +1,38 @@ +package com.example.jpa.repositories; + +import com.example.jpa.models.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + + +public interface UserJpaRepository extends JpaRepository { + Optional findByUsername(String username); + + List findByActive(boolean active); + + //ia toti useri ordonati dupa username ascendent + List findAllByOrderByUsernameAsc(); + + List findByActiveOrderByUsernameDesc(boolean active); + + List findByRegistrationDateBetween(LocalDate start, LocalDate end); + + List findByNameIgnoreCase(String name); + + List findByAgeGreaterThanEqual(int age); + + List findByUsernameContaining(String text); + + List findByUsernameStartingWith(String text); + + @Query("SELECT u FROM User u where u.age > 30") + List findUsersOver30(); + + @Query(value = "select u from users u where u.age > 30", nativeQuery = true) + List findUsersOver30NativeQuery(); + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/repositories/UserRepository.java b/src/main/java/com/example/jpa/repositories/UserRepository.java new file mode 100644 index 0000000..1a328a6 --- /dev/null +++ b/src/main/java/com/example/jpa/repositories/UserRepository.java @@ -0,0 +1,7 @@ +package com.example.jpa.repositories; + +import com.example.jpa.models.User; +import org.springframework.data.repository.CrudRepository; + +public interface UserRepository extends CrudRepository { +} diff --git a/src/main/java/com/example/jpa/security/SecurityConfig.java b/src/main/java/com/example/jpa/security/SecurityConfig.java new file mode 100644 index 0000000..f925af4 --- /dev/null +++ b/src/main/java/com/example/jpa/security/SecurityConfig.java @@ -0,0 +1,23 @@ +package com.example.jpa.security; + + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +public class SecurityConfig { + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + return http.authorizeHttpRequests(r -> { + r.requestMatchers(HttpMethod.POST, "/api/users/create-from-dto").permitAll().anyRequest().authenticated(); + }) + .oauth2Login(Customizer.withDefaults()) + .formLogin(Customizer.withDefaults()) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/services/InstrumentService.java b/src/main/java/com/example/jpa/services/InstrumentService.java new file mode 100644 index 0000000..870e9f5 --- /dev/null +++ b/src/main/java/com/example/jpa/services/InstrumentService.java @@ -0,0 +1,12 @@ +package com.example.jpa.services; + +import com.example.jpa.models.Instrument; + +import java.util.List; + +public interface InstrumentService { + List getAllInstruments(); + Instrument findInstrumentById(Long id); + Instrument createInstrument (Instrument instrument); + void updateInstrumentStock(Long id, Integer quantity); +} diff --git a/src/main/java/com/example/jpa/services/OrderService.java b/src/main/java/com/example/jpa/services/OrderService.java new file mode 100644 index 0000000..07af9bb --- /dev/null +++ b/src/main/java/com/example/jpa/services/OrderService.java @@ -0,0 +1,15 @@ +package com.example.jpa.services; + +import com.example.jpa.models.Order; +import com.example.jpa.models.OrderItem; + +import java.util.List; + + +public interface OrderService { + Order placeOrder(Long userId, List items); + + List getOrdersWithPagination(Long userId, int page, int size); + + Order cancelOrder(Long orderId); +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/services/ReviewService.java b/src/main/java/com/example/jpa/services/ReviewService.java new file mode 100644 index 0000000..c53b2e8 --- /dev/null +++ b/src/main/java/com/example/jpa/services/ReviewService.java @@ -0,0 +1,8 @@ +package com.example.jpa.services; + +import com.example.jpa.dtos.CreateReviewDto; +import com.example.jpa.models.Review; + +public interface ReviewService { + Review addReview(CreateReviewDto dto); +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/services/UserService.java b/src/main/java/com/example/jpa/services/UserService.java new file mode 100644 index 0000000..658fc11 --- /dev/null +++ b/src/main/java/com/example/jpa/services/UserService.java @@ -0,0 +1,23 @@ +package com.example.jpa.services; +import com.example.jpa.dtos.CreateUserDto; +import com.example.jpa.models.Instrument; +import com.example.jpa.models.User; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +public interface UserService { + Iterable saveAll(List users); + + Iterable findAllUsers(); + + void deleteUser(Long id); + + Optional findUserByUsername(String username); + + User addUser(User user); + + User createUserFromDto(CreateUserDto userDto); + + Set getWishlist(Long id); +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/services/impl/EmailService.java b/src/main/java/com/example/jpa/services/impl/EmailService.java new file mode 100644 index 0000000..43b00ff --- /dev/null +++ b/src/main/java/com/example/jpa/services/impl/EmailService.java @@ -0,0 +1,29 @@ +package com.example.jpa.services.impl; + +import com.example.jpa.exceptions.EmailSendingException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mail.MailException; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.stereotype.Service; + + +@Service +public class EmailService { + @Autowired + private JavaMailSender mailSender; + + public void sendEmail(String to, String subject, String body) throws EmailSendingException { + SimpleMailMessage message = new SimpleMailMessage(); + message.setTo(to); + message.setSubject(subject); + message.setText(body); + + try { + mailSender.send(message); + } catch (MailException ex) { + throw new EmailSendingException("Failed to send email: " + ex.getMessage()); + } + + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/services/impl/InstrumentServiceImpl.java b/src/main/java/com/example/jpa/services/impl/InstrumentServiceImpl.java new file mode 100644 index 0000000..1d72fd8 --- /dev/null +++ b/src/main/java/com/example/jpa/services/impl/InstrumentServiceImpl.java @@ -0,0 +1,48 @@ +package com.example.jpa.services.impl; + +import com.example.jpa.models.Instrument; +import com.example.jpa.repositories.InstrumentRepository; +import com.example.jpa.services.InstrumentService; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + + +@Service +public class InstrumentServiceImpl implements InstrumentService { + private final InstrumentRepository instrumentRepository; + + @Autowired + public InstrumentServiceImpl(InstrumentRepository instrumentRepository) { + this.instrumentRepository = instrumentRepository; + } + + public List getAllInstruments() { + return instrumentRepository.findAll(); + } + + public Instrument findInstrumentById(Long id) { + return instrumentRepository.findById(id).orElseThrow(() -> new EntityNotFoundException("Instrument not found")); + } + + public Instrument createInstrument(Instrument instrument) { + if (instrument.getStockQuantity() < 0) { + throw new IllegalArgumentException("Stock Quantity cannot be negative!"); + } + + return instrumentRepository.save(instrument); + } + + public void updateInstrumentStock(Long id, Integer quantity) { + Instrument instrument = findInstrumentById(id); + if (instrument == null) { + throw new EntityNotFoundException("Instrument with id: " + id + " cannot be found!"); + } + + instrument.setStockQuantity(quantity); + instrumentRepository.save(instrument); + } +} + diff --git a/src/main/java/com/example/jpa/services/impl/OrderServiceImpl.java b/src/main/java/com/example/jpa/services/impl/OrderServiceImpl.java new file mode 100644 index 0000000..b084571 --- /dev/null +++ b/src/main/java/com/example/jpa/services/impl/OrderServiceImpl.java @@ -0,0 +1,99 @@ +package com.example.jpa.services.impl; + +import com.example.jpa.enums.OrderStatus; +import com.example.jpa.models.Instrument; +import com.example.jpa.models.Order; +import com.example.jpa.models.OrderItem; +import com.example.jpa.models.User; +import com.example.jpa.repositories.InstrumentRepository; +import com.example.jpa.repositories.OrderRepository; +import com.example.jpa.repositories.UserJpaRepository; + +import com.example.jpa.services.OrderService; +import jakarta.persistence.EntityNotFoundException; +import jakarta.transaction.Transactional; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +/** + * This class provides implementation for handling orders. + */ +@Service +public class OrderServiceImpl implements OrderService { + @Autowired + private OrderRepository orderRepository; + @Autowired + private UserJpaRepository userRepository; + @Autowired + private InstrumentRepository instrumentRepository; + + /** + * Places an order for a specific user + */ + public Order placeOrder(Long userId, List items) { + if (items == null || items.isEmpty()) + throw new IllegalArgumentException("Order must contain at least one item!"); + + + Optional userOpt = userRepository.findById(userId); + Order order = new Order(); + if (userOpt.isPresent()) { + User user = userOpt.get(); + order.setUser(user); + order.setStatus(OrderStatus.PENDING); + order.setOrderDate(LocalDate.now()); + + List orderItems = items.stream() + .map(item -> { + OrderItem orderItem = new OrderItem(); + orderItem.setOrder(order); + orderItem.setQuantity(item.getQuantity()); + + if (item.getInstrument() == null) { + Instrument instrument = instrumentRepository.findById(item.getInstrument().getId()) + .orElseThrow(() -> new EntityNotFoundException("Instrument not found!")); + orderItem.setInstrument(instrument); + } else { + System.out.println("item.getInstrument() = " + item.getInstrument()); + orderItem.setInstrument(item.getInstrument()); + } + + return orderItem; + }).toList(); + + order.setItems(orderItems); + order.calculateTotalAmount(); + items.forEach(OrderItem::updateInstrumentStock); + } else { + throw new EntityNotFoundException("User was not found!"); + } + + return orderRepository.save(order); + } + + public List getOrdersWithPagination(Long userId, int page, int size) { + PageRequest pageRequest = PageRequest.of(page - 1, size); + Page orderPage = orderRepository.findByUserId(userId, pageRequest); + return orderPage.getContent(); + } + + @Transactional + public Order cancelOrder(Long orderId) { + Order order = orderRepository.findById(orderId) + .orElseThrow(() -> new EntityNotFoundException("Order was not found!")); + + order.getItems().forEach(item -> { + Instrument instrument = item.getInstrument(); + instrument.setStockQuantity(instrument.getStockQuantity() + item.getQuantity()); + }); + + order.setStatus(OrderStatus.CANCELLED); + return orderRepository.save(order); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/services/impl/ReportingService.java b/src/main/java/com/example/jpa/services/impl/ReportingService.java new file mode 100644 index 0000000..b9b1189 --- /dev/null +++ b/src/main/java/com/example/jpa/services/impl/ReportingService.java @@ -0,0 +1,66 @@ +package com.example.jpa.services.impl; + +import com.example.jpa.dtos.MonthlyIncomeReport; +import com.example.jpa.dtos.OrderWeeklyReport; +import com.example.jpa.models.Order; +import com.example.jpa.repositories.OrderRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class ReportingService { + @Autowired + private OrderRepository orderRepository; + + @Scheduled(cron = "0 0 9 ? * MON") + public void generateWeeklyOrderReport() { + LocalDate endDate = LocalDate.now(); + LocalDate startDate = endDate.minusDays(7); + + List weeklyOrders = orderRepository.findAllByOrderDateBetween(startDate, endDate); + + OrderWeeklyReport orderWeeklyReport = new OrderWeeklyReport(); + orderWeeklyReport.setStartDate(startDate); + orderWeeklyReport.setEndDate(endDate); + orderWeeklyReport.setTotalOrders(weeklyOrders.size()); + //@formatter:off + orderWeeklyReport.setTotalRevenue(calculateTotalIncome(weeklyOrders)); + + orderWeeklyReport.setOrderStatus(weeklyOrders.stream() + .collect(Collectors.groupingBy(Order::getStatus, Collectors.counting())));//@formatter:on + + System.out.println(orderWeeklyReport); + } + + @Scheduled(cron = "* * 9 1 * *") + public void generateMonthlyIncomeReport() { + LocalDate now = LocalDate.now().minusMonths(1); + LocalDate firstDayOfMonth = now.withDayOfMonth(1); + LocalDate lastDayOfMonth = now.withDayOfMonth(now.lengthOfMonth()); + + List orderList = orderRepository.findAllByOrderDateBetween(firstDayOfMonth, lastDayOfMonth); + + MonthlyIncomeReport report = new MonthlyIncomeReport(); + report.setYear(now.getYear()); + report.setMonth(now.getMonth()); + report.setTotalIncome(calculateTotalIncome(orderList)); + report.setAverageOrderValue(calculateTotalIncome(orderList).divide(BigDecimal.valueOf(orderList.size()), 2, RoundingMode.HALF_UP)); + report.setTotalOrderCount(orderList.size()); + System.out.println("Monthly report = " + report); + } + + private static BigDecimal calculateTotalIncome(List orderList) { + return orderList.stream() + .map(Order::getTotalAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/services/impl/ReviewServiceImpl.java b/src/main/java/com/example/jpa/services/impl/ReviewServiceImpl.java new file mode 100644 index 0000000..e868cca --- /dev/null +++ b/src/main/java/com/example/jpa/services/impl/ReviewServiceImpl.java @@ -0,0 +1,41 @@ +package com.example.jpa.services.impl; + +import com.example.jpa.dtos.CreateReviewDto; +import com.example.jpa.models.Instrument; +import com.example.jpa.models.Review; +import com.example.jpa.models.User; +import com.example.jpa.repositories.InstrumentRepository; +import com.example.jpa.repositories.ReviewRepository; +import com.example.jpa.repositories.UserJpaRepository; +import com.example.jpa.services.ReviewService; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +@Service +public class ReviewServiceImpl implements ReviewService { + @Autowired + private ReviewRepository reviewRepository; + @Autowired + private InstrumentRepository instrumentRepository; + @Autowired + private UserJpaRepository userRepository; + + + public Review addReview(CreateReviewDto dto) { + Review review = new Review(); + review.setComment(dto.getComment()); + review.setRating(dto.getRating()); + review.setReviewDate(LocalDateTime.now()); + + User user = userRepository.findById(dto.getUserId()).orElseThrow(() -> new EntityNotFoundException("User was not found!")); + review.setUser(user); + + Instrument instrument = instrumentRepository.findById(dto.getUserId()).orElseThrow(() -> new EntityNotFoundException("Instrument not found!")); + review.setInstrument(instrument); + + return reviewRepository.save(review); + } + +} \ No newline at end of file diff --git a/src/main/java/com/example/jpa/services/impl/UserServiceImpl.java b/src/main/java/com/example/jpa/services/impl/UserServiceImpl.java new file mode 100644 index 0000000..a5578db --- /dev/null +++ b/src/main/java/com/example/jpa/services/impl/UserServiceImpl.java @@ -0,0 +1,85 @@ +package com.example.jpa.services.impl; + +import com.example.jpa.dtos.CreateUserDto; +import com.example.jpa.models.Instrument; +import com.example.jpa.models.User; +import com.example.jpa.repositories.UserJpaRepository; +import com.example.jpa.repositories.UserRepository; +import com.example.jpa.services.UserService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +@Service +public class UserServiceImpl implements UserService { + @Autowired + private UserRepository repository; + @Autowired + private UserJpaRepository jpaRepository; + @Autowired + private ObjectMapper mapper; + @Autowired + private EmailService emailService; + + + public Iterable saveAll(List users) { + return jpaRepository.saveAll(users); + } + + public Iterable findAllUsers() { + return jpaRepository.findAll(); + } + + public void deleteUser(Long id) { + jpaRepository.deleteById(id); + } + + public Optional findUserByUsername(String username) { + return jpaRepository.findByUsername(username); + } + + public User addUser(User user) { + // user.getOrders().forEach(o-> o.setUser(savedUser)); + // Save User + return jpaRepository.save(user); + } + + public User createUserFromDto(CreateUserDto userDto) { +// User u = new User(); +// u.setName(userDto.getName());... + User user = mapper.convertValue(userDto, User.class); + + User savedUser = jpaRepository.save(user); + + String subject = "Welcome to our service!"; + String body = "Dear " + savedUser.getName() + " Thank you for registration! \n your username is " + savedUser.getUsername(); + +// try { +// emailService.sendEmail(savedUser.getEmail(), subject, body); +// } catch (EmailSendingException e) { +// System.out.println(e.getMessage()); +// throw new UserServiceException("User created successfully, but failed to send welcome email!", "ERROR_ON_MAIL_SENDING"); +//// e.printStackTrace(); +// } + + return savedUser; + } + + @Override + public Set getWishlist(Long id) { + return Set.of(); + } + + public Set getWishlist(long userId){ + Optional user = jpaRepository.findById(userId); + if (user.isPresent()) + return user.get().getWishlist(); + else return Collections.EMPTY_SET; + } + +} \ No newline at end of file diff --git a/src/main/resources/application-test.properties b/src/main/resources/application-test.properties new file mode 100644 index 0000000..1c37463 --- /dev/null +++ b/src/main/resources/application-test.properties @@ -0,0 +1,12 @@ +# Configurare H2 pentru teste +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect + +# Configurare JPA/Hibernate +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +spring.h2.console.enabled=true \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..e146cff --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,24 @@ +# Database connection prop +spring.datasource.url=jdbc:postgresql://localhost:5432/postgres +spring.datasource.username=postgres +spring.datasource.password=postgres + +#JPA prop +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto=update +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect + +#Email config +spring.mail.host=smtp.gmail.com +spring.mail.port=587 +spring.mail.username= +# adaugati emailul personal +spring.mail.password= +# generati o parola din contul vostru-> security -> 2-step verification -> App passwords generati una noua pe care sa o folositi +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.starttls.enable=true + +#Google props +logging.level.org.springframework.security=DEBUG +spring.security.oauth2.client.registration.google.client-id=vcghd +spring.security.oauth2.client.registration.google.client-secret=fdgdf \ No newline at end of file diff --git a/src/sistem_gestiune_angajati/Employee.java b/src/sistem_gestiune_angajati/Employee.java deleted file mode 100644 index 1dc093a..0000000 --- a/src/sistem_gestiune_angajati/Employee.java +++ /dev/null @@ -1,24 +0,0 @@ -package sistem_gestiune_angajati; - -public abstract class Employee { - - public String name; - public int id; - private double salary; - - public Employee(String name, int id, double salary) { - this.name = name; - this.id = id; - this.salary = salary; - } - - public abstract void work(); - - public void displayInfo() { - System.out.println("Name: " + this.name + "ID: " + id + "salary: " + salary); - } - - public String getName(){ - return name; - } -} diff --git a/src/sistem_gestiune_angajati/Main.java b/src/sistem_gestiune_angajati/Main.java deleted file mode 100644 index a0faef5..0000000 --- a/src/sistem_gestiune_angajati/Main.java +++ /dev/null @@ -1,31 +0,0 @@ -package sistem_gestiune_angajati; - -public class Main { - public static void main(String... args) { - SoftwareDeveloper dev = new SoftwareDeveloper(" Sam ", 1001, 5000); - ProjectManager pm = new ProjectManager(" Ion ",2001, 7000); - TechnicalLead tl = new TechnicalLead(" Marius ", 3001 , 8500); - - - dev.work(); - dev.learnNewTechnology(); - dev.writeCode(); - dev.debugCode(); - dev.displayInfo(); - - pm.conductMettings(); - pm.leadTeam(); - pm.work(); - pm.displayInfo(); - - tl.conductMettings(); - tl.work(); - tl.leadTeam(); - tl.displayInfo(); - tl.writeCode(); - tl.learnNewTechnology(); - - - - } -} diff --git a/src/sistem_gestiune_angajati/ManagementSkills.java b/src/sistem_gestiune_angajati/ManagementSkills.java deleted file mode 100644 index 6a4e5f4..0000000 --- a/src/sistem_gestiune_angajati/ManagementSkills.java +++ /dev/null @@ -1,7 +0,0 @@ -package sistem_gestiune_angajati; - -public interface ManagementSkills { - void leadTeam(); - - void conductMettings(); -} diff --git a/src/sistem_gestiune_angajati/ProgramingSkills.java b/src/sistem_gestiune_angajati/ProgramingSkills.java deleted file mode 100644 index 457bfd9..0000000 --- a/src/sistem_gestiune_angajati/ProgramingSkills.java +++ /dev/null @@ -1,7 +0,0 @@ -package sistem_gestiune_angajati; - -public interface ProgramingSkills { - void writeCode(); - - void debugCode(); -} diff --git a/src/sistem_gestiune_angajati/ProjectManager.java b/src/sistem_gestiune_angajati/ProjectManager.java deleted file mode 100644 index d6664ff..0000000 --- a/src/sistem_gestiune_angajati/ProjectManager.java +++ /dev/null @@ -1,25 +0,0 @@ -package sistem_gestiune_angajati; - -public class ProjectManager extends Employee implements ManagementSkills { - public ProjectManager(String name,int id,double salary){ - super(name,id,salary); - - - } - - - @Override - public void work() { - System.out.println(super.getName() + "works with projects and resources"); - } - - @Override - public void leadTeam() { - System.out.println(super.getName() +"coordina teams"); - } - - @Override - public void conductMettings() { - System.out.println(super.getName() + "organize mettings"); - } -} diff --git a/src/sistem_gestiune_angajati/SoftwareDeveloper.java b/src/sistem_gestiune_angajati/SoftwareDeveloper.java deleted file mode 100644 index ce4dee8..0000000 --- a/src/sistem_gestiune_angajati/SoftwareDeveloper.java +++ /dev/null @@ -1,23 +0,0 @@ -package sistem_gestiune_angajati; - -public class SoftwareDeveloper extends TechnicalEmployee { -public SoftwareDeveloper(String name,int id, double salary){ - super(name,id,salary); - -} - - @Override - public void learnNewTechnology() { - System.out.println(super.getName() + "learn activemq"); - } - - @Override - public void work() { - System.out.println(super.getName() + "softare developer"); - } - - @Override - public void writeCode() { - System.out.println(super.getName() + "write code and documentation"); - } -} diff --git a/src/sistem_gestiune_angajati/TechnicalEmployee.java b/src/sistem_gestiune_angajati/TechnicalEmployee.java deleted file mode 100644 index fcac9dd..0000000 --- a/src/sistem_gestiune_angajati/TechnicalEmployee.java +++ /dev/null @@ -1,18 +0,0 @@ -package sistem_gestiune_angajati; - -public abstract class TechnicalEmployee extends Employee implements ProgramingSkills { - - public TechnicalEmployee(String name, int id, double salary){ - super(name,id,salary); - } - - - @Override - public void debugCode(){ - System.out.println(super.getName() + "debugs code with advance techniques!"); - - } - public void learnNewTechnology(){ - - } -} diff --git a/src/sistem_gestiune_angajati/TechnicalLead.java b/src/sistem_gestiune_angajati/TechnicalLead.java deleted file mode 100644 index 79ffec9..0000000 --- a/src/sistem_gestiune_angajati/TechnicalLead.java +++ /dev/null @@ -1,34 +0,0 @@ -package sistem_gestiune_angajati; - -public class TechnicalLead extends TechnicalEmployee implements ManagementSkills { - public TechnicalLead(String name, int id, double salary) { - super(name, id, salary); - - - } - - @Override - public void learnNewTechnology() { - System.out.println(super.getName() + "learn new arhitecture for car development"); - } - - @Override - public void work() { - System.out.println(super.getName() + "conducts technical teams and add value to system architecture"); - } - - @Override - public void leadTeam() { - System.out.println(super.getName() + "lead the team"); - } - - @Override - public void conductMettings() { - System.out.println(super.getName() + "conduct meetings with team and clients"); - } - - @Override - public void writeCode() { - System.out.println(super.getName() + "write complex algoritms"); - } -} diff --git a/src/test/java/com/example/jpa/OrderControllerIntegrationTest.java b/src/test/java/com/example/jpa/OrderControllerIntegrationTest.java new file mode 100644 index 0000000..daca6f8 --- /dev/null +++ b/src/test/java/com/example/jpa/OrderControllerIntegrationTest.java @@ -0,0 +1,103 @@ +package com.example.jpa; + +import com.example.jpa.models.Order; +import com.example.jpa.models.User; +import com.example.jpa.repositories.OrderRepository; +import com.example.jpa.repositories.UserJpaRepository; +import jakarta.transaction.Transactional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.time.LocalDate; +import java.util.List; + +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@ActiveProfiles("test") +@Transactional +@AutoConfigureMockMvc +public class OrderControllerIntegrationTest { + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserJpaRepository userRepository; + + @Autowired + private OrderRepository orderRepository; + + private User testUser; + + @BeforeEach + void setUp() { + User u = new User(); + u.setName("sam"); + u.setUsername("test1"); + u.setEmail("user1@gmail.com"); + testUser = userRepository.save(u); + } + + @Test + void placeOrder_ShouldReturnCreatedOrder() throws Exception { + String product = "Test Product"; + double price = 99.9; + + mockMvc.perform(MockMvcRequestBuilders.post("/orders") + .param("userId", String.valueOf(testUser.getId())) + .param("product", product) + .param("price", String.valueOf(price)) + .contentType(MediaType.APPLICATION_FORM_URLENCODED)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.product").value(product)) + .andExpect(jsonPath("$.price").value(price)); + + List orders = orderRepository.findByUserId(testUser.getId()); + assertEquals(1, orders.size()); + + Order createdOrder = orders.get(0); + assertEquals(product, createdOrder.getProduct()); + assertEquals(price, createdOrder.getPrice()); + assertEquals(testUser.getId(), createdOrder.getUser().getId()); + } + + @Test + void ordersWithPagination_ShouldReturnPaginatedOrders() throws Exception { + createOrders(testUser, 10); + + mockMvc.perform(MockMvcRequestBuilders.get("/orders") + .param("userId", String.valueOf(testUser.getId())) + .param("page", "1") + .param("size", "5") + .contentType(MediaType.APPLICATION_FORM_URLENCODED)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(5))); + + mockMvc.perform(MockMvcRequestBuilders.get("/orders") + .param("userId", String.valueOf(testUser.getId())) + .param("page", "2") + .param("size", "3") + .contentType(MediaType.APPLICATION_FORM_URLENCODED)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(3))); + + } + + private void createOrders(User user, int count) { + for (int i = 0; i < count; i++) { + Order o = new Order("Product " + i, 100.0 + i, LocalDate.now(), user); + orderRepository.save(o); + } + } + +} \ No newline at end of file diff --git a/src/test/java/com/example/jpa/OrderServiceIntegrationTest.java b/src/test/java/com/example/jpa/OrderServiceIntegrationTest.java new file mode 100644 index 0000000..af19bab --- /dev/null +++ b/src/test/java/com/example/jpa/OrderServiceIntegrationTest.java @@ -0,0 +1,83 @@ +package com.example.jpa; + +import com.example.jpa.models.Order; +import com.example.jpa.models.User; +import com.example.jpa.repositories.OrderRepository; +import com.example.jpa.repositories.UserJpaRepository; +import com.example.jpa.services.impl.OrderServiceImpl; +import jakarta.transaction.Transactional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import java.time.LocalDate; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +@ActiveProfiles("test") +@Transactional +public class OrderServiceIntegrationTest { + + @Autowired + private OrderServiceImpl service; + + + @Autowired + private OrderRepository orderRepository; + + @Autowired + private UserJpaRepository userRepository; + + private User testUser; + private Order testOrder; + + @BeforeEach + void setUp() { + //curatare data base + orderRepository.deleteAll(); + userRepository.deleteAll(); + + //creaza user nou + User u = new User(); + u.setName("Angelo"); + u.setUsername("user 1"); + u.setEmail("user1@gmail.com"); + + testUser = userRepository.save(u); + //creaza order + Order o = new Order(); + o.setProduct("Test Product"); + o.setUser(testUser); + o.setPrice(100.0); + o.setOrderDate(LocalDate.now()); + testOrder = orderRepository.save(o); + } + + @Test + void placeOrder_ShouldCreateANewOrder() { + String product = "New Product"; + Double price = 150.0; + + Order placedOrder = service.placeOrder(testUser.getId(), product, price); + + assertNotNull(placedOrder); + assertNotNull(placedOrder.getId()); + assertEquals(product, placedOrder.getProduct()); + assertEquals(price, placedOrder.getPrice()); + assertEquals(testUser.getId(), placedOrder.getUser().getId()); + + assertTrue(orderRepository.findById(placedOrder.getId()).isPresent()); + + + } + + @Test + void placeOrder_ShouldReturnNull_WhenUserDoesNotExist(){ + Order placedOrder = service.placeOrder(9999L,"Same Product",50.0); + assertNull(placedOrder); + } + +} diff --git a/src/test/java/com/example/jpa/UserServiceTest.java b/src/test/java/com/example/jpa/UserServiceTest.java new file mode 100644 index 0000000..30ab2b3 --- /dev/null +++ b/src/test/java/com/example/jpa/UserServiceTest.java @@ -0,0 +1,120 @@ +package com.example.jpa; + +import com.example.jpa.dtos.CreateUserDto; +import com.example.jpa.exceptions.EmailSendingException; +import com.example.jpa.exceptions.UserServiceException; +import com.example.jpa.models.User; +import com.example.jpa.repositories.UserJpaRepository; +import com.example.jpa.services.impl.EmailService; +import com.example.jpa.services.UserService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +public class UserServiceTest { + + @Mock + private UserJpaRepository jpaRepository; + + @InjectMocks + private UserService userService; + + @Mock + private ObjectMapper mapper; + + @Mock + private EmailService emailService; + + + private User testUser; + + private CreateUserDto testUserDto; + + + @BeforeEach + void setUp() { + testUser = new User(); + testUser.setId(1L); + testUser.setName("Sam"); + testUser.setUsername("userboss"); + testUser.setEmail("setboss@gmail.com"); + + testUserDto = new CreateUserDto(); + } + + + @Test + void saveAll_ShouldReturnSavedUsers() { + List users = Arrays.asList(testUser); + when(jpaRepository.saveAll(users)).thenReturn(users); + + Iterable savedUser = userService.saveAll(users); + + assertNotNull(savedUser); + verify(jpaRepository).saveAll(users); + + } + + @Test + void findAllUsers_ShouldReturnAllUsers() { + List users = Arrays.asList(testUser); + when(jpaRepository.findAll()).thenReturn(users); + + Iterable foundUsers = userService.findAllUsers(); + assertNotNull(foundUsers); + verify(jpaRepository).findAll(); + } + + @Test + void deletUser_ShouldDeleteUserById() { + Long userId = 1L; + doNothing().when(jpaRepository).deleteById(userId); + + userService.deletUser(userId); + + verify(jpaRepository).deleteById(userId); + + } + + @Test + void createUserFromDto_ShouldCreateAndSendEmail() throws EmailSendingException { + when(mapper.convertValue(testUserDto, User.class)).thenReturn(testUser); + when(jpaRepository.save(testUser)).thenReturn(testUser); + doNothing().when(emailService).sendEmail(anyString(), anyString(), anyString()); + + User savedUser = userService.createUserFromDto(testUserDto); + + assertNotNull(savedUser); + verify(mapper).convertValue(testUserDto, User.class); + verify(jpaRepository).save(any(User.class)); + verify(emailService).sendEmail(anyString(), anyString(), anyString()); + } + + @Test + void createUserFromDto_ShouldThrowException_WhenEmailFailed() throws EmailSendingException { + + when(mapper.convertValue(testUserDto, User.class)).thenReturn(testUser); + when(jpaRepository.save(testUser)).thenReturn(testUser); + doThrow(new EmailSendingException("Failed to send email !")).when(emailService).sendEmail(anyString(), anyString(), anyString()); + + assertThrows(UserServiceException.class, () -> userService.createUserFromDto(testUserDto)); + + verify(mapper).convertValue(testUserDto, User.class); + verify(jpaRepository).save(any(User.class)); + verify(emailService).sendEmail(anyString(), anyString(), anyString()); + + } + +}