From 4075742a2508950d4b20ef7ef93ce2af55188daf Mon Sep 17 00:00:00 2001 From: Mirco Nasuti <mirco.nasuti@chuv.ch> Date: Wed, 13 Jul 2016 15:22:13 +0200 Subject: [PATCH] refactoring articleApi to use Spring Data --- .../org/hbp/mip/controllers/ArticlesApi.java | 71 +++++++------------ 1 file changed, 26 insertions(+), 45 deletions(-) diff --git a/src/main/java/org/hbp/mip/controllers/ArticlesApi.java b/src/main/java/org/hbp/mip/controllers/ArticlesApi.java index 6d2f1d96e..3fb682dd8 100644 --- a/src/main/java/org/hbp/mip/controllers/ArticlesApi.java +++ b/src/main/java/org/hbp/mip/controllers/ArticlesApi.java @@ -161,55 +161,36 @@ public class ArticlesApi { @RequestBody @ApiParam(value = "Article to update", required = true) @Valid Article article ) { - /*User user = mipApplication.getUser(); - try{ - String author = (String) session - .createQuery("select U.username from User U, Article A where A.createdBy = U.username and A.slug = :slug") - .setString("slug", slug) - .uniqueResult(); + User user = mipApplication.getUser(); - if(!user.getUsername().equals(author)) - { - session.getTransaction().commit(); - return new ResponseEntity<>(HttpStatus.FORBIDDEN); - } + String author = articleRepository.findOne(slug).getCreatedBy().getUsername(); + + if(!user.getUsername().equals(author)) + { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + String oldTitle = articleRepository.findOne(slug).getTitle(); - String oldTitle = (String) session - .createQuery("select title from Article where slug= :slug") - .setString("slug", slug) - .uniqueResult(); - - String newTitle = article.getTitle(); - - if(!newTitle.equals(oldTitle)) { - Long count; - int i = 0; - do { - i++; - newTitle = article.getTitle(); - count = (Long) session - .createQuery("select count(*) from Article where title= :title") - .setString("title", newTitle) - .uniqueResult(); - if (count > 0 && !newTitle.equals(oldTitle)) { - if (i > 1) { - newTitle = newTitle.substring(0, newTitle.length() - 4); - } - article.setTitle(newTitle + " (" + i + ")"); + String newTitle = article.getTitle(); + + if(!newTitle.equals(oldTitle)) { + Long count; + int i = 0; + do { + i++; + newTitle = article.getTitle(); + count = articleRepository.countByTitle(newTitle); + if (count > 0 && !newTitle.equals(oldTitle)) { + if (i > 1) { + newTitle = newTitle.substring(0, newTitle.length() - 4); } - } while (count > 0 && !newTitle.equals(oldTitle)); - } + article.setTitle(newTitle + " (" + i + ")"); + } + } while (count > 0 && !newTitle.equals(oldTitle)); + } - session.update(article); - session.getTransaction().commit(); - } catch (Exception e) - { - if(session.getTransaction() != null) - { - session.getTransaction().rollback(); - throw e; - } - }*/ + articleRepository.save(article); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } -- GitLab