1 pièce(s) jointe(s)
Probleme avec Tomcat Serveur embarqué
Salut
afin de permettre a Spring Boot de configurer le chargement des pages JSP,
il faudra mettre dans le fichier pom.xml
cette dependence :
Code:
1 2 3 4 5
|
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency> |
Sinon tu auras des pages comme celle-ci :
Pièce jointe 389303
et si lorsque du cote client vous essayez de vous connecter avec votre login et mot de passe et que vous recevez ceci comme erreur :
Code:
Could not extract response: no suitable HttpMessageConverter found for response type [class User] and content type [application/octet-stream]
alors vous devez effectuer cette modification dans la classe
LoginController:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
@PostMapping(value = "/login")
public ModelAndView login(@Valid @ModelAttribute("userForm") UserDto userForm,
BindingResult bindingResult, ModelAndView modelAndView) {
System.out.println("login .....................");
modelAndView.setViewName("loginForm");
if (bindingResult.hasErrors()) {
return modelAndView;
}
Map<String, String> variables = new HashMap<String, String>(1);
variables.put("loginName", userForm.getLogin());
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
ResponseEntity<User> userExists = restTemplate.getForEntity(configurationService.getUrl() +"user/users/{loginName}", User.class, variables);
System.out.println("URL2 :" + configurationService.getUrl() +"user/users/{loginName}");
User user = userExists.getBody();
if (user == null) {//ceci nous évite d'écrire une page de gestion des erreurs
modelAndView.addObject("saveError", "Aucun utilisateur trouvé avec ce compte");
return modelAndView;
}
modelAndView.setViewName("loginSuccess");
return modelAndView;
} |
le code ajouté est en rouge.
Eric
simplification test Junit du service ?
bonjour,
petit a petit je continue avec ce tuto qui est vraiment riche. j'attaque les tests.
je vous fait part de la légère modification que j'ai effectuée dans les déclarations en haut de la classe de test UserServiceImplTest .
j'ai remplacé le pavé de code suivant
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
@TestConfiguration //création des Beans nécessaires pour les tests
static class UserServiceImplTestContextConfiguration {
@Bean//bean de service
public UserService userService () {
return new UserServiceImpl();
}
@Bean//nécessaire pour encrypter le mot de passe sinon échec des tests
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
} |
par l'annotation @SpringBootTest
Voici ce que ça donne :
(NB : version dans pom.xml : springboot 2.0.2)
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
private static Logger LOGGER = LoggerFactory.getLogger(UserServiceImplTest.class);
@Autowired
private UserService userService;
@MockBean // création d'un mockBean pour UserRepository
private UserRepository userRepository;
@Test
public void testGetAllUsers() {
User user = new User("Dupont", "password", 1);
Role role = new Role("USER_ROLE");// initialisation du role utilisateur
Set<Role> roles = new HashSet<>();
roles.add(role);
user.setRoles(roles);
List<User> allUsers = Arrays.asList(user);
Mockito.when(userRepository.findAll()).thenReturn(allUsers);
Collection<User> users = userService.getAllUsers();
assertNotNull(users);
assertEquals(users, allUsers);
assertEquals(users.size(), allUsers.size());
Mockito.verify(userRepository).findAll();
}
...
} |
pas de contrepartie au niveau configuration; ça fonctionne très bien d'emblée; y'a t il un inconvénient quelque part ? je n'en ai pas remarqué mais si quelqu'un a des commentaires je suis preneur evidemment.
merci
bonne journée
Comment les infos sur le serveur sont récupérées
Bonjour
J'ai commencé à suivre votre excellent tuto et j'ai quelques questions.
Concernant l'envoi d'une requête "ping" au serveur à l'adresse app.serveur.url = http://localhost:8080/springboot-restserver/, vous dites que l'adresse du serveur est configurée dans le fichier application.properties et accessible grâce à la classe utilitaire ci-dessous:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
package com.bnguimgo.springbootrestclient.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class PropertiesConfigurationService{
@Value("${app.serveur.url}") // injection via application.properties
private String url="";
@Value("${app.serveur.pingServeur}")
private String pingServeur;
@Value("${app.serveur.ok}")
private String pingServeurOk;
@Value("${app.serveur.ko}")
private String pingServeurKo;
@Value("${nextpage.message}")
private String message;
@Value("${spring.profiles.active}")
private String profileActif;
// getters, setters
public String getUrl() {
return url;
}
public String getPingServeur() {
return pingServeur;
}
public String getPingServeurOk() {
return pingServeurOk;
}
public String getPingServeurKo() {
return pingServeurKo;
}
public String getMessage() {
return message;
}
public String getProfileActif() {
return profileActif;
}
} |
Citation:
Cette classe utilitaire PropertiesConfigurationService permet de récupérer l'URL du serveur stockée dans le fichier de configuration application.properties.
Pourtant dans le fichier application.properties, je ne vois toujours pas où est ce que l'url du serveur est récupérée:
Code:
1 2 3 4
| #Au démarrage de l'application, en cas d'erreur
server.error.whitelabel.enabled = false
#Chargement du profil par defaut dev
spring.profiles.active=dev |
Merci
Où trouver les sources du tuto ?
Bonjour Marc,
Le lien pour les sources est disponible au chapitre d'introduction, sinon le voici!
Il faudra juste te connecter avec ton login/pass de developpez.com
Bon tuto !!
demande d'aide suite à la lecture de votre tuto springboot
Bonjour à tous, merci à @parchemal pour ce super tuto. Je suis tombé dessus en cherchant à faire un webservice rest et une application web cliente permettant de manipuler cette api.
Je ne sais pas si c'est le bon lieu pour demander cela sinon je m'en excuse et déplacerais le post.
N'ayant pas une grande expérience dans le domaine, j'espère trouver avec vous des indications pour arriver à mon but.
Je dois réaliser un webservice qui permet de gérer des vidéos (ajout, modification, suppression d'une vidéo); une vidéo est caractérisé par un titre, un id qui est dans les faits l'identifiant youtube de cette vidéo et un ensemble de tags associé à cette vidéo. et un tag, c'est un id, et un nom.
Autre chose: une vidéo peut donc être lié à plusieurs tags et inversement, un tag peut être lié à plusieurs vidéos.
Voici donc mon approche pour le webservice : j'ai définis trois entité Video, Tag, et VideoTag qui est la table issue de l'association entre les deux entité Video et Tag
-------------------------------------------------------------------------------package entity -------------------------------------------------------------------------------------
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
|
@Entity(name = "Video")
@Table (name = "video")
@NaturalIdCache
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Video implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="increment"
)
@GenericGenerator(
name = "increment",
strategy = "increment"
)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@NaturalId
@NotBlank
@Column (name = "yid", unique = true)
private String youtubeId;
@NotBlank
private String title;
private String description;
private Long duration;
@OneToMany(
fetch = FetchType.EAGER, // LAZY me genere une erreur dans la fabrication du JSON
mappedBy = "video",
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
orphanRemoval = true
)
@JsonManagedReference
private Set<VideoTag> tags = new HashSet<>();
public Video() {}
public Video(@NotNull String youtubeId, @NotNull String title, String description, Long duration, Set<VideoTag> tags) {
super();
this.youtubeId = youtubeId;
this.title = title;
this.description = description;
this.duration = duration;
this.tags = tags;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getYoutubeId() {
return youtubeId;
}
public void setYoutubeId(String youtubeId) {
this.youtubeId = youtubeId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public Set<VideoTag> getTags() {
return tags;
}
public void setTags(Set<VideoTag> tags) {
this.tags = tags;
}
public void addTag(Tag tag) {
VideoTag videoTag = new VideoTag(this, tag);
tags.add(videoTag);
}
public void removeTag(Tag tag) {
for (Iterator<VideoTag> iterator = tags.iterator();iterator.hasNext(); ) {
VideoTag videoTag = iterator.next();
if (videoTag.getVideo().equals(this) && videoTag.getTag().equals(tag)) {
iterator.remove();
videoTag.setVideo(null);
videoTag.setTag(null);
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Video video = (Video) o;
return Objects.equals(youtubeId, video.youtubeId);
}
@Override
public int hashCode() {
return Objects.hash(youtubeId);
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
@Entity(name = "Tag")
@Table(name = "tag")
@NaturalIdCache
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="increment"
)
@GenericGenerator(
name = "increment",
strategy = "increment"
)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@NotBlank
@NaturalId
@Column( name = "name", unique = true, nullable = false)
private String name;
@OneToMany(
mappedBy = "tag",
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
orphanRemoval = true)
@JsonIgnore
Set<VideoTag> videos = new HashSet<>();
public Tag() {}
public Tag(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<VideoTag> getVideos() {
return videos;
}
public void setVideos(Set<VideoTag> videos) {
this.videos = videos;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tag tag = (Tag) o;
return Objects.equals(name, tag.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
@Entity(name = "VideoTag")
@Table(name = "video_tag")
public class VideoTag implements Serializable{
private static final long serialVersionUID = 1L;
private static final Boolean DEFAULT_VALUE_MAIN_TAG = false;
@EmbeddedId
@JsonIgnore
private VideoTagId id;
@ManyToOne
@MapsId("videoId")
@JsonBackReference
private Video video;
@ManyToOne
@MapsId("tagId")
private Tag tag;
@JsonIgnore
@Column(name = "is_main_tag", nullable = false, columnDefinition = "BOOLEAN")
private Boolean isMainTag;
protected VideoTag() {}
public VideoTag(Video video, Tag tag) {
this(video, tag, DEFAULT_VALUE_MAIN_TAG);
}
public VideoTag(Video video, Tag tag, Boolean isMainTag) {
this.video = video;
this.tag = tag;
this.isMainTag = isMainTag;
// creation de la clé primaire
this.id = new VideoTagId(video.getId(), tag.getId());
// mise à jour des relations pour assurer l'intégrité référentielle
video.getTags().add(this);
tag.getVideos().add(this);
}
public VideoTagId getId() {
return id;
}
public void setId(VideoTagId id) {
this.id = id;
}
public Video getVideo() {
return video;
}
public void setVideo(Video video) {
this.video = video;
}
public Tag getTag() {
return tag;
}
public void setTag(Tag tag) {
this.tag = tag;
}
public Boolean getIsMainTag() {
return isMainTag;
}
public void setIsMainTag(Boolean isMainTag) {
this.isMainTag = isMainTag;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
VideoTag that = (VideoTag) o;
return Objects.equals(video, that.video) &&
Objects.equals(tag, that.tag);
}
@Override
public int hashCode() {
return Objects.hash(video, tag);
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
@Embeddable
public class VideoTagId implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "vid")
private Long videoId;
@Column(name = "tid")
private Long tagId;
protected VideoTagId() {}
public VideoTagId(Long videoId, Long tagId) {
this.videoId = videoId;
this.tagId = tagId;
}
public Long getVideoId() {
return videoId;
}
public void setVideoId(Long videoId) {
this.videoId = videoId;
}
public Long getTagId() {
return tagId;
}
public void setTagId(Long tagId) {
this.tagId = tagId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
VideoTagId that = (VideoTagId) o;
return Objects.equals(videoId, that.videoId) &&
Objects.equals(tagId, that.tagId);
}
@Override
public int hashCode() {
return Objects.hash(videoId, tagId);
}
} |
------------------------------------------------------------------------package repository -----------------------------------------------------------------------------------------
Code:
1 2 3 4 5
|
@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {
Optional<Tag> findByName(String name);
} |
Code:
1 2 3 4 5 6
|
@Repository
public interface VideoRepository extends JpaRepository<Video, Long>{
@Query(value="SELECT v.* FROM video_tag vt JOIN tag t ON t.id = vt.tag_id JOIN video v ON v.id = vt.video_id WHERE t.name IN ('') UNION SELECT v.* FROM video_tag vt JOIN tag t ON t.id = vt.tag_id JOIN video v ON v.id = vt.video_id WHERE t.name IN (:mtags) OR t.name IN (:stags);", nativeQuery=true) // pouvoir recuperer les vidéos qui matchent les tags principaux se trouvant mtags et ceux qui matchent les tags sécondaires stags avec en premier, les videos matchant les tags contenus dans mtags
List<Video> findAllVideosByTags(@Param("mtags") List<String> mtags,@Param("stags") List<String> stags);
} |
-----------------------------------------------------------------------package controller --------------------------------------------------------------------------------
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
@RestController
@RequestMapping(path = "/tags", produces = MediaType.APPLICATION_JSON_VALUE)
public class TagController {
@Autowired ITagService tagService;
@GetMapping
ResponseEntity<Collection<Tag>> all() {
return new ResponseEntity<>(tagService.findAll(), HttpStatus.OK);
}
@PostMapping
ResponseEntity<Tag> addTag(@RequestBody Tag newTag) {
return new ResponseEntity<>(tagService.save(newTag), HttpStatus.CREATED);
}
@GetMapping("/{id}")
ResponseEntity<Tag> getOneTag(@PathVariable Long id) {
return tagService.findById(id)
.map(tag -> {
return new ResponseEntity<>(tag, HttpStatus.OK);
})
.orElseThrow(() -> new ResourceNotFoundException("Tag", id));
}
@PutMapping("/{id}")
ResponseEntity<Tag> replaceTag(@RequestBody Tag newTag, @PathVariable Long id) {
return tagService.findById(id)
.map(tag -> {
tag.setName(newTag.getName());
return new ResponseEntity<Tag>(tagService.save(tag), HttpStatus.OK);
})
.orElseGet(() -> {
newTag.setId(id);
return new ResponseEntity<Tag>(tagService.save(newTag), HttpStatus.CREATED);
});
}
@DeleteMapping("/{id}")
ResponseEntity<Void> deleteTag(@PathVariable Long id) {
tagService.deleteById(id);
return new ResponseEntity<Void>(HttpStatus.OK);
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
@RestController
@RequestMapping(path = "/videos", produces = MediaType.APPLICATION_JSON_VALUE)
public class VideoController {
@Autowired private IVideoService videoService;
@GetMapping
List<Video> all() {
return videoService.findAllVideos();
}
@GetMapping("/{id}")
Video one(@PathVariable Long id) {
Video video = videoService.findVideoById(id);
return video;
}
@GetMapping("/search")
ResponseEntity<Collection<Video>> findVideosByTagNames(@RequestParam("mt") List<String> mtags, @RequestParam("st") List<String> stags) {
if(mtags.isEmpty() ) {
mtags.add("");
}
if(stags.isEmpty()) {
stags.add("");
}
return new ResponseEntity<>(
videoService.findVideosByTags(mtags, stags).stream()
.distinct()
.collect(Collectors.toList()), HttpStatus.OK);
}
@GetMapping("{id}/tags")
ResponseEntity<Collection<Tag>> getTagsForIdVideo(@PathVariable Long id) {
return new ResponseEntity<>(videoService.findTagsByIdVideo(id), HttpStatus.OK);
}
@PostMapping
Video newVideo(@RequestBody Video newVideo) {
return videoService.insertVideo(newVideo);
}
// @PostMapping
// ResponseEntity<Object> newVideo(@RequestBody Video newVideo) {
// Video savedVideo = videoService.insertVideo(newVideo);
//
// URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
// .buildAndExpand(savedVideo.getId()).toUri();
// return ResponseEntity.created(location).build();
// }
@PutMapping("/{id}/tags/aid")
Video addTagsByIdsToVideo(@PathVariable(name = "id") Long idVideo, @RequestParam (name = "ids") List<Long> tagIds) {
return videoService.addTagsByIdsToVideo(idVideo, tagIds);
}
@PutMapping("/{id}/tags/aname")
Video addTagsByNamesToVideo(@PathVariable(name = "id") Long idVideo, @RequestParam (name = "names") List<String> tagNames) {
return videoService.addTagsByNamesToVideo(idVideo, tagNames);
}
@PutMapping("/{id}/tags/did")
Video delTagsByIdsToVideo(@PathVariable(name = "id") Long idVideo, @RequestParam (name = "ids") List<Long> tagIds) {
return videoService.delTagsByIdsToVideo(idVideo, tagIds);
}
@PutMapping("/{id}/tags/dname")
Video delTagsByNamesToVideo(@PathVariable(name = "id") Long idVideo, @RequestParam (name = "names") List<String> tagNames) {
return videoService.delTagsByNamesToVideo(idVideo, tagNames);
}
@PutMapping("/{id}")
Video replaceVideo(@RequestBody Video newVideo, @PathVariable Long id) {
videoService.findVideoById(id);
return videoService.updateVideoById(newVideo, id);
}
// @PutMapping("/{id}")
// ResponseEntity<Object> replaceVideo(@RequestBody Video newVideo, @PathVariable Long id) {
// Optional<Video> video = videoService.findById(id);
// if(!video.isPresent()) {
// return ResponseEntity.notFound().build();
// }
// newVideo.setId(id);
// Video updatedVideo = videoService.save(newVideo);
// URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
// .buildAndExpand(updatedVideo.getId()).toUri();
// return ResponseEntity.created(location).build();
// }
@DeleteMapping("/{id}")
ResponseEntity<Object> deleteVideo(@PathVariable Long id) {
videoService.deleteVideoById(id);
return ResponseEntity.noContent().build();
}
} |
Code:
1 2 3 4 5 6 7 8 9 10
|
@ControllerAdvice
public class ErrorAdvice {
@ResponseBody
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
String videoNotFoundHandler(ResourceNotFoundException ex) {
return ex.getMessage();
}
} |
------------------------------------------------------------------------------package service-----------------------------------------------------------------------------------------------------
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
@Service
public class VideoServiceImpl implements IVideoService {
@Autowired private VideoRepository videoRepository;
@Autowired private ITagService tagService;
@Override
public Video findVideoById(Long id) {
return videoRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Video", id));
}
@Override
public List<Video> findAllVideos() {
return videoRepository.findAll();
}
@Override
public List<Video> findVideosByTags(List<String> mtags, List<String> stags) {
List<Video> videos = videoRepository.findAllVideosByTags(mtags, stags);
return videos;
}
@Override
public Video updateVideoById(Video newVideo, Long id) {
return videoRepository.findById(id)
.map(video -> {
video.setYoutubeId(newVideo.getYoutubeId());
video.setTitle(newVideo.getTitle());
video.setDescription(newVideo.getDescription());
video.setDuration(newVideo.getDuration());
return videoRepository.save(video);
})
.orElseGet(() -> {
newVideo.setId(id);
return videoRepository.save(newVideo);
});
}
@Override
public Video insertVideo(Video video) {
return videoRepository.save(video);
}
@Override
public void deleteVideoById(Long id) {
Video video = findVideoById(id);
videoRepository.delete(video);
}
@Transactional
@Override
public Video addTagsByIdsToVideo(Long idVideo, List<Long> idsTag) {
Video video = findVideoById(idVideo);
for(Long tagId : idsTag) {
Optional<Tag> tagOptional = tagService.findById(tagId);
if(tagOptional.isPresent()) {
video.addTag(tagOptional.get());
}
}
return save(video);
}
@Override
public Video delTagsByIdsToVideo(Long idVideo, List<Long> idsTag) {
Video video = findVideoById(idVideo);
for(Long tagId : idsTag) {
Optional<Tag> tagOptional = tagService.findById(tagId);
// si tag present on l'enleve de la video sinon on fait rien
if(tagOptional.isPresent()) {
video.removeTag(tagOptional.get());
}
}
return save(video);
}
@Override
public Video addTagsByNamesToVideo(Long idVideo, List<String> names) {
Video video = findVideoById(idVideo);
for(String tagName : names) {
Optional<Tag> tagOptional = tagService.findByName(tagName);
// si tag present on l'ajoute
Tag tag;
if(tagOptional.isPresent()) {
tag = tagOptional.get();
}else { // si non present on le cree et on l'ajoute
tag = tagService.save(new Tag(tagName));
}
video.addTag(tag);
}
return save(video);
}
@Override
public Video delTagsByNamesToVideo(Long idVideo, List<String> names) {
Video video = findVideoById(idVideo);
for(String tagName : names) {
Optional<Tag> tagOptional = tagService.findByName(tagName);
// si tag present on l'enleve de la video sinon on fait rien
if(tagOptional.isPresent()) {
video.removeTag(tagOptional.get());
}
}
return save(video);
}
@Override
public Video updateVideo(Video video) {
return videoRepository.save(video);
}
@Override
public Optional<Video> findById(Long id) {
return videoRepository.findById(id);
}
@Override
public Video save(Video newVideo) {
return videoRepository.save(newVideo);
}
@Override
public List<Tag> findTagsByIdVideo(Long idVideo) {
return findVideoById(idVideo).getTags().stream()
.map(VideoTag::getTag)
.collect(Collectors.toList());
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
public interface IVideoService {
Video findVideoById(Long id);
List<Video> findAllVideos();
List<Video> findVideosByTags(List<String> mtags, List<String> stags);
Video updateVideo(Video video);
Video insertVideo(Video video);
Video updateVideoById(Video newVideo, Long id);
void deleteVideoById(Long id);
Video addTagsByIdsToVideo(Long idVideo, List<Long> idsTag);
Video delTagsByIdsToVideo(Long idVideo, List<Long> idsTag);
Video addTagsByNamesToVideo(Long idVideo, List<String> names);
Video delTagsByNamesToVideo(Long idVideo, List<String> names);
Optional<Video> findById(Long id);
Video save(Video newVideo);
List<Tag> findTagsByIdVideo(Long idVideo);
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
public interface ITagService {
public Tag save(Tag tag);
public List<Tag> findAll();
public Optional<Tag> findById(Long id);
public List<Tag> saveAll(Iterable<Tag> tags);
public void deleteById(Long id);
public Tag getOne(Long id);
public void delete(Tag tag);
public void deleteAll(Iterable<Tag> tags);
public void deleteAll();
public boolean existsById(Long id);
public Long count();
public Optional<Tag> findByName(String name);
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
@Service
public class TagServiceImpl implements ITagService {
@Autowired private TagRepository tagRepository;
public Tag save(Tag tag) {
return tagRepository.save(tag);
}
public List<Tag> findAll() {
return tagRepository.findAll(Sort.by(Sort.Direction.ASC, "id"));
}
public Optional<Tag> findById(Long id) {
return tagRepository.findById(id);
}
public List<Tag> saveAll(Iterable<Tag> tags) {
return tagRepository.saveAll(tags);
}
public void deleteById(Long id) {
Tag tag = tagRepository.findById(id).get();
if(tag != null && !tag.getVideos().isEmpty()) {
tag.getVideos().clear();
}
tagRepository.delete(tag);
}
public Tag getOne(Long id) {
return tagRepository.getOne(id);
}
public void delete(Tag tag) {
tagRepository.delete(tag);
}
public void deleteAll(Iterable<Tag> tags) {
tagRepository.deleteAll(tags);
}
public void deleteAll() {
tagRepository.deleteAll();
}
public boolean existsById(Long id) {
return tagRepository.existsById(id);
}
public Long count() {
return tagRepository.count();
}
@Override
public Optional<Tag> findByName(String name) {
return tagRepository.findByName(name);
}
} |
__________________________________________APP principal__________________________________________________________
Code:
1 2 3 4 5 6 7
|
@SpringBootApplication
public class ProjetVideoApplication {
public static void main(String[] args) {
SpringApplication.run(ProjetVideoApplication.class, args);
}
} |
Je souhaite obtenir une présentation comme celle-ci :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
[
{
"id" : 1,
"youtubeId": "hgfdgdU_riE",
"title": "Video de test d'ajout",
"description": "Une video pour tester l'ajout avec POST",
"duration": 300,
"tags" : [
{
"id" : 1,
"name" : "tuto"
},
{
"id" : 2,
"name" : "rest"
}
]
},
{
"id" : 2,
"youtubeId": "hgfdgdU_riE",
"title": "Autre Video",
"description": "autre description",
"duration": 300,
"tags" : [
{
"id" : 1,
"name" : "tuto"
}
]
},
{
"id" : 3,
"youtubeId": "hgfdgdU_riE",
"title": "Autre Video",
"description": "autre description",
"duration": 300,
"tags" : []
}
] |
Ceci est la partie webservice
j'ai pas encore commencé le client.
Mais déjà j'aimerais pouvoir être sûr que le webservice fonctionne avec tous les besoins c'est-à-dire la recherche des vidéos par liste de tags principaux et secondaires.
j'aimerais avoir votre avis et suggestions sachant que pour l'instant la suppression d'un tag en passant par le service tagservice entraine la suppression du lien dans VideoTag (jusque là ça va), mais aussi la vidéo correspondante. Pareil quand j'enleve un tag d'une vidéo je veux juste enlever le lien entre le tag et la vidéo mais ça ne fonctionne pas, le lien n'est pas supprimé dans videoTag.
Merci pour vos retour.
1 pièce(s) jointe(s)
Méthodes findOne et delete non reconnues
Bonjour
Il me semble qu'il y ait des problèmes de compatibilité concernant la méthode findOne et delete qui se trouvent dans UserController.java.
Dans le service User, la méthode findOne(Long) n'est plus disponible et j'ai lu dans les commentaires du tuto qu'il fallait la remplacer par findById et la signature devient "Optional<User> getUserById(Long id) throws BusinessResourceException;". Et ça marche.
Maintenant dans la Class UserController.java , je suis obligé de changer :
Code:
User userToUpdate = userService.getUserById(id);
par
Code:
Optional<User> userToUpdate = userService.getUserById(id);
Sauf que les méthodes getRoles, setLogin, setPassword, setActive, saveOrUpdateUser me génèrent des erreurs du genre:
Citation:
The method getRoles() is undefined for the type Optional<User>
Pièce jointe 533930
Ensuite concernant la méthode delete:
Code:
1 2 3 4 5 6 7 8 9
| @Override
@Transactional(readOnly=false)
public void deleteUser(Long id) throws BusinessResourceException {
try{
userRepository.delete(id);
}catch(Exception ex){
throw new BusinessResourceException("Delete User Error", "Erreur de suppression de l'utilisateur avec l'identifiant: "+id, HttpStatus.INTERNAL_SERVER_ERROR);
}
} |
j'ai ce message d'erreur:
Citation:
The method delete(User) in the type CrudRepository<User,Long> is not applicable for the arguments (Long)
Par quelle méthode dois-je la remplacer pour régler ce problème?
Merci