Commit 926ad82e authored by elisabeth kee's avatar elisabeth kee

Project so far - still need to complete modification section of web

service
parent 4ff39a34
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
This diff is collapsed.
@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 https://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 Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.5-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>trial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>trial</name>
<description>Trial for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
package com.example.trial;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import java.io.IOException;
public class CORSResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
\ No newline at end of file
package com.example.trial;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.stereotype.Component;
import com.example.trial.lovers.resource.LoverResource;
import com.example.trial.profile.resource.ProfileResource;
import javax.ws.rs.ApplicationPath;
@Component
@ApplicationPath("api")
public class JerseyConfiguration extends ResourceConfig {
public JerseyConfiguration() {
register(ProfileResource.class);
register(LoverResource.class);
register(CORSResponseFilter.class);
// La servlet de jersey map toutes les url /* donc impossible de servir du contenu statique via la servlet par défaut de sprign boot.
// On doit donc dire à jersey de quand même laisser passer la requête pour que la prochaine servlet prenne le relais.
// https://stackoverflow.com/questions/29658240/spring-boot-jersey-allow-jersey-to-serve-static-content/29670751#29670751
property(ServletProperties.FILTER_FORWARD_ON_404, true);
}
}
package com.example.trial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TrialApplication {
public static void main(String[] args) {
SpringApplication.run(TrialApplication.class, args);
}
}
package com.example.trial.lovers.bdd;
import javax.persistence.*;
@Entity
public class Lover {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long id;
public String partnerGender;
public String partnerPet;
public Lover() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPartnerGender() {
return partnerGender;
}
public void setPartnerGender(String partnerGender) {
this.partnerGender = partnerGender;
}
public String getPartnerPet() {
return partnerPet;
}
public void setPartnerPet(String partnerPet) {
this.partnerPet = partnerPet;
}
}
package com.example.trial.lovers.bdd;
import org.springframework.data.repository.CrudRepository;
public interface LoverRepository extends CrudRepository<Lover, Long> { }
\ No newline at end of file
package com.example.trial.lovers.resource;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.trial.lovers.bdd.Lover;
import com.example.trial.lovers.bdd.LoverRepository;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Path("lovers")
public class LoverResource {
@Autowired
public LoverRepository loverRepository;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Lover> listerLovers() {
List<Lover> lovers = new ArrayList<>();
loverRepository.findAll().forEach(lovers::add);
return lovers;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Lover creerLover(Lover l) {
return loverRepository.save(l);
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteLover(@PathParam("id") Long id) {
if (loverRepository.findById(id).isPresent()) {
try {
loverRepository.deleteById(id);
} catch (Exception e) {
return Response.serverError().build();
}
}
return Response.noContent().build();
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
// PATCH /lovers/{id}
public Response updatePartnerGender(@PathParam("id") Long id, Lover l) {
String partnerGender = l.getPartnerGender();
Optional<Lover> optional = loverRepository.findById(id);
if (optional.isPresent()) {
Lover lBDD = optional.get();
lBDD.setPartnerGender(partnerGender);
loverRepository.save(lBDD);
return Response.ok(lBDD).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
public Response updatePartnerPet(@PathParam("id") Long id, Lover l) {
String partnerPet = l.getPartnerPet();
Optional<Lover> optional = loverRepository.findById(id);
if (optional.isPresent()) {
Lover lBDD = optional.get();
lBDD.setPartnerGender(partnerPet);
loverRepository.save(lBDD);
return Response.ok(lBDD).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
}
package com.example.trial.profile.process;
import java.util.List;
import javax.persistence.*;
import com.example.trial.lovers.bdd.Lover;
@Entity
public class Profile {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
public Long id;
public String firstname;
public int age;
public String gender;
public String pet;
public String contact;
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
public List<Lover> lovers;
public Profile() {
super();
}
public Profile(String firstname, int age, String gender, String pet, String contact) {
super();
this.firstname = firstname ;
this.age = age;
this.gender = gender;
this.pet = pet;
this.contact = contact;
}
public String Firstname() {
return firstname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPet() {
return pet;
}
public void setPet(String pet) {
this.pet = pet;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public List<Lover> getLovers() {
return lovers;
}
public void setLovers(List<Lover> lovers) {
this.lovers = lovers;
}
}
package com.example.trial.profile.process;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
public interface ProfileRepository extends CrudRepository<Profile, Long> {
Optional<Profile> findByFirstname(String firstname);
Optional<Profile> findById(Long id);
List<Profile> findByAge(int age);
List<Profile> findByGenderAndPet(String gender, String pet);
}
\ No newline at end of file
package com.example.trial.profile.resource;
public class LoverInput {
Long idLover;
public LoverInput() {
super();
}
public Long getIdLover() {
return idLover;
}
public void setIdLover(Long idLover) {
this.idLover = idLover;
}
}
package com.example.trial.profile.resource;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.trial.lovers.bdd.Lover;
import com.example.trial.lovers.bdd.LoverRepository;
import com.example.trial.profile.process.Profile;
import com.example.trial.profile.process.ProfileRepository;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Path("profiles")
public class ProfileResource {
@Autowired
public ProfileRepository profileRepository;
@Autowired
public LoverRepository loverRepository;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Profile createProfile(Profile p) {
return profileRepository.save(p);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Profile> getAllProfile() {
List<Profile> profiles = new ArrayList<>();
profileRepository.findAll().forEach(profiles::add);
return profiles;
}
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Profile updateTotalyProfile(@PathParam("id") Long id, Profile p) {
p.setId(id);
return profileRepository.save(p);
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteProfile(@PathParam("id") Long id) {
if (profileRepository.findById(id).isPresent()) {
profileRepository.deleteById(id);
}
return Response.noContent().build();
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getprofileById(@PathParam("id") Long id) {
Optional<Profile> p = profileRepository.findById(id);
if (p.isPresent()) {
return Response.ok(p.get()).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/updateAge")
public Response updateAge(@PathParam("id") Long id, Profile p) {
int age = p.getAge();
Optional<Profile> optional = profileRepository.findById(id);
if (optional.isPresent()) {
Profile pBDD = optional.get();
pBDD.setAge(age);
profileRepository.save(pBDD);
return Response.ok(pBDD).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/updateFirstname")
public Response updateFirstname(@PathParam("id") Long id, Profile p) {
String firstname = p.getFirstname();
Optional<Profile> optional = profileRepository.findById(id);
if (optional.isPresent()) {
Profile pBDD = optional.get();
pBDD.setFirstname(firstname);
profileRepository.save(pBDD);
return Response.ok(pBDD).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/updateGender")
public Response updateGender(@PathParam("id") Long id, Profile p) {
String gender = p.getGender();
Optional<Profile> optional = profileRepository.findById(id);
if (optional.isPresent()) {
Profile pBDD = optional.get();
pBDD.setGender(gender);
profileRepository.save(pBDD);
return Response.ok(pBDD).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/updatePet")
public Response updatePet(@PathParam("id") Long id, Profile p) {
String pet = p.getPet();
Optional<Profile> optional = profileRepository.findById(id);
if (optional.isPresent()) {
Profile pBDD = optional.get();
pBDD.setPet(pet);
profileRepository.save(pBDD);
return Response.ok(pBDD).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/updateContact")
public Response updateContact(@PathParam("id") Long id, Profile p) {
String partner = p.getContact();
Optional<Profile> optional = profileRepository.findById(id);
if (optional.isPresent()) {
Profile pBDD = optional.get();
pBDD.setContact(partner);
profileRepository.save(pBDD);
return Response.ok(pBDD).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/updateLovers")
public Response updateLovers(@PathParam("id") Long id, Profile p) {
List<Lover> lovers = p.getLovers();
Optional<Profile> optional = profileRepository.findById(id);
if (optional.isPresent()) {
Profile pBDD = optional.get();
pBDD.setLovers(lovers);
profileRepository.save(pBDD);
return Response.ok(pBDD).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@GET
@Path("{id}/lovers")
@Produces(MediaType.APPLICATION_JSON)
// GET /profiles/{id}/lovers
public List<Lover> listerLovers(@PathParam("id") Long id) {
return profileRepository.findById(id).get().getLovers();
}
@GET
@Path("{idLover}/loversmatch")
@Produces(MediaType.APPLICATION_JSON)
// GET /profiles/{idLover}/loversmatch
public List<Profile> listerLoversMatch(@PathParam("idLover") Long idLover) {
List<Profile> matches = new ArrayList<>();
String profilePartnerGender = loverRepository.findById(idLover).get().getPartnerGender();
String profilePartnerPet = loverRepository.findById(idLover).get().getPartnerPet();
profileRepository.findByGenderAndPet(profilePartnerGender, profilePartnerPet).forEach(matches::add);
return matches;
}
@POST
@Path("{idProfile}/lovers")
@Produces(MediaType.APPLICATION_JSON)
public Response addLoverDejaExistant(@PathParam("idProfile") Long idProfile, LoverInput lovers) {
Optional<Profile> pOpt = profileRepository.findById(idProfile);
Optional<Lover> lOpt = loverRepository.findById(lovers.getIdLover());
if (!pOpt.isPresent() || !lOpt.isPresent()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
Profile p = pOpt.get();
Lover l = lOpt.get();
p.getLovers().add(l);
profileRepository.save(p);
return Response.ok(p).build();
}
}
\ No newline at end of file
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:hsql://localhost/trial
spring.datasource.username=SA
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
\ No newline at end of file
$(document).ready(function() {
let $listeLovers= $("#listLovers");
let $listeProfilesDelete = $("#listProfilesDelete");
let $listeProfilesSelect = $("#listProfilesSelect");
let $listeProfilesSelect2 = $("#listProfilesSelect2");
let $listeMatches= $("#listMatches");
let $listeMyProfile= $("#myProfile");
let $selectLovers = $("#selectLovers");
let $selectLovers2 = $("#selectLovers2");
$.get("http://localhost:8080/api/profiles",function(resp){
resp.forEach( p => {
appendToListProfileDelete(p);
appendToListProfileSelect(p);
appendToListProfileSelect2(p);
});
});
$.get("http://localhost:8080/api/lovers",function(resp){
resp.forEach( l => {
appendToListLover(l);
appendToSelects(l);
});
});
$listeProfilesDelete.on("click", "li button", function() {
let elemid = $(this).parent().attr('id');
$.ajax({
type: "DELETE",
url: "http://localhost:8080/api/profiles/" + elemid.replace('profile-',''),
dataType: "json",
success: function(data){
$("#"+elemid).remove();
}
});
});
$listeProfilesSelect.on("click", "li button", function() {
let idLover = $(this).attr('id');
$.get("http://localhost:8080/api/profiles/"+idLover+"/loversmatch",function(resp){
resp.forEach( p => appendToListMatches(p));
});
});
$listeProfilesSelect2.on("click", "li button", function() {
let idProfile = $(this).parent().attr('id');
$.ajax({
type: "GET",
url: "http://localhost:8080/api/profiles/"+idProfile.replace('profile-',''),
dataType: "json",
success: function(data){
appendToListMyProfile(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert("Impossible de trouver le profile");
}
});
});
$listeLovers.on("click", "li button", function() {
let elemid = $(this).parent().attr('id');
let idLover = elemid.replace('lover-','');
$.ajax({
type: "DELETE",
url: "http://localhost:8080/api/lovers/"+idLover,
dataType: "json",
success: function(data){
$("#"+elemid).remove();
$(`#selectLovers option[value="${idLover}"]`).remove();
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert("Impossible de supprimer le lover, il est peut-être encore utilisé");
}
});
});
$('#addbtnProfile').click(function(){
let firstname = $('#firstname-input').val();
let age = $('#age-input').val();
let gender = $('#gender-input').val();
let pet = $('#pet-input').val();
let contact= $('#contact-input').val();
let idLover = $selectLovers.val();
$.ajax({
type: "POST",
url: "http://localhost:8080/api/profiles",
data: JSON.stringify({ "firstname": firstname, "age" : age, "gender": gender, "pet": pet, "contact": contact}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
addLoverToProfile(data.id, idLover);
}
});
$('#firstname-input').val('');
$('#age-input').val('');
$('#gender-input').val('');
$('#pet-input').val('');
$('#contact-input').val('');
return false;
});
$('#addbtnLover').click(function(){
let lover = {
partnerGender: $('#partner-input').val(),
partnerPet: $('#partner-pet-input').val()
};
$.ajax({
type: "POST",
url: "http://localhost:8080/api/lovers",
data: JSON.stringify(lover),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
appendToListLover(data);
appendToSelects(data);
}
});
$('#partner-input').val('');
$('#partner-pet-input').val('');
return false;
});
/* Ajoute un élément li dans la liste de lovers*/
function appendToListLover(lover) {
$listeLovers.append(`<li id="lover-${lover.id}" class="list-group-item">${lover.partnerGender} - who likes ${lover.partnerPet} <button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" >X</button></li>`);
}
/* Ajoute un élément li dans le select des lovers*/
function appendToSelects(lover) {
$selectLovers.append(`<option value="${lover.id}">${lover.partnerGender} - who likes ${lover.partnerPet}</option>`);
$selectLovers2.append(`<option value="${lover.id}">${lover.partnerGender} - who likes ${lover.partnerPet}</option>`);
}
/* Ajoute un élément li pour supprimer dans la liste de profiles*/
function appendToListProfileDelete(profile) {
liToAppend1 = `<li id="profile-${profile.id}" class="list-group-item">You are: ${profile.firstname} - age: ${profile.age}`;
profile.lovers.forEach( lover => liToAppend1+= ` - interested in: ${lover.partnerGender} - who likes ${lover.partnerPet}`);
liToAppend1+= ` <button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" >X</button></li>`;
$listeProfilesDelete.append(liToAppend1);
}
/* Ajoute un élément li pour selectionner dans la liste de profiles*/
function appendToListProfileSelect(profile) {
liToAppend2 = `<li id="${profile.id}" class="list-group-item">You are: ${profile.firstname} - age: ${profile.age}`;
profile.lovers.forEach( lover => liToAppend2+= ` - interested in: ${lover.partnerGender} - who likes ${lover.partnerPet} <button id="${lover.id}" class="btn btn-success btn-xs" data-title="Select" data-toggle="modal" data-target="#select" >;)</button>`);
liToAppend2+= `</li>`;
$listeProfilesSelect.append(liToAppend2);
}
/* Ajoute un élément li pour selectionner dans la liste de profiles
function appendToListProfileSelect2(profile) {
liToAppend3 = `<li id="profile-${profile.id}" class="list-group-item">You are: ${profile.firstname} - age: ${profile.age}`;
profile.lovers.forEach( lover => liToAppend3+= ` - interested in: ${lover.partnerGender} - who likes ${lover.partnerPet} <button id="${lover.id}" class="btn btn-success btn-xs" data-title="Select" data-toggle="modal" data-target="#select" >o</button>`);
liToAppend3+= `</li>`;
$listeProfilesSelect2.append(liToAppend3);
}*/
/*Ajoute un élément option pour selectionner dans la liste de profiles*/
function appendToListProfileSelect2(profile) {
optionToAppend = `<option value="${profile.id}">Name: ${profile.firstname} - age: ${profile.age} - gender: ${profile.gender} - who likes: ${profile.pet} - contact info: ${profile.contact}`;
profile.lovers.forEach( lover => optionToAppend+= ` - interested in: ${lover.partnerGender} - who likes ${lover.partnerPet}`);
optionToAppend+= `</option>`;
$listeProfilesSelect2.append(optionToAppend);
}
/* Ajoute un élément li dans la liste de matches*/
function appendToListMatches(profile) {
liToAppend = `<li id="profile-${profile.id}" class="list-group-item">Match name: ${profile.firstname} - age: ${profile.age} - gender: ${profile.gender} - who likes: ${profile.pet} - contact info: ${profile.contact}</li>`;
$listeMatches.append(liToAppend);
}
/* Ajoute un élément li dans la liste de matches
function appendToListMyProfile(profile) {
liToAppend = `<li id="profile-${profile.id}" class="list-group-item">name: ${profile.firstname} - age: ${profile.age} - gender: ${profile.gender} - who likes: ${profile.pet} - contact info: ${profile.contact}`;
profile.lovers.forEach( lover => liToAppend+= ` - interested in: ${lover.partnerGender} - who likes ${lover.partnerPet}`);
liToAppend+= `</li>`;
$listeMyProfile.append(liToAppend);
}*/
/* Ajout un lover à une profile existante*/
function addLoverToProfile(idProfile, idLover) {
$.ajax({
type: "POST",
url: "http://localhost:8080/api/profiles/"+idProfile+"/lovers",
data: JSON.stringify({"idLover" : idLover}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
appendToListProfileSelect(data);
appendToListProfileSelect2(data);
appendToListProfileDelete(data);
}
});
};
});
\ No newline at end of file
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<title>Love is just a click away!</title>
</head>
<body style="background-color:honeydew; text-align: center;">
<p><h1 style="color:deeppink;">Love is just a click away!</h1></p>
<main>
<p>
<h2 style="color:darkorchid;">Create your profile: </h2>
<div class="form-group">
<p><label>Now tell us about yourself :</label></p>
<p>Firstname : <input type="text" name="firstname" id="firstname-input"></p>
<p>Age : <input type="number" name="age" id="age-input"></p>
<p>Gender (Male/Female/Other): <input type="text" name="gender" id="gender-input"></p>
<p>For a pet, what do you prefer (cats/dogs/other) ? : <input type="text" name="pet" id="pet-input"></p>
<p>Contact information for potential lovers : <input type="text" name="contact" id="contact-input"></p>
<p>Choose your love interest from this list (if not available in the list, add it to the list in the next section) : </p>
<select id="selectLovers"></select>
<p id="demo" style="display:none">Thank you for creating your profile. Scroll down and search for love!</p>
<p><input type="button" id="addbtnProfile" name="addbtn" value="Add" class="btn btn-primary btn-sm" onclick="document.getElementById('demo').style.display='block'"></p>
</div>
</p>
<h2 style="color:mediumseagreen;">Who are you interesting in finding (if not already available in the list) ?</h2>
<div class="form-group">
<p><label>You're interested in someone who :</label></p>
<p>is Male/Female/Other : <input type="text" name="partnerGender" id="partner-input"></p>
<p>Likes cats/dogs/other for a pet : <input type="text" name="partnerPet" id="partner-pet-input"></p>
<input type="button" id="addbtnLover" name="addbtn" value="Add" class="btn btn-primary btn-sm"/>
<ul class="list-group" id="listLovers">
</ul>
</div>
<p>
<h2 style="color:crimson;">Ready to find love?</h2>
<p>Select your profile and search for matches by clicking on your green ";)" button : </p>
<ul class="list-group" id="listProfilesSelect">
</ul>
<p>Here are your matches : </p>
<ul class= "list-group" id="listMatches"></ul>
</p>
<p>
<h2 style="color:darkcyan;">Everyone changes at some point in their lives...</h2>
<div class="form-group">
<p>Select the profile you wish to modify : </p>
<p><select id="listProfilesSelect2"></select></p>
<p>Modify your profile info : </p>
<p>Firstname : <input type="text" name="firstname" id="firstname-modify"><input type="button" id="modifyFirstname" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>Age : <input type="number" name="age" id="age-modify"><input type="button" id="modifyAge" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>Gender (Male/Female/Other): <input type="text" name="gender" id="gender-modify"><input type="button" id="modifyGender" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>For a pet, what do you prefer (cats/dogs/other) ? : <input type="text" name="pet" id="pet-modify"><input type="button" id="modifyPet" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>Contact information for potential lovers : <input type="text" name="contact" id="contact-modify"><input type="button" id="modifyContact" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>Want to choose a new love interest ?: </p>
<p><select id="selectLovers2"></select><input type="button" id="modifyLover" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>See your new profile now that you have made all your modifications: </p>
<p><input type="button" id="seeModifications" name="addbtn" value="Modified" class="btn btn-primary btn-sm"></p>
</div>
</p>
<p>
<h2>Are you now spoken for?</h2>
<div class="form-group">
<label>Want to delete your profile ? Click on the red "X" button :</label>
<ul class= "list-group" id="listProfilesDelete">
</ul>
</div>
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="hello1.js"></script>
</main>
</body>
</html>
\ No newline at end of file
/*
let firstname = $('#firstname-modify').val();
let age = $('#age-modify').val();
let gender = $('#gender-modify').val();
let pet = $('#pet-modify').val();
let contact= $('#contact-modify').val();
let idLover = $selectLovers2.val();
if(age !== null){
$.ajax({
type: "PATCH",
url: "http://localhost:8080/api/profiles/"+idProfile.replace('profile-','')+"/updateAge",
data: JSON.stringify({ "updateAge" : age}),
contentType: "application/json; charset=utf-8",
dataType: "json",
}); }
if(firstname !== ''){
$.ajax({
type: "PATCH",
url: "http://localhost:8080/api/profiles/"+idProfile.replace('profile-','')+"/updateFirstname",
data: JSON.stringify({ "updateFirstname" : firstname}),
contentType: "application/json; charset=utf-8",
dataType: "json",
}); }
if(gender !== null){
$.ajax({
type: "PATCH",
url: "http://localhost:8080/api/profiles/"+idProfile.replace('profile-','')+"/updateGender",
data: JSON.stringify({ "updateGender" : gender}),
contentType: "application/json; charset=utf-8",
dataType: "json",
}); }
if(pet !== null){
$.ajax({
type: "PATCH",
url: "http://localhost:8080/api/profiles/"+idProfile.replace('profile-','')+"/updatePet",
data: JSON.stringify({ "updatePet" : pet}),
contentType: "application/json; charset=utf-8",
dataType: "json",
}); }
if(contact !== null){
$.ajax({
type: "PATCH",
url: "http://localhost:8080/api/profiles/"+idProfile.replace('profile-','')+"/updateContact",
data: JSON.stringify({ "updateContact" : contact}),
contentType: "application/json; charset=utf-8",
dataType: "json",
}); }
if(idLover !== null){
$.ajax({
type: "PATCH",
url: "http://localhost:8080/api/profiles/"+idProfile.replace('profile-','')+"/updateLovers",
data: JSON.stringify({ "updateLovers" : idLover}),
contentType: "application/json; charset=utf-8",
dataType: "json",
}); }
$('#firstname-modify').val('');
$('#age-modify').val('');
$('#gender-modify').val('');
$('#pet-modify').val('');
$('#contact-modify').val('');
$.ajax({
type: "GET",
url: "http://localhost:8080/api/profiles"+idProfile.replace('profile-',''),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
myNewProfile(data);
},
});
return false;
*/
<p>Here is the profile you want to change : </p>
<p id="ProfileToModify"></p>
<p>Modify your profile info : </p>
<p>Firstname : <input type="text" name="firstname" id="firstname-modify"><input type="button" id="modifyFirstname" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>Age : <input type="number" name="age" id="age-modify"><input type="button" id="modifyAge" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>Gender (Male/Female/Other): <input type="text" name="gender" id="gender-modify"><input type="button" id="modifyGender" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>For a pet, what do you prefer (cats/dogs/other) ? : <input type="text" name="pet" id="pet-modify"><input type="button" id="modifyPet" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>Contact information for potential lovers : <input type="text" name="contact" id="contact-modify"><input type="button" id="modifyContact" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>Want to choose a new love interest ?: </p>
<p><select id="selectLovers2"></select><input type="button" id="modifyLover" name="addbtn" value="Modify" class="btn btn-primary btn-sm"></p>
<p>See your new profile now that you have made all your modifications: </p>
<p><input type="button" id="seeModifications" name="addbtn" value="Modified" class="btn btn-primary btn-sm"></p>
\ No newline at end of file
package com.example.trial;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TrialApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment