From 5a446cfb69f0b46177ce4a4214b777db7334780b Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 18:14:26 +0100 Subject: [PATCH 001/125] =?UTF-8?q?Comprobar=20disponibilidad=20de=20URIs?= =?UTF-8?q?=20peri=C3=B3dicamente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/urlshortener/demo/Application.java | 2 + .../demo/controller/CheckApi.java | 6 +- .../urlshortener/demo/controller/UriApi.java | 11 ++-- .../controller/impl/CheckApiController.java | 22 ++++++- .../controller/impl/UriApiController.java | 62 ++++++++++++++++--- .../demo/schedule/checkSchedule.java | 57 +++++++++++++++++ .../urlshortener/demo/utils/CheckAlive.java | 21 +++++++ .../src/main/resources/application.properties | 2 +- .../java/urlshortener/team/Application.java | 1 + 9 files changed, 168 insertions(+), 16 deletions(-) create mode 100644 demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java create mode 100644 demo/src/main/java/urlshortener/demo/utils/CheckAlive.java diff --git a/demo/src/main/java/urlshortener/demo/Application.java b/demo/src/main/java/urlshortener/demo/Application.java index 63ff12cb..12dd3cac 100755 --- a/demo/src/main/java/urlshortener/demo/Application.java +++ b/demo/src/main/java/urlshortener/demo/Application.java @@ -4,10 +4,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.scheduling.annotation.EnableScheduling; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 +@EnableScheduling public class Application extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/demo/src/main/java/urlshortener/demo/controller/CheckApi.java b/demo/src/main/java/urlshortener/demo/controller/CheckApi.java index 71e05c20..72fb4d83 100644 --- a/demo/src/main/java/urlshortener/demo/controller/CheckApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/CheckApi.java @@ -18,8 +18,10 @@ public interface CheckApi { @ApiOperation(value = "Checks the state of the original URI", nickname = "checkURI", notes = "Checks the state of the original URI", tags={ "F5", }) @ApiResponses(value = { - @ApiResponse(code = 200, message = "The original URI is alive"), - @ApiResponse(code = 404, message = "The original URI is dead or the shortened URI doesn't exist") }) + @ApiResponse(code = 200, message = "The original URI is alive"), + @ApiResponse(code = 404, message = "The original URI is dead or the shortened URI doesn't exist"), + @ApiResponse(code = 418, message = "I'm a teapot") + }) @RequestMapping(value = "/check/{id}", method = RequestMethod.GET) ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id); diff --git a/demo/src/main/java/urlshortener/demo/controller/UriApi.java b/demo/src/main/java/urlshortener/demo/controller/UriApi.java index 09b14e14..91b0de13 100644 --- a/demo/src/main/java/urlshortener/demo/controller/UriApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/UriApi.java @@ -34,8 +34,9 @@ public interface UriApi { @ApiOperation(value = "Creates a new redirection", nickname = "createURI", notes = "Create a new URI redirection ", response = URIItem.class, tags={ "F0 - The app will short, storage and get URI's", }) @ApiResponses(value = { - @ApiResponse(code = 201, message = "The URI redirection has been successfully created", response = URIItem.class), - @ApiResponse(code = 400, message = "Error creating resource") }) + @ApiResponse(code = 201, message = "The URI redirection has been successfully created", response = URIItem.class), + @ApiResponse(code = 400, message = "The URI was not reachable", response = URIItem.class), + @ApiResponse(code = 418, message = "I'm a teapot", response = URIItem.class)}) @RequestMapping(value = "/uri", produces = { "application/json" }, consumes = { "application/json" }, @@ -54,8 +55,10 @@ public interface UriApi { @ApiOperation(value = "Returns the data of a redirection", nickname = "getURI", notes = "Get a URI redirection ", tags={ "F0 - The app will short, storage and get URI's", }) @ApiResponses(value = { - @ApiResponse(code = 307, message = "Redirect to the real URI"), - @ApiResponse(code = 404, message = "The given URI couldn't be found") }) + @ApiResponse(code = 307, message = "Redirect to the real URI"), + @ApiResponse(code = 404, message = "The given URI couldn't be found"), + @ApiResponse(code = 418, message = "I'm a teapot") + }) @RequestMapping(value = "/uri/{id}", method = RequestMethod.GET) ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVariable("id") String id); diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index bc3dc7c1..46fde4e8 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -9,8 +9,12 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import urlshortener.demo.controller.CheckApi; +import urlshortener.demo.utils.CheckAlive; import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.ProtocolException; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-21T05:15:43.072Z[GMT]") @@ -31,8 +35,22 @@ public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request) public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); + String uri = ""; //Se recupera la URI asociada a al parámetro "id" + CheckAlive c = new CheckAlive(); - return new ResponseEntity(HttpStatus.OK); - } + try { + HttpStatus httpStatus = HttpStatus.valueOf(c.makeRequest(uri)); + + return new ResponseEntity(httpStatus); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (ProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return new ResponseEntity(HttpStatus.I_AM_A_TEAPOT); + } } diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 9685ac36..8ffdab66 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -14,13 +14,14 @@ import urlshortener.demo.domain.ErrorItem; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.utils.CheckAlive; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; -import java.net.URI; -import java.net.URISyntaxException; +import java.io.IOException; +import java.net.*; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-21T05:15:43.072Z[GMT]") @@ -53,13 +54,38 @@ public ResponseEntity changeURI(@ApiParam(value = "Optional description public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body) { String accept = request.getHeader("Accept"); + CheckAlive c = new CheckAlive(); + URL url = null; + HttpStatus httpStatus = HttpStatus.I_AM_A_TEAPOT; URIItem uri = new URIItem(); uri.setId(""); - uri.setRedirection("https://google.es"); + uri.setRedirection(""); + uri.setHashpass(""); + try { + if (c.makeRequest(body.getUri()) == 200) { + + /*uri.setId(""); + uri.setRedirection(""); + uri.setHashpass("");*/ + + //Completar método, rellenar el objeto de tipo URIItem "uri" + + return new ResponseEntity(uri, HttpStatus.CREATED); + } + else { + return new ResponseEntity(uri, HttpStatus.BAD_REQUEST); + } + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (ProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } - return new ResponseEntity(uri, HttpStatus.TEMPORARY_REDIRECT); + return new ResponseEntity(uri, httpStatus); } public ResponseEntity deleteURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { @@ -69,19 +95,41 @@ public ResponseEntity deleteURI(@ApiParam(value = "",required=true) @PathV public ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); + CheckAlive c = new CheckAlive(); + URI location = null; + String redirection = ""; //Se recupera de la BD la URI asociada al parámetro "id" + - String redirection; URIItem item = uriService.get(id); if(item == null){ throw new UnknownEntityException(1, "Unknown URI: " + id); } redirection = item.getRedirection(); - URI location = null; try { - location = new URI(redirection); + if (c.makeRequest(redirection) == 200){ + //OK + //Para esa URI, se registra la fecha actual como útima fecha en la que estuvo viva + location = new URI(redirection); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setLocation(location); + return new ResponseEntity(responseHeaders, HttpStatus.TEMPORARY_REDIRECT); + } + else { + //Cualquier otra cosa aparte de un código 200 significará que la URI está muerta + //Se obtiene la última vez que la URI estuvo viva + // -Si la diferencia entre la fecha actual y la fecha recuperada es >= K, entonces la URI se borra + return new ResponseEntity(HttpStatus.NOT_FOUND); + } + } catch (URISyntaxException e) { e.printStackTrace(); + } catch (ProtocolException e) { + e.printStackTrace(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); } HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java new file mode 100644 index 00000000..49e80ac3 --- /dev/null +++ b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java @@ -0,0 +1,57 @@ +package urlshortener.demo.schedule; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import urlshortener.demo.domain.URIItem; +import urlshortener.demo.utils.CheckAlive; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-21T05:15:43.072Z[GMT]") + +@Component +public class checkSchedule { + + private static final Logger log = LoggerFactory.getLogger(checkSchedule.class); + + @Scheduled(fixedRate = 5000) + public void check() throws IOException { + CheckAlive c = new CheckAlive(); + + //HAY QUE CAMBIAR ESTE FRAGMENTO DE CÓDIGO Y RECUPERAR LA LISTA DE LA BD REAL + List uris = new ArrayList<>(); + URIItem u = new URIItem(); + u.setRedirection("https://google.es"); + uris.add(u); + u = new URIItem(); + u.setRedirection("https://stackoverflow.com"); + uris.add(u); + + log.info("Comienza el checkeo de las URI..."); + for (int i=0; i < uris.size(); i++){ + log.info("COMPROBANDO URI " + uris.get(i).getRedirection()); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (c.makeRequest(uris.get(i).getRedirection()) == 200){ + log.info("La URI " + uris.get(i).getRedirection() + " está viva."); + //OK + //Para esa URI, se registra la fecha actual como útima fecha en la que estuvo viva + } + else { + log.info("La URI " + uris.get(i).getRedirection() + " no responde."); + //Cualquier otra cosa aparte de un código 200 significará que la URI está muerta + //Se obtiene la última vez que la URI estuvo viva + // -Si la diferencia entre la fecha actual y la fecha recuperada es >= K, entonces la URI se borra + } + } + } + +} + diff --git a/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java b/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java new file mode 100644 index 00000000..c1bddc03 --- /dev/null +++ b/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java @@ -0,0 +1,21 @@ +package urlshortener.demo.utils; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class CheckAlive { + + //@org.springframework.beans.factory.annotation.Autowired + public CheckAlive() { + } + + public int makeRequest(String s) throws IOException { + URL url = new URL(s); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + return con.getResponseCode(); + } + +} \ No newline at end of file diff --git a/demo/src/main/resources/application.properties b/demo/src/main/resources/application.properties index ca4b8b41..0a134790 100755 --- a/demo/src/main/resources/application.properties +++ b/demo/src/main/resources/application.properties @@ -3,4 +3,4 @@ spring.datasource.platform=hsqldb spring.datasource.url=jdbc:hsqldb:mem:. spring.datasource.username=sa spring.datasource.password= -spring.datasource.driverClassName=org.hsqldb.jdbcDriver +spring.datasource.driverClassName=org.hsqldb.jdbcDriver \ No newline at end of file diff --git a/team/src/main/java/urlshortener/team/Application.java b/team/src/main/java/urlshortener/team/Application.java index 1f6ad655..5ea320bc 100644 --- a/team/src/main/java/urlshortener/team/Application.java +++ b/team/src/main/java/urlshortener/team/Application.java @@ -3,6 +3,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication public class Application { From dc60386e891073ad3a082f3d3cfe4184dd6cc9bb Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 18:30:21 +0100 Subject: [PATCH 002/125] =?UTF-8?q?Comprobar=20disponibilidad=20de=20URIs?= =?UTF-8?q?=20peri=C3=B3dicamente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/repository/URIRepository.java | 4 +++- .../demo/repository/impl/URIRepositoryImpl.java | 8 ++++++++ .../demo/schedule/checkSchedule.java | 16 +++++++++------- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index 8304d201..b0920cfd 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -2,6 +2,8 @@ import urlshortener.demo.domain.URIItem; -public interface URIRepository extends IRepository { +import java.util.List; +public interface URIRepository extends IRepository { + List comprobar(); } diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index e41444e4..7d4683bc 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -5,6 +5,14 @@ import urlshortener.demo.repository.AbstractRepository; import urlshortener.demo.repository.URIRepository; +import java.util.ArrayList; +import java.util.List; + @Repository public class URIRepositoryImpl extends AbstractRepository implements URIRepository { + + @Override + public List comprobar() { + return new ArrayList<>(); + } } diff --git a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java index 49e80ac3..47153765 100644 --- a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java +++ b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java @@ -5,6 +5,7 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.CheckAlive; import java.io.IOException; @@ -18,18 +19,19 @@ public class checkSchedule { private static final Logger log = LoggerFactory.getLogger(checkSchedule.class); + private final URIRepository uriService; + + @org.springframework.beans.factory.annotation.Autowired + public checkSchedule(URIRepository uriService) { + this.uriService = uriService; + } + @Scheduled(fixedRate = 5000) public void check() throws IOException { CheckAlive c = new CheckAlive(); //HAY QUE CAMBIAR ESTE FRAGMENTO DE CÓDIGO Y RECUPERAR LA LISTA DE LA BD REAL - List uris = new ArrayList<>(); - URIItem u = new URIItem(); - u.setRedirection("https://google.es"); - uris.add(u); - u = new URIItem(); - u.setRedirection("https://stackoverflow.com"); - uris.add(u); + List uris = uriService.comprobar(); log.info("Comienza el checkeo de las URI..."); for (int i=0; i < uris.size(); i++){ From e525fdf59715455d1d1f599d71c5fe6dc36fb355 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 18:43:47 +0100 Subject: [PATCH 003/125] =?UTF-8?q?Comprobar=20disponibilidad=20de=20URIs?= =?UTF-8?q?=20peri=C3=B3dicamente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/src/main/java/urlshortener/demo/utils/CheckAlive.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java b/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java index c1bddc03..982baede 100644 --- a/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java +++ b/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java @@ -5,11 +5,6 @@ import java.net.URL; public class CheckAlive { - - //@org.springframework.beans.factory.annotation.Autowired - public CheckAlive() { - } - public int makeRequest(String s) throws IOException { URL url = new URL(s); HttpURLConnection con = (HttpURLConnection) url.openConnection(); From b5ab8230ac05bf5b66b36d81867ce849217b3399 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 18:50:55 +0100 Subject: [PATCH 004/125] =?UTF-8?q?Comprobar=20disponibilidad=20de=20URIs?= =?UTF-8?q?=20peri=C3=B3dicamente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java | 1 - 1 file changed, 1 deletion(-) diff --git a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java index 47153765..9bcd0929 100644 --- a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java +++ b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java @@ -9,7 +9,6 @@ import urlshortener.demo.utils.CheckAlive; import java.io.IOException; -import java.util.ArrayList; import java.util.List; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-21T05:15:43.072Z[GMT]") From ae3f8a3cb16c873c6ade66f1a4bcb70a9869023e Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 19:15:54 +0100 Subject: [PATCH 005/125] =?UTF-8?q?Comprobar=20disponibilidad=20de=20URIs?= =?UTF-8?q?=20peri=C3=B3dicamente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/controller/impl/CheckApiController.java | 2 +- .../controller/UriApiControllerIntegrationTest.java | 13 +++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 46fde4e8..22de35d1 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -35,7 +35,7 @@ public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request) public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); - String uri = ""; //Se recupera la URI asociada a al parámetro "id" + String uri = "https://google.es"; //Se recupera la URI asociada a al parámetro "id" CheckAlive c = new CheckAlive(); try { diff --git a/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java index 297e46de..e3f59b67 100644 --- a/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java @@ -32,7 +32,7 @@ public void cleanUp(){ } @Test - public void changeURITest() throws Exception { + public void changeURITest() { URICreate body = new URICreate(); String name = "name_example"; ResponseEntity responseEntity = api.changeURI(body, name); @@ -40,21 +40,22 @@ public void changeURITest() throws Exception { } @Test - public void createURITest() throws Exception { + public void createURITest() { URICreate body = new URICreate(); + body.setUri("https://google.es"); ResponseEntity responseEntity = api.createURI(body); - assertEquals(HttpStatus.TEMPORARY_REDIRECT, responseEntity.getStatusCode()); + assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); } @Test - public void deleteURITest() throws Exception { + public void deleteURITest() { String id = "id_example"; ResponseEntity responseEntity = api.deleteURI(id); assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); } @Test - public void getURITestError() throws Exception { + public void getURITestError() { String id = "id_example"; try { api.getURI(id); @@ -63,7 +64,7 @@ public void getURITestError() throws Exception { } @Test - public void getURITestOK() throws Exception { + public void getURITestOK() { String id = "id_example"; service.add((URIItem) new URIItem().id(id).redirection("http://google.es").hashpass("abc")); try { From 3e13b7aac7d942c5a280096fa585f4fe75b31494 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 19:35:30 +0100 Subject: [PATCH 006/125] =?UTF-8?q?Comprobar=20disponibilidad=20de=20URIs?= =?UTF-8?q?=20peri=C3=B3dicamente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/controller/impl/CheckApiController.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 22de35d1..7295e68c 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -9,6 +9,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import urlshortener.demo.controller.CheckApi; +import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.CheckAlive; import javax.servlet.http.HttpServletRequest; @@ -27,15 +28,20 @@ public class CheckApiController implements CheckApi { private final HttpServletRequest request; + private final URIRepository uriService; + @org.springframework.beans.factory.annotation.Autowired - public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request) { + public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request, URIRepository uriService) { this.objectMapper = objectMapper; this.request = request; + this.uriService = uriService; } public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); - String uri = "https://google.es"; //Se recupera la URI asociada a al parámetro "id" + //String uri = uriService.get(id); //Esta línea deberá descomentarse cuando esté implementada la BD + String uri = "https://google.es"; //Se recupera la URI asociada a al parámetro "id" + CheckAlive c = new CheckAlive(); try { From b5293625c3b07cef7ca08793677293101bfbb55e Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 19:37:10 +0100 Subject: [PATCH 007/125] Comprobar disponibilidad (GET /check/{id}) --- .../urlshortener/demo/controller/impl/CheckApiController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 7295e68c..e157276c 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -40,7 +40,7 @@ public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request, public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); //String uri = uriService.get(id); //Esta línea deberá descomentarse cuando esté implementada la BD - String uri = "https://google.es"; //Se recupera la URI asociada a al parámetro "id" + String uri = "https://google.com"; //Se recupera la URI asociada a al parámetro "id" CheckAlive c = new CheckAlive(); From 3a90aa5ca50bd450eb92753deb159a9d51dc9632 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 19:55:07 +0100 Subject: [PATCH 008/125] Comprobar disponibilidad (GET /check/{id}) --- .../demo/controller/impl/CheckApiController.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index e157276c..34c51040 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -9,6 +9,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import urlshortener.demo.controller.CheckApi; +import urlshortener.demo.domain.URIItem; import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.CheckAlive; @@ -39,13 +40,14 @@ public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request, public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); - //String uri = uriService.get(id); //Esta línea deberá descomentarse cuando esté implementada la BD - String uri = "https://google.com"; //Se recupera la URI asociada a al parámetro "id" + //URIItem uri = uriService.get(id); //Esta línea deberá descomentarse cuando esté implementada la BD + URIItem uri = new URIItem(); //Se recupera la URI asociada a al parámetro "id" + uri.setRedirection("https://google.com"); CheckAlive c = new CheckAlive(); try { - HttpStatus httpStatus = HttpStatus.valueOf(c.makeRequest(uri)); + HttpStatus httpStatus = HttpStatus.valueOf(c.makeRequest(uri.getRedirection())); return new ResponseEntity(httpStatus); From 7eda46ca570a8a215edb0ca8ac7acb0dd89813e5 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Tue, 4 Dec 2018 19:58:05 +0100 Subject: [PATCH 009/125] Comprobar disponibilidad (GET /check/{id}) --- .../demo/controller/impl/CheckApiController.java | 4 +--- .../java/urlshortener/demo/repository/URIRepository.java | 2 ++ .../demo/repository/impl/URIRepositoryImpl.java | 7 +++++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 34c51040..8d132018 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -40,9 +40,7 @@ public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request, public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); - //URIItem uri = uriService.get(id); //Esta línea deberá descomentarse cuando esté implementada la BD - URIItem uri = new URIItem(); //Se recupera la URI asociada a al parámetro "id" - uri.setRedirection("https://google.com"); + URIItem uri = uriService.obtenerUri(id); //Esta línea deberá descomentarse cuando esté implementada la BD CheckAlive c = new CheckAlive(); diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index b0920cfd..e70f6bc0 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -6,4 +6,6 @@ public interface URIRepository extends IRepository { List comprobar(); + + URIItem obtenerUri(String id); } diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index 7d4683bc..f438e7c8 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -15,4 +15,11 @@ public class URIRepositoryImpl extends AbstractRepository imple public List comprobar() { return new ArrayList<>(); } + + @Override + public URIItem obtenerUri(String id) { + URIItem uri = new URIItem(); //Se recupera la URI asociada a al parámetro "id" + uri.setRedirection("https://google.com"); + return uri; + } } From 966680ad2841f618a4736ac7d0b410398dc69d52 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Wed, 5 Dec 2018 17:35:28 +0100 Subject: [PATCH 010/125] Change function names language --- .../demo/controller/impl/CheckApiController.java | 2 +- .../demo/controller/impl/UriApiController.java | 2 ++ .../urlshortener/demo/repository/URIRepository.java | 6 ++++-- .../demo/repository/impl/URIRepositoryImpl.java | 11 +++++++++-- .../urlshortener/demo/schedule/checkSchedule.java | 2 +- 5 files changed, 17 insertions(+), 6 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 8d132018..3354668c 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -40,7 +40,7 @@ public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request, public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); - URIItem uri = uriService.obtenerUri(id); //Esta línea deberá descomentarse cuando esté implementada la BD + URIItem uri = uriService.obtainURI(id); //Esta línea deberá descomentarse cuando esté implementada la BD CheckAlive c = new CheckAlive(); diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 8ffdab66..e819258e 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -72,6 +72,8 @@ public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true //Completar método, rellenar el objeto de tipo URIItem "uri" + uriService.saveURI(uri); + return new ResponseEntity(uri, HttpStatus.CREATED); } else { diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index e70f6bc0..5e53b76f 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -5,7 +5,9 @@ import java.util.List; public interface URIRepository extends IRepository { - List comprobar(); + List checkURI(); - URIItem obtenerUri(String id); + URIItem obtainURI(String id); + + void saveURI(URIItem uri); } diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index f438e7c8..5cb8976a 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -12,14 +12,21 @@ public class URIRepositoryImpl extends AbstractRepository implements URIRepository { @Override - public List comprobar() { + public List checkURI() { return new ArrayList<>(); } @Override - public URIItem obtenerUri(String id) { + public URIItem obtainURI(String id) { URIItem uri = new URIItem(); //Se recupera la URI asociada a al parámetro "id" uri.setRedirection("https://google.com"); return uri; } + + @Override + public void saveURI(URIItem uri) { + + } + + } diff --git a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java index 9bcd0929..59898bd8 100644 --- a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java +++ b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java @@ -30,7 +30,7 @@ public void check() throws IOException { CheckAlive c = new CheckAlive(); //HAY QUE CAMBIAR ESTE FRAGMENTO DE CÓDIGO Y RECUPERAR LA LISTA DE LA BD REAL - List uris = uriService.comprobar(); + List uris = uriService.checkURI(); log.info("Comienza el checkeo de las URI..."); for (int i=0; i < uris.size(); i++){ From 16eac70d5b1951ed28d277d3f73b7ca6c8848926 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Wed, 5 Dec 2018 17:55:07 +0100 Subject: [PATCH 011/125] Added comment to saveURI function --- .../urlshortener/demo/repository/impl/URIRepositoryImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index 5cb8976a..18913b75 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -25,7 +25,7 @@ public URIItem obtainURI(String id) { @Override public void saveURI(URIItem uri) { - + //This function will save the "uri" object in the DB } From 4250d32a7f22a4c43606425931f7372dd1b6f4d0 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 18:58:10 +0100 Subject: [PATCH 012/125] Update sonar --- build.gradle | 2 +- sonar-project.properties | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 60d1f46d..015dcc7c 100644 --- a/build.gradle +++ b/build.gradle @@ -13,12 +13,12 @@ buildscript { plugins { id "org.sonarqube" version "2.6.2" - id 'jacoco' } allprojects { apply plugin: 'idea' apply plugin: 'eclipse' + apply plugin: 'jacoco' } // Instructions for each sub project diff --git a/sonar-project.properties b/sonar-project.properties index a5af0e47..f96f440a 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -16,7 +16,8 @@ sonar.links.issue=https://github.com/Blue-Bash/UrlShortener/issues # ===================================================== # SQ standard properties -sonar.java.binaries=. +sonar.java.binaries=demo/out/production/classes +sonar.test.binaries=demo/out/test/classes sonar.sources=demo/src/main/java sonar.tests=demo/src/test sonar.exclusions=demo/src/main/resources/static/vendor/**/* From 4fbfefe786f02004f8f33a9ee6d743dae78e2922 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 19:05:41 +0100 Subject: [PATCH 013/125] Update sonar (II) --- sonar-project.properties | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sonar-project.properties b/sonar-project.properties index f96f440a..552e472b 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -16,8 +16,10 @@ sonar.links.issue=https://github.com/Blue-Bash/UrlShortener/issues # ===================================================== # SQ standard properties -sonar.java.binaries=demo/out/production/classes -sonar.test.binaries=demo/out/test/classes +sonar.java.binaries=demo/build/classes/java/main +sonar.test.binaries=demo/build/classes/java/test sonar.sources=demo/src/main/java +sonar.java.sources=demo/src/main/java sonar.tests=demo/src/test +sonar.java.tests=demo/src/test sonar.exclusions=demo/src/main/resources/static/vendor/**/* From 68d7936f80c9f9ee29ad112291586cd86dce7a29 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 19:12:25 +0100 Subject: [PATCH 014/125] Update sonar (III) --- build.gradle | 7 +++++++ sonar-project.properties | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 015dcc7c..380a33a4 100644 --- a/build.gradle +++ b/build.gradle @@ -15,6 +15,13 @@ plugins { id "org.sonarqube" version "2.6.2" } +sonarqube { + properties { + property 'sonar.host.url', 'https://sonarcloud.io' + property 'sonar.organization', 'blue-bash' + } +} + allprojects { apply plugin: 'idea' apply plugin: 'eclipse' diff --git a/sonar-project.properties b/sonar-project.properties index 552e472b..e16ead5c 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -20,6 +20,6 @@ sonar.java.binaries=demo/build/classes/java/main sonar.test.binaries=demo/build/classes/java/test sonar.sources=demo/src/main/java sonar.java.sources=demo/src/main/java -sonar.tests=demo/src/test -sonar.java.tests=demo/src/test +sonar.tests=demo/src/test/java +sonar.java.tests=demo/src/test/java sonar.exclusions=demo/src/main/resources/static/vendor/**/* From 0335696d1a32ca1ac1790f69a62f22bd22d476ef Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 19:25:13 +0100 Subject: [PATCH 015/125] Add URIUpdate test --- .../demo/domain/URIUpdateTests.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java diff --git a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java new file mode 100644 index 00000000..45419a7d --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java @@ -0,0 +1,22 @@ +package urlshortener.demo.domain; + + +import org.junit.Test; + +import java.net.URI; + +import static org.junit.Assert.assertEquals; + +public class URIUpdateTests { + + @Test + public void testOK(){ + URIUpdate uriUpdate1 = new URIUpdate(); + URIUpdate uriUpdate2 = uriUpdate1.newName("abc"); + URIUpdate uriUpdate3 = (URIUpdate) uriUpdate2.hashpass("abcd"); + + assertEquals(uriUpdate3, uriUpdate1); + assertEquals(uriUpdate3, uriUpdate2); + } + +} From f47a8bf99db5c3be1ce0c00032fd89f7ba65462a Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Wed, 5 Dec 2018 19:29:09 +0100 Subject: [PATCH 016/125] Created mock test about createURI method --- .../controller/impl/UriApiController.java | 6 ++--- .../java/urlshortener/demo/web/UriTests.java | 25 +++++++++++++++++-- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index e819258e..0c2054b3 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -59,9 +59,9 @@ public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true URL url = null; HttpStatus httpStatus = HttpStatus.I_AM_A_TEAPOT; URIItem uri = new URIItem(); - uri.setId(""); - uri.setRedirection(""); - uri.setHashpass(""); + uri.setId("1234"); + uri.setRedirection(body.getUri()); + uri.setHashpass("1234"); try { if (c.makeRequest(body.getUri()) == 200) { diff --git a/demo/src/test/java/urlshortener/demo/web/UriTests.java b/demo/src/test/java/urlshortener/demo/web/UriTests.java index ecf3d742..a95438ea 100644 --- a/demo/src/test/java/urlshortener/demo/web/UriTests.java +++ b/demo/src/test/java/urlshortener/demo/web/UriTests.java @@ -6,21 +6,26 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import urlshortener.demo.controller.advice.BaseServiceAdvice; import urlshortener.demo.controller.impl.UriApiController; +import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; import urlshortener.demo.repository.URIRepository; import javax.servlet.http.HttpServletRequest; import static org.mockito.Mockito.when; +import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static urlshortener.demo.web.fixture.UriItemFixture.someURI; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; public class UriTests { private MockMvc mockMvc; @@ -60,4 +65,20 @@ public void getUriError() throws Exception { mockMvc.perform(get("/uri/{id}", "1")).andDo(print()) .andExpect(status().isNotFound()); } + + @Test + public void createUriWorks() throws Exception { + URICreate uri = new URICreate(); + uri.setUri("https://google.es"); + + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(uri); + + mockMvc.perform(put("/uri").contentType(MediaType.APPLICATION_JSON_UTF8).content(json)).andDo(print()) + .andExpect(status().isCreated()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(jsonPath("$.id", is("1234"))) + .andExpect(jsonPath("$.redirection", is("https://google.es"))) + .andExpect(jsonPath("$.hashpass", is("1234"))); + } } From 80e41442345dbd810b81fdfa395c0a46f2ce666e Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 19:36:43 +0100 Subject: [PATCH 017/125] Update name --- .../demo/domain/{URIUpdateTests.java => URIUpdateTest.java} | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) rename demo/src/test/java/urlshortener/demo/domain/{URIUpdateTests.java => URIUpdateTest.java} (89%) diff --git a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTest.java similarity index 89% rename from demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java rename to demo/src/test/java/urlshortener/demo/domain/URIUpdateTest.java index 45419a7d..5bb7d8df 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java +++ b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTest.java @@ -3,11 +3,9 @@ import org.junit.Test; -import java.net.URI; - import static org.junit.Assert.assertEquals; -public class URIUpdateTests { +public class URIUpdateTest { @Test public void testOK(){ From adef40b79923dfabb69d8978bd3e082d8b7404a4 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 19:41:16 +0100 Subject: [PATCH 018/125] Add jacoco properties --- sonar-project.properties | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sonar-project.properties b/sonar-project.properties index e16ead5c..04f0d6d3 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -23,3 +23,6 @@ sonar.java.sources=demo/src/main/java sonar.tests=demo/src/test/java sonar.java.tests=demo/src/test/java sonar.exclusions=demo/src/main/resources/static/vendor/**/* + +sonar.java.coveragePlugin=jacoco +sonar.jacoco.reportPath=build/test-reports/jacoco.exec From 9a3162f2e38a7413b9c799df9f5780191ed60f56 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 19:45:49 +0100 Subject: [PATCH 019/125] Add jacoco properties (II) --- sonar-project.properties | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sonar-project.properties b/sonar-project.properties index 04f0d6d3..16d6f85e 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -25,4 +25,5 @@ sonar.java.tests=demo/src/test/java sonar.exclusions=demo/src/main/resources/static/vendor/**/* sonar.java.coveragePlugin=jacoco -sonar.jacoco.reportPath=build/test-reports/jacoco.exec +sonar.jacoco.reportPath=demo/build/test-reports/jacoco.exec +sonar.jacoco.reportPaths=demo/build/test-reports/jacoco.exec From 03e824dc9e3464629d386025355f5004f951a6ce Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 20:00:31 +0100 Subject: [PATCH 020/125] Fetch unshallow --- .travis.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 602fb55f..8799a1d3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,5 +9,7 @@ addons: script: - bash sonar.sh before_install: -- openssl aes-256-cbc -K $encrypted_be44edb6a80d_key -iv $encrypted_be44edb6a80d_iv - -in app.properties.enc -out app.properties -d + # Our tests inspect some of *our* git history + - git fetch --unshallow + - openssl aes-256-cbc -K $encrypted_be44edb6a80d_key -iv $encrypted_be44edb6a80d_iv + -in app.properties.enc -out app.properties -d From 38ec99b2da1fb520a9d7da18b73021e3d5691630 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 20:07:32 +0100 Subject: [PATCH 021/125] Add java libraries --- sonar-project.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/sonar-project.properties b/sonar-project.properties index 16d6f85e..5362e55f 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -16,6 +16,7 @@ sonar.links.issue=https://github.com/Blue-Bash/UrlShortener/issues # ===================================================== # SQ standard properties +sonar.java.libraries=demo/**/*.jar sonar.java.binaries=demo/build/classes/java/main sonar.test.binaries=demo/build/classes/java/test sonar.sources=demo/src/main/java From 0b49a6439d232597aac267c402cf5ec0ed819945 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 20:11:31 +0100 Subject: [PATCH 022/125] Add test libraries --- sonar-project.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/sonar-project.properties b/sonar-project.properties index 5362e55f..b596b10e 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -17,6 +17,7 @@ sonar.links.issue=https://github.com/Blue-Bash/UrlShortener/issues # SQ standard properties sonar.java.libraries=demo/**/*.jar +sonar.java.test.libraries=demo/**/*.jar sonar.java.binaries=demo/build/classes/java/main sonar.test.binaries=demo/build/classes/java/test sonar.sources=demo/src/main/java From 6cba4e7a8037bddbccc3ed26321615492437d2dd Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Wed, 5 Dec 2018 20:12:50 +0100 Subject: [PATCH 023/125] Created getURI minimum functionality for integration test --- .../urlshortener/demo/controller/UriApi.java | 8 +--- .../controller/impl/UriApiController.java | 37 ++++++++++++++++--- .../demo/repository/URIRepository.java | 3 ++ .../repository/impl/URIRepositoryImpl.java | 6 +++ .../UriApiControllerIntegrationTest.java | 3 +- 5 files changed, 45 insertions(+), 12 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/UriApi.java b/demo/src/main/java/urlshortener/demo/controller/UriApi.java index 91b0de13..20cb161c 100644 --- a/demo/src/main/java/urlshortener/demo/controller/UriApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/UriApi.java @@ -1,8 +1,3 @@ -/** - * NOTE: This class is auto generated by the swagger code generator program (3.0.2). - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ package urlshortener.demo.controller; import io.swagger.annotations.*; @@ -13,6 +8,7 @@ import org.springframework.web.bind.annotation.RequestMethod; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.domain.URIUpdate; import javax.validation.Valid; @@ -29,7 +25,7 @@ public interface UriApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PUT) - ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URICreate body,@ApiParam(value = "",required=true) @PathVariable("name") String name); + ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URIUpdate body, @ApiParam(value = "",required=true) @PathVariable("name") String name); @ApiOperation(value = "Creates a new redirection", nickname = "createURI", notes = "Create a new URI redirection ", response = URIItem.class, tags={ "F0 - The app will short, storage and get URI's", }) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 0c2054b3..65ad24b9 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -11,9 +11,9 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import urlshortener.demo.controller.UriApi; -import urlshortener.demo.domain.ErrorItem; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.domain.URIUpdate; import urlshortener.demo.utils.CheckAlive; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; @@ -43,13 +43,40 @@ public UriApiController(ObjectMapper objectMapper, HttpServletRequest request, U this.uriService = uriService; } - public ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URICreate body,@ApiParam(value = "",required=true) @PathVariable("name") String name) { + public ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URIUpdate body, @ApiParam(value = "",required=true) @PathVariable("name") String name) { String accept = request.getHeader("Accept"); + CheckAlive c = new CheckAlive(); + + URL url = null; + HttpStatus httpStatus = HttpStatus.I_AM_A_TEAPOT; + + String redirection = "https://null.es"; //Se recupera de la BD la URI que corresponde al hashpass recibido + + URIItem resultado = new URIItem(); + resultado.setRedirection(redirection); + resultado.setHashpass(body.getHashpass()); + resultado.setId(body.getNewName()); + + try { + if (c.makeRequest(redirection) == 200) { + //Completar método, rellenar el objeto de tipo URIItem "uri" + + uriService.updateURI(body); - ErrorItem error = new ErrorItem(); - error.setErrorInfo("This is a test error"); + return new ResponseEntity(resultado, HttpStatus.CREATED); + } + else { + return new ResponseEntity(resultado, HttpStatus.BAD_REQUEST); + } + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (ProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } - return new ResponseEntity(HttpStatus.BAD_REQUEST); + return new ResponseEntity(resultado, HttpStatus.BAD_REQUEST); } public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body) { diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index 5e53b76f..d7c067b9 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -1,6 +1,7 @@ package urlshortener.demo.repository; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.domain.URIUpdate; import java.util.List; @@ -10,4 +11,6 @@ public interface URIRepository extends IRepository { URIItem obtainURI(String id); void saveURI(URIItem uri); + + void updateURI(URIUpdate uri); } diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index 18913b75..38689562 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -2,6 +2,7 @@ import org.springframework.stereotype.Repository; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.domain.URIUpdate; import urlshortener.demo.repository.AbstractRepository; import urlshortener.demo.repository.URIRepository; @@ -28,5 +29,10 @@ public void saveURI(URIItem uri) { //This function will save the "uri" object in the DB } + @Override + public void updateURI(URIUpdate uri) { + //This function will update the "hashpass" uri name + } + } diff --git a/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java index e3f59b67..077c5b00 100644 --- a/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java @@ -10,6 +10,7 @@ import org.springframework.test.context.junit4.SpringRunner; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.domain.URIUpdate; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; @@ -33,7 +34,7 @@ public void cleanUp(){ @Test public void changeURITest() { - URICreate body = new URICreate(); + URIUpdate body = new URIUpdate(); String name = "name_example"; ResponseEntity responseEntity = api.changeURI(body, name); assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); From c3cda5ddfe279ce770783d1a71dbc1b656fb9020 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 20:28:56 +0100 Subject: [PATCH 024/125] Update libraries --- sonar-project.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sonar-project.properties b/sonar-project.properties index b596b10e..44028852 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -16,8 +16,8 @@ sonar.links.issue=https://github.com/Blue-Bash/UrlShortener/issues # ===================================================== # SQ standard properties -sonar.java.libraries=demo/**/*.jar -sonar.java.test.libraries=demo/**/*.jar +sonar.java.libraries=./**/*.jar +sonar.java.test.libraries=./**/*.jar sonar.java.binaries=demo/build/classes/java/main sonar.test.binaries=demo/build/classes/java/test sonar.sources=demo/src/main/java From ac8720a070b1974351d373432257f3f175d02617 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Wed, 5 Dec 2018 20:31:27 +0100 Subject: [PATCH 025/125] Created getURI minimum functionality for mock test --- .../test/java/urlshortener/demo/web/UriTests.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/web/UriTests.java b/demo/src/test/java/urlshortener/demo/web/UriTests.java index a95438ea..5f4de5ad 100644 --- a/demo/src/test/java/urlshortener/demo/web/UriTests.java +++ b/demo/src/test/java/urlshortener/demo/web/UriTests.java @@ -13,6 +13,7 @@ import urlshortener.demo.controller.impl.UriApiController; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.domain.URIUpdate; import urlshortener.demo.repository.URIRepository; import javax.servlet.http.HttpServletRequest; @@ -81,4 +82,17 @@ public void createUriWorks() throws Exception { .andExpect(jsonPath("$.redirection", is("https://google.es"))) .andExpect(jsonPath("$.hashpass", is("1234"))); } + + @Test + public void changeUriWorks() throws Exception { + URIUpdate uri = new URIUpdate(); + uri.setNewName("name_example"); + uri.setHashpass("1234"); + + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(uri); + + mockMvc.perform(put("/uri/{name}", "patata").contentType(MediaType.APPLICATION_JSON_UTF8).content(json)).andDo(print()) + .andExpect(status().isBadRequest()); + } } From 9b9cb20f70a4d35cbbcf74f37c72c8fd8285209e Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 20:35:52 +0100 Subject: [PATCH 026/125] Update test name --- .../demo/domain/{URIUpdateTest.java => URIUpdateTests.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename demo/src/test/java/urlshortener/demo/domain/{URIUpdateTest.java => URIUpdateTests.java} (93%) diff --git a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTest.java b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java similarity index 93% rename from demo/src/test/java/urlshortener/demo/domain/URIUpdateTest.java rename to demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java index 5bb7d8df..b673ded5 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTest.java +++ b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java @@ -5,7 +5,7 @@ import static org.junit.Assert.assertEquals; -public class URIUpdateTest { +public class URIUpdateTests { @Test public void testOK(){ From b62d6cb761818942e91952850fba8d482e08118c Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 20:46:53 +0100 Subject: [PATCH 027/125] Remove exceptions --- .../urlshortener/demo/repository/AbstractRepository.java | 6 +++--- .../main/java/urlshortener/demo/repository/IRepository.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java b/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java index 4235771a..e86f95bb 100644 --- a/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java @@ -13,7 +13,7 @@ public class AbstractRepository> implements IReposito private Map uris = new HashMap<>(); @Override - public void add(V uri) throws CannotAddEntityException { + public void add(V uri) { if(uris.containsKey(uri.getId())){ throw new CannotAddEntityException(HttpStatus.BAD_REQUEST.value(), "Cannot add uri with hash " + uri.getId()); } @@ -22,7 +22,7 @@ public void add(V uri) throws CannotAddEntityException { } @Override - public V get(K hash) throws UnknownEntityException { + public V get(K hash) { V item = uris.get(hash); if(item == null){ throw new UnknownEntityException(HttpStatus.NOT_FOUND.value(), "Cannot fetch uri with hash " + hash); @@ -31,7 +31,7 @@ public V get(K hash) throws UnknownEntityException { } @Override - public void remove(K hash) throws UnknownEntityException { + public void remove(K hash) { if(!uris.containsKey(hash)){ throw new UnknownEntityException(HttpStatus.NOT_FOUND.value(), "Cannot fetch uri with hash " + hash); } diff --git a/demo/src/main/java/urlshortener/demo/repository/IRepository.java b/demo/src/main/java/urlshortener/demo/repository/IRepository.java index 15b0ff75..083d674a 100644 --- a/demo/src/main/java/urlshortener/demo/repository/IRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/IRepository.java @@ -6,11 +6,11 @@ public interface IRepository> { - void add(V value) throws CannotAddEntityException; + void add(V value); - V get(K key) throws UnknownEntityException; + V get(K key); - void remove(K key) throws UnknownEntityException; + void remove(K key); void removeAll(); } From 1f1c07e48941fae6cadc02869d95dbbb88001d39 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 20:51:53 +0100 Subject: [PATCH 028/125] Removed unused imports --- .../src/main/java/urlshortener/demo/repository/IRepository.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/IRepository.java b/demo/src/main/java/urlshortener/demo/repository/IRepository.java index 083d674a..6018e840 100644 --- a/demo/src/main/java/urlshortener/demo/repository/IRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/IRepository.java @@ -1,8 +1,6 @@ package urlshortener.demo.repository; import urlshortener.demo.domain.BaseEntity; -import urlshortener.demo.exception.CannotAddEntityException; -import urlshortener.demo.exception.UnknownEntityException; public interface IRepository> { From 3b0fa2021bb287a59b04b3989acb77dbbaacb46f Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 5 Dec 2018 21:04:22 +0100 Subject: [PATCH 029/125] Update sonar tests --- sonar-project.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sonar-project.properties b/sonar-project.properties index 44028852..f01676c5 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -22,8 +22,8 @@ sonar.java.binaries=demo/build/classes/java/main sonar.test.binaries=demo/build/classes/java/test sonar.sources=demo/src/main/java sonar.java.sources=demo/src/main/java -sonar.tests=demo/src/test/java -sonar.java.tests=demo/src/test/java +sonar.tests=demo/src/test/**/* +sonar.java.tests=demo/src/test/**/* sonar.exclusions=demo/src/main/resources/static/vendor/**/* sonar.java.coveragePlugin=jacoco From b6fe4e9acecb97f93b27e8305b08775fc3bf3555 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Sun, 9 Dec 2018 18:40:23 +0100 Subject: [PATCH 030/125] Modified checkURI integration tests --- .../demo/controller/CheckApi.java | 8 +---- .../urlshortener/demo/controller/UriApi.java | 7 ++-- .../controller/impl/CheckApiController.java | 4 +-- .../controller/impl/UriApiController.java | 2 +- .../demo/schedule/checkSchedule.java | 2 +- .../CheckApiControllerIntegrationTest.java | 34 +++++++++++++++++-- .../java/urlshortener/demo/web/UriTests.java | 2 -- 7 files changed, 39 insertions(+), 20 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/CheckApi.java b/demo/src/main/java/urlshortener/demo/controller/CheckApi.java index 72fb4d83..0f1ad235 100644 --- a/demo/src/main/java/urlshortener/demo/controller/CheckApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/CheckApi.java @@ -1,8 +1,3 @@ -/** - * NOTE: This class is auto generated by the swagger code generator program (3.0.2). - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ package urlshortener.demo.controller; import io.swagger.annotations.*; @@ -19,8 +14,7 @@ public interface CheckApi { @ApiOperation(value = "Checks the state of the original URI", nickname = "checkURI", notes = "Checks the state of the original URI", tags={ "F5", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "The original URI is alive"), - @ApiResponse(code = 404, message = "The original URI is dead or the shortened URI doesn't exist"), - @ApiResponse(code = 418, message = "I'm a teapot") + @ApiResponse(code = 404, message = "The original URI is dead or the shortened URI doesn't exist") }) @RequestMapping(value = "/check/{id}", method = RequestMethod.GET) diff --git a/demo/src/main/java/urlshortener/demo/controller/UriApi.java b/demo/src/main/java/urlshortener/demo/controller/UriApi.java index 20cb161c..70ee0b20 100644 --- a/demo/src/main/java/urlshortener/demo/controller/UriApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/UriApi.java @@ -31,8 +31,8 @@ public interface UriApi { @ApiOperation(value = "Creates a new redirection", nickname = "createURI", notes = "Create a new URI redirection ", response = URIItem.class, tags={ "F0 - The app will short, storage and get URI's", }) @ApiResponses(value = { @ApiResponse(code = 201, message = "The URI redirection has been successfully created", response = URIItem.class), - @ApiResponse(code = 400, message = "The URI was not reachable", response = URIItem.class), - @ApiResponse(code = 418, message = "I'm a teapot", response = URIItem.class)}) + @ApiResponse(code = 400, message = "The URI was not reachable", response = URIItem.class) + }) @RequestMapping(value = "/uri", produces = { "application/json" }, consumes = { "application/json" }, @@ -52,8 +52,7 @@ public interface UriApi { @ApiOperation(value = "Returns the data of a redirection", nickname = "getURI", notes = "Get a URI redirection ", tags={ "F0 - The app will short, storage and get URI's", }) @ApiResponses(value = { @ApiResponse(code = 307, message = "Redirect to the real URI"), - @ApiResponse(code = 404, message = "The given URI couldn't be found"), - @ApiResponse(code = 418, message = "I'm a teapot") + @ApiResponse(code = 404, message = "The given URI couldn't be found") }) @RequestMapping(value = "/uri/{id}", method = RequestMethod.GET) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 3354668c..7352acac 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -40,7 +40,7 @@ public CheckApiController(ObjectMapper objectMapper, HttpServletRequest request, public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); - URIItem uri = uriService.obtainURI(id); //Esta línea deberá descomentarse cuando esté implementada la BD + URIItem uri = uriService.get(id); CheckAlive c = new CheckAlive(); @@ -57,6 +57,6 @@ public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVa e.printStackTrace(); } - return new ResponseEntity(HttpStatus.I_AM_A_TEAPOT); + return new ResponseEntity(HttpStatus.BAD_REQUEST); } } diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 65ad24b9..edc18a79 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -84,7 +84,7 @@ public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true CheckAlive c = new CheckAlive(); URL url = null; - HttpStatus httpStatus = HttpStatus.I_AM_A_TEAPOT; + HttpStatus httpStatus = HttpStatus.BAD_REQUEST; URIItem uri = new URIItem(); uri.setId("1234"); uri.setRedirection(body.getUri()); diff --git a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java index 59898bd8..bd6ddf18 100644 --- a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java +++ b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java @@ -25,7 +25,7 @@ public checkSchedule(URIRepository uriService) { this.uriService = uriService; } - @Scheduled(fixedRate = 5000) + @Scheduled(fixedRate = 86400) public void check() throws IOException { CheckAlive c = new CheckAlive(); diff --git a/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java index b7e7eaec..b0175784 100644 --- a/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java @@ -1,6 +1,7 @@ package urlshortener.demo.controller; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -8,6 +9,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; +import urlshortener.demo.domain.URIItem; +import urlshortener.demo.repository.URIRepository; import static org.junit.Assert.assertEquals; @@ -19,11 +22,36 @@ public class CheckApiControllerIntegrationTest { @Autowired private CheckApi api; + @Autowired + private URIRepository repo; + + @Test(expected = urlshortener.demo.exception.UnknownEntityException.class) + public void checkURITest_not_existing_URI() { + ResponseEntity responseEntity = api.checkURI("id_example"); + } + @Test - public void checkURITest() throws Exception { - String id = "id_example"; - ResponseEntity responseEntity = api.checkURI(id); + public void checkURITest_not_null_existing_URI(){ + URIItem uri = new URIItem(); + uri.setId("1"); + uri.setHashpass("1"); + uri.setRedirection("https://www.google.es"); + repo.add(uri); + + URIItem newUri = repo.get("1"); + + assertEquals(uri.getRedirection(), newUri.getRedirection()); + ResponseEntity responseEntity = api.checkURI("1"); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); } + @Test(expected = urlshortener.demo.exception.UnknownEntityException.class) + public void checkURITest_null_URI_throws_UnknownEntityException() { + ResponseEntity responseEntity = api.checkURI(null); + } + + @Test(expected = urlshortener.demo.exception.UnknownEntityException.class) + public void checkURITest_empty_URI_throws_UnknownEntityException() { + ResponseEntity responseEntity = api.checkURI(""); + } } diff --git a/demo/src/test/java/urlshortener/demo/web/UriTests.java b/demo/src/test/java/urlshortener/demo/web/UriTests.java index 5f4de5ad..ed76151c 100644 --- a/demo/src/test/java/urlshortener/demo/web/UriTests.java +++ b/demo/src/test/java/urlshortener/demo/web/UriTests.java @@ -25,8 +25,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static urlshortener.demo.web.fixture.UriItemFixture.someURI; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; public class UriTests { private MockMvc mockMvc; From c3744676260781996ab5d8a3980f0f502535cb1a Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:35:29 +0100 Subject: [PATCH 031/125] Add redirection interface --- .../main/java/urlshortener/demo/repository/URIRepository.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index 8304d201..51d12f39 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -4,4 +4,6 @@ public interface URIRepository extends IRepository { + long getRedirectionAmount(String hash, long timeFromNow); + } From 062aa4c7c7e762380d7c624f9e1fcd9743cfb4d4 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:35:38 +0100 Subject: [PATCH 032/125] Add redirection tests --- .../demo/repository/URIRepositoryTest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java b/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java index f1897fa0..b2dcd6a9 100644 --- a/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java +++ b/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java @@ -7,6 +7,8 @@ import org.springframework.test.context.junit4.SpringRunner; import urlshortener.demo.domain.URIItem; +import static org.junit.Assert.assertEquals; + @RunWith(SpringRunner.class) @SpringBootTest @@ -52,4 +54,14 @@ public void testContains(){ super.testContains(repository, item1.getId()); super.testNotContains(repository, "randomID :D"); } + + @Test + public void testRedirectionAmount(){ + repository.add(item1); + assertEquals(0, repository.getRedirectionAmount(item1.getId(), System.currentTimeMillis())); + + repository.get(item1.getId()); + assertEquals(1, repository.getRedirectionAmount(item1.getId(), System.currentTimeMillis())); + assertEquals(0, repository.getRedirectionAmount(item1.getId(), -1000)); + } } From f0d20bdd819d68ff30bd3d18a12126518f6b4888 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:35:48 +0100 Subject: [PATCH 033/125] Add redirection implementation --- .../repository/impl/URIRepositoryImpl.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index e41444e4..8e4bebd6 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -1,10 +1,54 @@ package urlshortener.demo.repository.impl; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Repository; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.exception.CannotAddEntityException; +import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.AbstractRepository; import urlshortener.demo.repository.URIRepository; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Repository public class URIRepositoryImpl extends AbstractRepository implements URIRepository { + + private Map stats = new HashMap<>(); + + @Override + public long getRedirectionAmount(String hash, long timeFromNow) { + URIStats stats = this.stats.get(hash); + if(stats == null) throw new UnknownEntityException(HttpStatus.BAD_REQUEST.value(), "Unknown URI " + hash); + + return stats.getAccesssesAfter(System.currentTimeMillis() - timeFromNow); + } + + @Override + public void add(URIItem uri) throws CannotAddEntityException { + stats.putIfAbsent(uri.getId(), new URIStats()); + super.add(uri); + } + + @Override + public URIItem get(String hash) throws UnknownEntityException { + stats.putIfAbsent(hash, new URIStats()); + stats.get(hash).addAccess(); + + return super.get(hash); + } + + private static class URIStats{ + private List lastAccesses = new ArrayList<>(); + + private void addAccess(){ + this.lastAccesses.add(System.currentTimeMillis()); + } + + private long getAccesssesAfter(long time){ + return lastAccesses.stream().filter(t -> t > time).count(); + } + } } From 814d9e585d10d9556d0a29b93d0d707a1d36bcf6 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:44:02 +0100 Subject: [PATCH 034/125] Limit to 100 redirections unit test --- .../controller/UriApiControllerIntegrationTest.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java index 02c9b812..4e146ce0 100644 --- a/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java @@ -206,4 +206,17 @@ public void getURITestOK() { assertEquals(HttpStatus.TEMPORARY_REDIRECT, responseEntity.getStatusCode()); } + @Test + public void getURITestTooManyRequests() { + final long MAX_REDIRECTIONS = 100; + String id = "id_example"; + repository.add((URIItem) new URIItem().id(id).redirection("http://google.es").hashpass("abc")); + for(int i = 0; i < MAX_REDIRECTIONS; i++){ + repository.get(id); + } + + ResponseEntity responseEntity = api.getURI(id); + assertEquals(HttpStatus.TOO_MANY_REQUESTS, responseEntity.getStatusCode()); + } + } From e2d88e480d407ac8a5934602c045af261fd6a793 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:48:13 +0100 Subject: [PATCH 035/125] Limit to 100 redirections mock test --- demo/src/test/java/urlshortener/demo/web/UriTests.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/web/UriTests.java b/demo/src/test/java/urlshortener/demo/web/UriTests.java index 2d2d1a75..5bdc89b8 100644 --- a/demo/src/test/java/urlshortener/demo/web/UriTests.java +++ b/demo/src/test/java/urlshortener/demo/web/UriTests.java @@ -224,5 +224,14 @@ public void getUriError() throws Exception { .andExpect(status().isNotFound()); } + @Test + public void getUriTooManyRequests() throws Exception { + URIItem item = someURI(); + when(service.get("abc")).thenReturn(someURI()); + when(service.getRedirectionAmount(eq("abc"), isA(Long.class))).thenReturn(101L); + + mockMvc.perform(get("/uri/{id}", item.getId())).andDo(print()) + .andExpect(status().isTooManyRequests()); + } } From aa055b21fbf511b6426fbf2decd91d7172b6135a Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:48:26 +0100 Subject: [PATCH 036/125] Add limit to 100 redirections feature --- .../demo/controller/impl/UriApiController.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index da2e2aef..fc7f7ee8 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -30,6 +30,12 @@ @Controller public class UriApiController implements UriApi { + //Limit to K redirections in one hour + private static final long MAX_REDIRECTION_TIME = 3600000L; + + //Limit to 100 redirections in X ms. + private static final long MAX_REDIRECTIONS = 100; + private static final Logger log = LoggerFactory.getLogger(UriApiController.class); private final ObjectMapper objectMapper; @@ -82,6 +88,11 @@ public ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVari if(item == null){ throw new UnknownEntityException(1, "Unknown URI: " + id); } + + if(uriService.getRedirectionAmount(id, MAX_REDIRECTION_TIME) > MAX_REDIRECTIONS){ + return new ResponseEntity<>(HttpStatus.TOO_MANY_REQUESTS); + } + redirection = item.getRedirection(); URI location = null; From ffa25302b5056ef932756f18ea3869ce43e2b0a4 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:55:24 +0100 Subject: [PATCH 037/125] Update tests to clean the repository --- .../java/urlshortener/demo/repository/URIRepositoryTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java b/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java index b2dcd6a9..03582dc1 100644 --- a/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java +++ b/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java @@ -1,5 +1,6 @@ package urlshortener.demo.repository; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -24,7 +25,7 @@ public URIRepositoryTest(){ this.item3 = (URIItem) new URIItem().id("abcd").redirection("http://google.es").hashpass("none"); } - @Test + @Before public void cleanUp() { super.cleanUp(repository); } @@ -51,6 +52,7 @@ public void testRemove() { @Test public void testContains(){ + repository.add(item1); super.testContains(repository, item1.getId()); super.testNotContains(repository, "randomID :D"); } From 9a7ee42719f24d4b5df60b319ea64dbb9c3fef45 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:57:17 +0100 Subject: [PATCH 038/125] Add hook to remove data from stats and then from parent repository --- .../demo/repository/impl/URIRepositoryImpl.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index 8e4bebd6..6bceca5d 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -40,6 +40,18 @@ public URIItem get(String hash) throws UnknownEntityException { return super.get(hash); } + @Override + public void remove(String hash) throws UnknownEntityException { + stats.remove(hash); + super.remove(hash); + } + + @Override + public void removeAll() { + stats.clear(); + super.removeAll(); + } + private static class URIStats{ private List lastAccesses = new ArrayList<>(); From 3cf42d5ede48448434dd6cd260f57572282a3811 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 19:57:55 +0100 Subject: [PATCH 039/125] Rename local variable stats to statsData as it was hiding this.stats --- .../demo/repository/impl/URIRepositoryImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index 6bceca5d..699e7ff2 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -20,10 +20,10 @@ public class URIRepositoryImpl extends AbstractRepository imple @Override public long getRedirectionAmount(String hash, long timeFromNow) { - URIStats stats = this.stats.get(hash); - if(stats == null) throw new UnknownEntityException(HttpStatus.BAD_REQUEST.value(), "Unknown URI " + hash); + URIStats statsData = this.stats.get(hash); + if(statsData == null) throw new UnknownEntityException(HttpStatus.BAD_REQUEST.value(), "Unknown URI " + hash); - return stats.getAccesssesAfter(System.currentTimeMillis() - timeFromNow); + return statsData.getAccesssesAfter(System.currentTimeMillis() - timeFromNow); } @Override From 000c22716a83da86dd3b05c75f8eeecfd58df710 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Sun, 9 Dec 2018 20:13:22 +0100 Subject: [PATCH 040/125] Merged develop branch with ft-check --- .../java/urlshortener/demo/controller/UriApi.java | 2 +- .../demo/controller/impl/UriApiController.java | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/UriApi.java b/demo/src/main/java/urlshortener/demo/controller/UriApi.java index 0281f71a..83b4bf51 100644 --- a/demo/src/main/java/urlshortener/demo/controller/UriApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/UriApi.java @@ -22,7 +22,7 @@ public interface UriApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PUT) - ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URIUpdate body, @ApiParam(value = "",required=true) @PathVariable("name") String name); + ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URICreate body,@ApiParam(value = "",required=true) @PathVariable("name") String name); @ApiOperation(value = "Creates a new redirection", nickname = "createURI", notes = "Create a new URI redirection ", response = URIItem.class, tags={ "F0 - The app will short, storage and get URI's", }) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index c6f8bfbd..a0270796 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -14,7 +14,7 @@ import urlshortener.demo.controller.UriApi; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; -import urlshortener.demo.domain.URIUpdate; +import urlshortener.demo.exception.IncorrectHashPassException; import urlshortener.demo.utils.CheckAlive; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; @@ -23,6 +23,9 @@ import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.ProtocolException; import java.net.URI; import java.net.URISyntaxException; @@ -57,12 +60,11 @@ public ResponseEntity changeURI(@ApiParam(value = "Optional description try { - if (c.makeRequest(redirection) == 200) { + if (Integer.valueOf(c.makeRequest(item.getRedirection())) == 200) { uriService.add(item); return new ResponseEntity(item, HttpStatus.CREATED); - } - else { + } else { return new ResponseEntity(HttpStatus.BAD_REQUEST); } } catch (MalformedURLException e) { @@ -74,6 +76,7 @@ public ResponseEntity changeURI(@ApiParam(value = "Optional description } return new ResponseEntity(HttpStatus.BAD_REQUEST); + } public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body) { String accept = request.getHeader("Accept"); From 93d29542d58b93afa6b78e973f6f1c3f16c64392 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Sun, 9 Dec 2018 20:31:19 +0100 Subject: [PATCH 041/125] Merged develop branch with ft-check --- .../urlshortener/demo/repository/URIRepository.java | 12 ++++++++---- .../demo/repository/impl/URIRepositoryImpl.java | 2 -- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index bdbde5af..f3d76b96 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -8,11 +8,15 @@ public interface URIRepository extends IRepository { List checkURI(); - URIItem obtainURI(String id); + long getRedirectionAmount(String hash, long timeFromNow); - void saveURI(URIItem uri); + void add(URIItem uri); + + URIItem get(String hash); + + void remove(String hash); + + void removeAll(); - void updateURI(URIUpdate uri); - long getRedirectionAmount(String hash, long timeFromNow); } diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index 674979d9..890f24e1 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -69,6 +69,4 @@ private long getAccesssesAfter(long time){ return lastAccesses.stream().filter(t -> t > time).count(); } } - - } From 14ec6e5129acdc9b4c05f51ee6387ddd6cb9a67a Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Sun, 9 Dec 2018 20:35:57 +0100 Subject: [PATCH 042/125] Merged develop branch with ft-check --- .../main/java/urlshortener/demo/repository/URIRepository.java | 1 - 1 file changed, 1 deletion(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index f3d76b96..d95389a1 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -1,7 +1,6 @@ package urlshortener.demo.repository; import urlshortener.demo.domain.URIItem; -import urlshortener.demo.domain.URIUpdate; import java.util.List; From e8e1bc6c2261c5095b72186a13e3cecc5120725c Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Sun, 9 Dec 2018 21:08:59 +0100 Subject: [PATCH 043/125] "Code smell" solved --- demo/src/main/java/urlshortener/demo/controller/UriApi.java | 1 - .../main/java/urlshortener/demo/repository/URIRepository.java | 2 -- .../urlshortener/demo/repository/impl/URIRepositoryImpl.java | 1 - 3 files changed, 4 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/UriApi.java b/demo/src/main/java/urlshortener/demo/controller/UriApi.java index 83b4bf51..b1f27835 100644 --- a/demo/src/main/java/urlshortener/demo/controller/UriApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/UriApi.java @@ -5,7 +5,6 @@ import org.springframework.web.bind.annotation.*; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; -import urlshortener.demo.domain.URIUpdate; import javax.validation.Valid; diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index 16fef055..d6de94d8 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -1,8 +1,6 @@ package urlshortener.demo.repository; import urlshortener.demo.domain.URIItem; -import urlshortener.demo.domain.URIUpdate; - import java.util.List; public interface URIRepository extends IRepository { diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index cc3c8169..f6280a24 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -3,7 +3,6 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Repository; import urlshortener.demo.domain.URIItem; -import urlshortener.demo.domain.URIUpdate; import urlshortener.demo.exception.CannotAddEntityException; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.AbstractRepository; From ad9e0d8da0fec7d288456c58bef16e316c5510e5 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 21:32:14 +0100 Subject: [PATCH 044/125] Update sonar shell script and properties --- sonar-project.properties | 8 ++++---- sonar.sh | 4 +++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/sonar-project.properties b/sonar-project.properties index f01676c5..13103ec5 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -20,10 +20,10 @@ sonar.java.libraries=./**/*.jar sonar.java.test.libraries=./**/*.jar sonar.java.binaries=demo/build/classes/java/main sonar.test.binaries=demo/build/classes/java/test -sonar.sources=demo/src/main/java -sonar.java.sources=demo/src/main/java -sonar.tests=demo/src/test/**/* -sonar.java.tests=demo/src/test/**/* +sonar.sources=demo/src/main +sonar.java.sources=demo/src/main +sonar.tests=demo/src/test +sonar.java.tests=demo/src/test sonar.exclusions=demo/src/main/resources/static/vendor/**/* sonar.java.coveragePlugin=jacoco diff --git a/sonar.sh b/sonar.sh index fdbf5fb6..1d0f43d7 100644 --- a/sonar.sh +++ b/sonar.sh @@ -34,4 +34,6 @@ pullRequest="${TRAVIS_PULL_REQUEST:-false}" printenv -sonar-scanner -Dsonar.projectVersion=${VERSION} \ No newline at end of file +sonar-scanner -Dsonar.projectVersion=${VERSION} + +find . \ No newline at end of file From 5615286fb4e820830268ec69d5cc462c9218e97f Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 21:36:49 +0100 Subject: [PATCH 045/125] Remove jacoco reportPath --- sonar-project.properties | 2 -- 1 file changed, 2 deletions(-) diff --git a/sonar-project.properties b/sonar-project.properties index 13103ec5..3c730f3f 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -27,5 +27,3 @@ sonar.java.tests=demo/src/test sonar.exclusions=demo/src/main/resources/static/vendor/**/* sonar.java.coveragePlugin=jacoco -sonar.jacoco.reportPath=demo/build/test-reports/jacoco.exec -sonar.jacoco.reportPaths=demo/build/test-reports/jacoco.exec From ed681b553113408003fd7a188e23b1bd75875231 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 21:44:26 +0100 Subject: [PATCH 046/125] Enable codeCoverage --- build.gradle | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build.gradle b/build.gradle index 380a33a4..1bec8efc 100644 --- a/build.gradle +++ b/build.gradle @@ -9,6 +9,8 @@ buildscript { dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } + + testCoverageEnabled true } plugins { From f74eaf6513a3551b9bd5c3e08e53174489491c0f Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 21:52:24 +0100 Subject: [PATCH 047/125] Configure jacoco on build.gradle --- build.gradle | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 1bec8efc..bf2cc91c 100644 --- a/build.gradle +++ b/build.gradle @@ -9,12 +9,11 @@ buildscript { dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } - - testCoverageEnabled true } plugins { id "org.sonarqube" version "2.6.2" + id 'jacoco' } sonarqube { @@ -24,6 +23,18 @@ sonarqube { } } +jacoco { + toolVersion = "0.8.2" + reportsDir = file("$buildDir/customJacocoReportDir") +} + +jacocoTestReport { + reports { + xml.enabled false + csv.enabled false + } +} + allprojects { apply plugin: 'idea' apply plugin: 'eclipse' From 4bd0285e95c1adc3e6a1172dd8848c0bdbae9bc9 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 21:55:44 +0100 Subject: [PATCH 048/125] Apply java plugin to all projects --- build.gradle | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index bf2cc91c..16412691 100644 --- a/build.gradle +++ b/build.gradle @@ -39,12 +39,11 @@ allprojects { apply plugin: 'idea' apply plugin: 'eclipse' apply plugin: 'jacoco' + apply plugin: 'java' } // Instructions for each sub project subprojects { - - apply plugin: 'java' apply plugin: 'io.spring.dependency-management' sourceCompatibility = 1.8 From 8ed0b10eb41b762b1403feadbb64a120c81d6b6d Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 21:57:34 +0100 Subject: [PATCH 049/125] Move jacocoTestCoverage --- build.gradle | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 16412691..1aae7f97 100644 --- a/build.gradle +++ b/build.gradle @@ -28,12 +28,6 @@ jacoco { reportsDir = file("$buildDir/customJacocoReportDir") } -jacocoTestReport { - reports { - xml.enabled false - csv.enabled false - } -} allprojects { apply plugin: 'idea' @@ -113,6 +107,13 @@ project(':demo') { testCompile 'org.springframework.boot:spring-boot-starter-test' testCompile 'org.apache.httpcomponents:httpclient' } + + jacocoTestReport { + reports { + xml.enabled false + csv.enabled false + } + } } project ('team') { From fcefa9e14a8175839fceaeef1463da74c043f24a Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 22:01:09 +0100 Subject: [PATCH 050/125] Run Jacoco?!?!?! --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 8799a1d3..be05a1b0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,8 @@ addons: token: secure: yUN8YFkxwRsLb53i+J/G3huQHEg190cvTcslKyP/m7GBpjwcrcXcvI4/z32leAQkXWnLAsjCIsoQuNHtAdFZptSMFxV9nvLeAgSQdlv8WcPO3tTKSj7nR6vFgnhpIiS/FqRCKp1X3tPCtOI5JbGjxpJ8nKjkI7ow+MxaDIATLEELcEu6XNX8lwKnFlsfAwVBGcFBx3lfZLjTnbBe+PSjFy3oLrOZyfhKXIs8RF8c7xdPN1E8Au7mml5YqYsAev5IU4GkCd7GQRWTi9k/cnC4Y9T+FlbMZp5SjebQh4cNh8jagcVSLBDfTH9dRvdw2xiniOFqQzg2SQKjf3rn2UqMnKhMqYo2kGwQZKNrHj37RYpZtaNYvQTcnoQCPk4Bk0LwxCaxG7AYyMaMO8LbCJIoCYmsaXIIzHQ79UdttVsNN+vI0qtWB0uHPToyWoB3DcvoT8ocZRSYARcQ6g53BWnmpQu5gSxgNAHhnCL7eSLhvAZfeHbSf2ObGcaHpRhEI8GiBvK4jX66nuV0H+6CODcDgniBM99Urknu24V4jJjD079psX4lWKBOiuMfrtPSXAIOCEWpSgXX10lyD/rTTasBmb111novg8JNlzB+MwnLIoAte96+AyCoYh41A2HQUh+0EOOrcgxO3kYUiaaBUbUJ4w5ex11o3BQBxsq2dX2BCdM= script: -- bash sonar.sh + - ./gradlew test jacocoTestReport + - bash sonar.sh before_install: # Our tests inspect some of *our* git history - git fetch --unshallow From f32dccab5f39adb8e8f1a011ce6d53e054273cca Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 22:08:07 +0100 Subject: [PATCH 051/125] Add reportPath --- sonar-project.properties | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sonar-project.properties b/sonar-project.properties index 3c730f3f..e18d714c 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -27,3 +27,5 @@ sonar.java.tests=demo/src/test sonar.exclusions=demo/src/main/resources/static/vendor/**/* sonar.java.coveragePlugin=jacoco +sonar.jacoco.reportPath=demo/build/jacoco/test.exec +sonar.jacoco.reportPaths=demo/build/jacoco/test.exec From e3516fa33fe9cd2ab75be0834fb5720786075073 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 22:16:34 +0100 Subject: [PATCH 052/125] Exclude all resources by now --- sonar-project.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sonar-project.properties b/sonar-project.properties index e18d714c..c2dde1e9 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -24,7 +24,7 @@ sonar.sources=demo/src/main sonar.java.sources=demo/src/main sonar.tests=demo/src/test sonar.java.tests=demo/src/test -sonar.exclusions=demo/src/main/resources/static/vendor/**/* +sonar.exclusions=demo/src/main/resources/**/* sonar.java.coveragePlugin=jacoco sonar.jacoco.reportPath=demo/build/jacoco/test.exec From 83d8410db151882a0bfc9ff615c99d8e616f69ac Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 22:25:16 +0100 Subject: [PATCH 053/125] Test URIUpdate toString --- .../java/urlshortener/demo/domain/URIUpdateTests.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java index b673ded5..e2a2fea6 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java +++ b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java @@ -15,6 +15,14 @@ public void testOK(){ assertEquals(uriUpdate3, uriUpdate1); assertEquals(uriUpdate3, uriUpdate2); + assertEquals("abc", uriUpdate1.getNewName()); + assertEquals("abcd", uriUpdate1.getHashpass()); + } + + @Test + public void testToString(){ + URIUpdate uriUpdate1 = (URIUpdate) new URIUpdate().newName("abc").hashpass("abcd"); + assertEquals("class URIUpdate {\n newName: abc\n hashpass: abcd\n}", uriUpdate1.toString()); } } From a54a098845a117d20e956473d2407f51ef5ee4b9 Mon Sep 17 00:00:00 2001 From: lAngelP Date: Sun, 9 Dec 2018 22:32:17 +0100 Subject: [PATCH 054/125] Update .travis.yml --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index be05a1b0..0ff0325c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,6 +11,5 @@ script: - bash sonar.sh before_install: # Our tests inspect some of *our* git history - - git fetch --unshallow - openssl aes-256-cbc -K $encrypted_be44edb6a80d_key -iv $encrypted_be44edb6a80d_iv -in app.properties.enc -out app.properties -d From 11e4ea982a821e757887d1c6af768c2fd252e2b3 Mon Sep 17 00:00:00 2001 From: lAngel Date: Sun, 9 Dec 2018 22:42:05 +0100 Subject: [PATCH 055/125] Remove runtime exceptions thrown from method --- .../demo/repository/impl/URIRepositoryImpl.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index 699e7ff2..904ea824 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -3,7 +3,6 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Repository; import urlshortener.demo.domain.URIItem; -import urlshortener.demo.exception.CannotAddEntityException; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.AbstractRepository; import urlshortener.demo.repository.URIRepository; @@ -27,13 +26,13 @@ public long getRedirectionAmount(String hash, long timeFromNow) { } @Override - public void add(URIItem uri) throws CannotAddEntityException { + public void add(URIItem uri) { stats.putIfAbsent(uri.getId(), new URIStats()); super.add(uri); } @Override - public URIItem get(String hash) throws UnknownEntityException { + public URIItem get(String hash) { stats.putIfAbsent(hash, new URIStats()); stats.get(hash).addAccess(); @@ -41,7 +40,7 @@ public URIItem get(String hash) throws UnknownEntityException { } @Override - public void remove(String hash) throws UnknownEntityException { + public void remove(String hash) { stats.remove(hash); super.remove(hash); } From d8737ce41de1942f33bcf0f2cb9339a50a62fa23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Fern=C3=A1ndez=20Melic?= Date: Mon, 10 Dec 2018 18:36:05 +0100 Subject: [PATCH 056/125] QrApiController updated --- .gitignore | 12 +++------ .../demo/controller/impl/QrApiController.java | 26 ++++++++++++++++--- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 8ba30af0..ad59a637 100644 --- a/.gitignore +++ b/.gitignore @@ -16,14 +16,10 @@ gradle-app.setting out/ *.iml .DS_Store -.project/ +.project .settings/org.eclipse.buildship.core.prefs -common/src/main/java/io/swagger/api/CheckApiController.java -team/.classpath -team/.project/ -team/.settings/org.eclipse.buildship.core.prefs -team/.settings/org.eclipse.jdt.core.prefs -team/bin/main/urlshortener/team/Application.class +.classpath +.settings/ .vscode - +bin/ app.properties \ No newline at end of file diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java index 14792544..16dc592a 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java @@ -11,6 +11,9 @@ import org.springframework.web.bind.annotation.PathVariable; import urlshortener.demo.controller.QrApi; import urlshortener.demo.domain.QRItem; +import urlshortener.demo.domain.URIItem; +import urlshortener.demo.repository.QRRepository; +import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.*; import javax.servlet.http.HttpServletRequest; @@ -26,10 +29,16 @@ public class QrApiController implements QrApi { private final HttpServletRequest request; + private final QRRepository qrRepository; + + private final URIRepository uriRepository; + @org.springframework.beans.factory.annotation.Autowired - public QrApiController(ObjectMapper objectMapper, HttpServletRequest request) { + public QrApiController(ObjectMapper objectMapper, HttpServletRequest request, QRRepository qrRepository, URIRepository uriRepository) { this.objectMapper = objectMapper; this.request = request; + this.qrRepository = qrRepository; + this.uriRepository = uriRepository; } public ResponseEntity getQR(@ApiParam(value = "",required=true) @PathVariable("id") String id) { @@ -37,15 +46,24 @@ public ResponseEntity getQR(@ApiParam(value = "",required=true) @PathVar String accept = request.getHeader("Accept"); String width = request.getParameter("width"); String height = request.getParameter("height"); + + QRItem qr; // Check that width and heigth params are not null or negative // and return int int w = StringChecker.checkString2Int(width); int h = StringChecker.checkString2Int(height); - QRItem qr = new QRItem(); - qr.setUri(id); - qr.convertBase64(w, h); + // Default qr is required, so it's saved if the uri is shorthed + if(w==500 && h==500){ + qr = this.qrRepository.get(id); + }else{ + URIItem uriItem = this.uriRepository.get(id); + qr = new QRItem(); + qr.setUri(uriItem.getId()); + qr.convertBase64(w, h); + } + return new ResponseEntity(qr, HttpStatus.OK); } From 66b5e1aff5f668492b3719d266c90d132e39a511 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 15:40:28 +0100 Subject: [PATCH 057/125] Remove exceptions duplicating error codes --- .../urlshortener/demo/exception/CannotAddEntityException.java | 2 -- .../urlshortener/demo/exception/IncorrectHashPassException.java | 2 -- .../demo/exception/InvalidRequestParametersException.java | 2 -- .../java/urlshortener/demo/exception/NotFoundException.java | 2 -- .../urlshortener/demo/exception/UnknownEntityException.java | 2 -- 5 files changed, 10 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/exception/CannotAddEntityException.java b/demo/src/main/java/urlshortener/demo/exception/CannotAddEntityException.java index 7e7b5342..3594124d 100644 --- a/demo/src/main/java/urlshortener/demo/exception/CannotAddEntityException.java +++ b/demo/src/main/java/urlshortener/demo/exception/CannotAddEntityException.java @@ -3,9 +3,7 @@ @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-26T14:20:22.002Z[GMT]") public class CannotAddEntityException extends RuntimeApiException { - private int code; public CannotAddEntityException(int code, String msg) { super(code, msg); - this.code = code; } } diff --git a/demo/src/main/java/urlshortener/demo/exception/IncorrectHashPassException.java b/demo/src/main/java/urlshortener/demo/exception/IncorrectHashPassException.java index eb7afbbf..89aaf821 100644 --- a/demo/src/main/java/urlshortener/demo/exception/IncorrectHashPassException.java +++ b/demo/src/main/java/urlshortener/demo/exception/IncorrectHashPassException.java @@ -3,9 +3,7 @@ @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-26T14:20:22.002Z[GMT]") public class IncorrectHashPassException extends RuntimeApiException { - private int code; public IncorrectHashPassException(int code, String msg) { super(code, msg); - this.code = code; } } diff --git a/demo/src/main/java/urlshortener/demo/exception/InvalidRequestParametersException.java b/demo/src/main/java/urlshortener/demo/exception/InvalidRequestParametersException.java index 9131f2ac..36d32a2e 100644 --- a/demo/src/main/java/urlshortener/demo/exception/InvalidRequestParametersException.java +++ b/demo/src/main/java/urlshortener/demo/exception/InvalidRequestParametersException.java @@ -3,9 +3,7 @@ @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-26T14:20:22.002Z[GMT]") public class InvalidRequestParametersException extends RuntimeApiException { - private int code; public InvalidRequestParametersException(int code, String msg) { super(code, msg); - this.code = code; } } diff --git a/demo/src/main/java/urlshortener/demo/exception/NotFoundException.java b/demo/src/main/java/urlshortener/demo/exception/NotFoundException.java index 44cd56c6..4a14eb77 100644 --- a/demo/src/main/java/urlshortener/demo/exception/NotFoundException.java +++ b/demo/src/main/java/urlshortener/demo/exception/NotFoundException.java @@ -3,9 +3,7 @@ @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-26T14:20:22.002Z[GMT]") public class NotFoundException extends ApiException { - private int code; public NotFoundException (int code, String msg) { super(code, msg); - this.code = code; } } diff --git a/demo/src/main/java/urlshortener/demo/exception/UnknownEntityException.java b/demo/src/main/java/urlshortener/demo/exception/UnknownEntityException.java index 3416d8cc..075f80c9 100644 --- a/demo/src/main/java/urlshortener/demo/exception/UnknownEntityException.java +++ b/demo/src/main/java/urlshortener/demo/exception/UnknownEntityException.java @@ -3,9 +3,7 @@ @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-26T14:20:22.002Z[GMT]") public class UnknownEntityException extends RuntimeApiException{ - private int code; public UnknownEntityException(int code, String msg) { super(code, msg); - this.code = code; } } From 2c7adc22490d3ce505ced74d23ca278c623347a6 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 15:46:39 +0100 Subject: [PATCH 058/125] Throw custom exception instead of catching exception and not doing anything --- .../demo/controller/impl/UriApiController.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index fc7f7ee8..31ca17b6 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -15,6 +15,7 @@ import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; import urlshortener.demo.exception.IncorrectHashPassException; +import urlshortener.demo.exception.InvalidRequestParametersException; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.ParameterUtils; @@ -83,23 +84,21 @@ public ResponseEntity deleteURI(@ApiParam(value = "",required=true) @PathV public ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVariable("id") String id) { String accept = request.getHeader("Accept"); - String redirection; URIItem item = uriService.get(id); if(item == null){ throw new UnknownEntityException(1, "Unknown URI: " + id); } - if(uriService.getRedirectionAmount(id, MAX_REDIRECTION_TIME) > MAX_REDIRECTIONS){ - return new ResponseEntity<>(HttpStatus.TOO_MANY_REQUESTS); - } - - redirection = item.getRedirection(); - + String redirection = item.getRedirection(); URI location = null; try { location = new URI(redirection); } catch (URISyntaxException e) { - e.printStackTrace(); + throw new InvalidRequestParametersException(HttpStatus.BAD_REQUEST.value(), ""); + } + + if(uriService.getRedirectionAmount(id, MAX_REDIRECTION_TIME) > MAX_REDIRECTIONS){ + return new ResponseEntity<>(HttpStatus.TOO_MANY_REQUESTS); } HttpHeaders responseHeaders = new HttpHeaders(); From 156e51d0bed8842752515d6bab970de66ad7e33c Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 15:47:02 +0100 Subject: [PATCH 059/125] Test getting redirection amount of nonexisting item --- .../urlshortener/demo/repository/URIRepositoryTest.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java b/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java index 03582dc1..4fa3c675 100644 --- a/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java +++ b/demo/src/test/java/urlshortener/demo/repository/URIRepositoryTest.java @@ -7,8 +7,10 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.exception.UnknownEntityException; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; @RunWith(SpringRunner.class) @@ -65,5 +67,10 @@ public void testRedirectionAmount(){ repository.get(item1.getId()); assertEquals(1, repository.getRedirectionAmount(item1.getId(), System.currentTimeMillis())); assertEquals(0, repository.getRedirectionAmount(item1.getId(), -1000)); + + try{ + repository.getRedirectionAmount(item1.getId() + "invalid", -1000); + fail(); + }catch(UnknownEntityException ignored){} } } From e066287aecda57d75eaab8531eebb6be879357b3 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 15:52:05 +0100 Subject: [PATCH 060/125] Test that, if URI has the wrong format, request returns HTTP 400. --- .../controller/UriApiControllerIntegrationTest.java | 11 +++++++++++ .../src/test/java/urlshortener/demo/web/UriTests.java | 7 +++++++ .../urlshortener/demo/web/fixture/UriItemFixture.java | 4 ++++ 3 files changed, 22 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java index 4e146ce0..4cd42e0c 100644 --- a/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/UriApiControllerIntegrationTest.java @@ -219,4 +219,15 @@ public void getURITestTooManyRequests() { assertEquals(HttpStatus.TOO_MANY_REQUESTS, responseEntity.getStatusCode()); } + @Test + public void getURITestInvalidURLFormat() { + String id = "id_example"; + repository.add((URIItem) new URIItem().id(id).redirection("2invalid0http:/google.es").hashpass("abc")); + + try { + api.getURI(id); + fail(); + }catch(InvalidRequestParametersException ignored){} + } + } diff --git a/demo/src/test/java/urlshortener/demo/web/UriTests.java b/demo/src/test/java/urlshortener/demo/web/UriTests.java index 5bdc89b8..89a4d4ff 100644 --- a/demo/src/test/java/urlshortener/demo/web/UriTests.java +++ b/demo/src/test/java/urlshortener/demo/web/UriTests.java @@ -217,6 +217,13 @@ public void getUriWorks() throws Exception { .andExpect(redirectedUrl(item.getRedirection())); } + @Test + public void getUriInvalidURL() throws Exception { + when(service.get("1")).thenReturn(someURIInvalidURI()); + mockMvc.perform(get("/uri/{id}", "1")).andDo(print()) + .andExpect(status().isBadRequest()); + } + @Test public void getUriError() throws Exception { when(service.get("1")).thenReturn(null); diff --git a/demo/src/test/java/urlshortener/demo/web/fixture/UriItemFixture.java b/demo/src/test/java/urlshortener/demo/web/fixture/UriItemFixture.java index 362aecbc..4dc45355 100644 --- a/demo/src/test/java/urlshortener/demo/web/fixture/UriItemFixture.java +++ b/demo/src/test/java/urlshortener/demo/web/fixture/UriItemFixture.java @@ -9,6 +9,10 @@ public static URIItem someURI(){ return (URIItem) new URIItem().id("abc").redirection("https://google.es").hashpass("abc"); } + public static URIItem someURIInvalidURI(){ + return (URIItem) new URIItem().id("abc").redirection("2invalid0http://google.es").hashpass("abc"); + } + public static URICreate someCorrectURICreate(){ return new URICreate().uri("https://www.google.es"); } From 17263643669c3dc28f388f10d9f7467c1d88b36f Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:03:15 +0100 Subject: [PATCH 061/125] Create StringCheckerTest --- .../demo/utils/StringCheckerTest.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/utils/StringCheckerTest.java diff --git a/demo/src/test/java/urlshortener/demo/utils/StringCheckerTest.java b/demo/src/test/java/urlshortener/demo/utils/StringCheckerTest.java new file mode 100644 index 00000000..6f23f8b1 --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/utils/StringCheckerTest.java @@ -0,0 +1,18 @@ +package urlshortener.demo.utils; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class StringCheckerTest { + + @Test + public void testStringChecker(){ + assertEquals(500, StringChecker.checkString2Int(null)); + assertEquals(500, StringChecker.checkString2Int("0")); + assertEquals(500, StringChecker.checkString2Int("3000")); + assertEquals(500, StringChecker.checkString2Int("500")); + + } + +} From eaa769eccca022db7dcb39edd9140bd30b306bdf Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:03:32 +0100 Subject: [PATCH 062/125] Create URIBaseTest --- .../urlshortener/demo/domain/URIBaseTest.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java diff --git a/demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java b/demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java new file mode 100644 index 00000000..1c45bfd7 --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java @@ -0,0 +1,46 @@ +package urlshortener.demo.domain; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class URIBaseTest { + + @Test + public void testURIBaseHashpass(){ + URIBase base = new URIBase().hashpass("abc"); + + assertEquals("abc", base.getHashpass()); + base.setHashpass("abcd"); + assertEquals("abcd", base.getHashpass()); + } + + @Test + public void testURIBaseEquals(){ + URIBase base = new URIBase().hashpass("abc"); + URIBase base2 = new URIBase().hashpass("abc"); + URIBase base3 = new URIBase().hashpass("abcd"); + + assertEquals(base, base); + assertNotEquals(base, null); + assertNotEquals(base, "abc"); + assertEquals(base, base2); + assertNotEquals(base, base3); + } + + @Test + public void testURIBaseCheckHashcode(){ + URIBase base = new URIBase().hashpass("abc"); + + assertEquals(96385, base.hashCode()); + } + + @Test + public void testURIBaseCheckHashpass(){ + URIBase base = new URIBase().hashpass("abc"); + + assertFalse(base.checkHashPass(null)); + assertFalse(base.checkHashPass("abcd")); + assertTrue(base.checkHashPass("abc")); + } +} From 87977181bac3ca7b23904ba45d617dc4080d7b80 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:03:56 +0100 Subject: [PATCH 063/125] Fix URIBase --- demo/src/main/java/urlshortener/demo/domain/URIBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/src/main/java/urlshortener/demo/domain/URIBase.java b/demo/src/main/java/urlshortener/demo/domain/URIBase.java index f8404fd5..988d1470 100644 --- a/demo/src/main/java/urlshortener/demo/domain/URIBase.java +++ b/demo/src/main/java/urlshortener/demo/domain/URIBase.java @@ -40,7 +40,7 @@ public boolean equals(java.lang.Object o) { if (o == null || getClass() != o.getClass()) { return false; } - URIBase urIItem = (URIItem) o; + URIBase urIItem = (URIBase) o; return Objects.equals(this.hashpass, urIItem.hashpass); } From f8baec7c7f719af1d36ea195c41cda8e6930ee75 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:09:37 +0100 Subject: [PATCH 064/125] Remove code from constructor --- .../main/java/urlshortener/demo/utils/StringChecker.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/utils/StringChecker.java b/demo/src/main/java/urlshortener/demo/utils/StringChecker.java index 4aeae62b..ac3b5e97 100644 --- a/demo/src/main/java/urlshortener/demo/utils/StringChecker.java +++ b/demo/src/main/java/urlshortener/demo/utils/StringChecker.java @@ -2,12 +2,8 @@ public class StringChecker { - private StringChecker() { - throw new IllegalStateException("Utility class"); - } - public static int checkString2Int(String string){ - + if (string == null){ return 500; } @@ -25,4 +21,7 @@ public static int checkString2Int(String string){ return num; } + private StringChecker() { + //Let's hide the implicit public constructor as this class should never be instantiated. + } } \ No newline at end of file From 01baa22e46f3e8ef60b1c4638e3957c2c135110e Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:11:10 +0100 Subject: [PATCH 065/125] Check if hashpass is null --- demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java b/demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java index 1c45bfd7..9a540d16 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java +++ b/demo/src/test/java/urlshortener/demo/domain/URIBaseTest.java @@ -38,9 +38,14 @@ public void testURIBaseCheckHashcode(){ @Test public void testURIBaseCheckHashpass(){ URIBase base = new URIBase().hashpass("abc"); + URIBase base2 = new URIBase().hashpass(null); assertFalse(base.checkHashPass(null)); assertFalse(base.checkHashPass("abcd")); assertTrue(base.checkHashPass("abc")); + + assertFalse(base2.checkHashPass(null)); + assertFalse(base2.checkHashPass("abcd")); + assertFalse(base2.checkHashPass("abc")); } } From cc474d73e6b82fab2e637cb4c6fe66d039afd475 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:21:11 +0100 Subject: [PATCH 066/125] Add QRItem tests --- .../urlshortener/demo/domain/QRItemTest.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/domain/QRItemTest.java diff --git a/demo/src/test/java/urlshortener/demo/domain/QRItemTest.java b/demo/src/test/java/urlshortener/demo/domain/QRItemTest.java new file mode 100644 index 00000000..2ea934f3 --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/domain/QRItemTest.java @@ -0,0 +1,56 @@ +package urlshortener.demo.domain; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class QRItemTest { + + @Test + public void checkQRQR(){ + QRItem qrItem = new QRItem().qr("qr"); + + assertEquals("qr", qrItem.getQr()); + qrItem.setQr("qr2"); + assertEquals("qr2", qrItem.getQr()); + } + + @Test + public void checkQRUri(){ + QRItem qrItem = new QRItem().uri("http://unizar.com"); + + assertEquals("http://unizar.com", qrItem.getUri()); + assertEquals("http://unizar.com", qrItem.getId()); + qrItem.setUri("http://unizar.es"); + assertEquals("http://unizar.es", qrItem.getUri()); + } + + @Test + public void testQREquals(){ + QRItem base = new QRItem().uri("abc"); + QRItem base2 = new QRItem().uri("abc"); + QRItem base3 = new QRItem().uri("abcd"); + QRItem base4 = new QRItem().uri("abcd").qr("otherQR"); + + assertEquals(base, base); + assertNotEquals(base, null); + assertNotEquals(base, "abc"); + assertEquals(base, base2); + assertNotEquals(base, base3); + assertNotEquals(base, base4); + } + + @Test + public void testQRHashcode(){ + QRItem base = new QRItem().uri("abc"); + + assertEquals(2987935, base.hashCode()); + } + + @Test + public void testQRtoString(){ + QRItem base = new QRItem().uri("abc"); + assertEquals("class QRItem {\n uri: abc\n qr: null\n}", base.toString()); + } +} From 427b48f2e4942fad38ab530fc110b477d4229bd3 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:30:04 +0100 Subject: [PATCH 067/125] Remove Click and ShortURL --- .../demo/config/PersistenceContext.java | 16 -- .../java/urlshortener/demo/domain/Click.java | 88 ---------- .../urlshortener/demo/domain/ShortURL.java | 108 ------------- .../demo/repository/ClickRepository.java | 24 --- .../demo/repository/ClickRepositoryImpl.java | 151 ------------------ .../demo/repository/ShortURLRepository.java | 25 --- .../repository/ShortURLRepositoryImpl.java | 131 --------------- .../demo/web/UrlShortenerController.java | 101 ------------ .../demo/repository/ClickRepositoryTests.java | 85 ---------- .../repository/ShortURLRepositoryTests.java | 129 --------------- .../demo/repository/fixture/ClickFixture.java | 11 -- .../repository/fixture/ShortURLFixture.java | 34 ---- .../demo/web/UrlShortenerTests.java | 115 ------------- .../demo/web/fixture/ShortURLFixture.java | 10 -- 14 files changed, 1028 deletions(-) delete mode 100644 demo/src/main/java/urlshortener/demo/domain/Click.java delete mode 100644 demo/src/main/java/urlshortener/demo/domain/ShortURL.java delete mode 100644 demo/src/main/java/urlshortener/demo/repository/ClickRepository.java delete mode 100644 demo/src/main/java/urlshortener/demo/repository/ClickRepositoryImpl.java delete mode 100644 demo/src/main/java/urlshortener/demo/repository/ShortURLRepository.java delete mode 100644 demo/src/main/java/urlshortener/demo/repository/ShortURLRepositoryImpl.java delete mode 100755 demo/src/main/java/urlshortener/demo/web/UrlShortenerController.java delete mode 100644 demo/src/test/java/urlshortener/demo/repository/ClickRepositoryTests.java delete mode 100644 demo/src/test/java/urlshortener/demo/repository/ShortURLRepositoryTests.java delete mode 100644 demo/src/test/java/urlshortener/demo/repository/fixture/ClickFixture.java delete mode 100644 demo/src/test/java/urlshortener/demo/repository/fixture/ShortURLFixture.java delete mode 100644 demo/src/test/java/urlshortener/demo/web/UrlShortenerTests.java delete mode 100644 demo/src/test/java/urlshortener/demo/web/fixture/ShortURLFixture.java diff --git a/demo/src/main/java/urlshortener/demo/config/PersistenceContext.java b/demo/src/main/java/urlshortener/demo/config/PersistenceContext.java index 40780e55..40efa828 100755 --- a/demo/src/main/java/urlshortener/demo/config/PersistenceContext.java +++ b/demo/src/main/java/urlshortener/demo/config/PersistenceContext.java @@ -1,17 +1,11 @@ package urlshortener.demo.config; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.jdbc.core.JdbcTemplate; -import urlshortener.demo.repository.ClickRepository; -import urlshortener.demo.repository.ClickRepositoryImpl; -import urlshortener.demo.repository.ShortURLRepository; -import urlshortener.demo.repository.ShortURLRepositoryImpl; - @Configuration @ComponentScan(basePackages = {"urlshortener.demo" }) @Import({JacksonConfiguration.class, SwaggerDocumentationConfig.class}) @@ -19,15 +13,5 @@ public class PersistenceContext { @Autowired protected JdbcTemplate jdbc; - - @Bean - ShortURLRepository shortURLRepository() { - return new ShortURLRepositoryImpl(jdbc); - } - - @Bean - ClickRepository clickRepository() { - return new ClickRepositoryImpl(jdbc); - } } diff --git a/demo/src/main/java/urlshortener/demo/domain/Click.java b/demo/src/main/java/urlshortener/demo/domain/Click.java deleted file mode 100644 index 41417404..00000000 --- a/demo/src/main/java/urlshortener/demo/domain/Click.java +++ /dev/null @@ -1,88 +0,0 @@ -package urlshortener.demo.domain; - -import java.sql.Date; - -public class Click { - - private Long id; - private String hash; - private Date created; - private String referrer; - private String browser; - private String platform; - private String ip; - private String country; - - - public Long getId() { - return id; - } - - public String getHash() { - return hash; - } - - public Date getCreated() { - return created; - } - - public String getReferrer() { - return referrer; - } - - public String getBrowser() { - return browser; - } - - public String getPlatform() { - return platform; - } - - public String getIp() { - return ip; - } - - public String getCountry() { - return country; - } - - public Click id(Long id) { - this.id = id; - return this; - } - - public Click hash(String hash) { - this.hash = hash; - return this; - } - - public Click created(Date created) { - this.created = created; - return this; - } - - public Click referrer(String referrer) { - this.referrer = referrer; - return this; - } - - public Click browser(String browser) { - this.browser = browser; - return this; - } - - public Click platform(String platform) { - this.platform = platform; - return this; - } - - public Click ip(String ip) { - this.ip = ip; - return this; - } - - public Click country(String country) { - this.country = country; - return this; - } -} diff --git a/demo/src/main/java/urlshortener/demo/domain/ShortURL.java b/demo/src/main/java/urlshortener/demo/domain/ShortURL.java deleted file mode 100644 index 4b579ae0..00000000 --- a/demo/src/main/java/urlshortener/demo/domain/ShortURL.java +++ /dev/null @@ -1,108 +0,0 @@ -package urlshortener.demo.domain; - -import java.net.URI; -import java.sql.Date; - -public class ShortURL { - - private String hash; - private String target; - private URI uri; - private String sponsor; - private Date created; - private String owner; - private Integer mode; - private Boolean safe; - private String ip; - private String country; - - public String getHash() { - return hash; - } - - public String getTarget() { - return target; - } - - public URI getUri() { - return uri; - } - - public Date getCreated() { - return created; - } - - public String getOwner() { - return owner; - } - - public Integer getMode() { - return mode; - } - - public String getSponsor() { - return sponsor; - } - - public Boolean getSafe() { - return safe; - } - - public String getIP() { - return ip; - } - - public String getCountry() { - return country; - } - - public ShortURL hash(String hash) { - this.hash = hash; - return this; - } - - public ShortURL target(String target) { - this.target = target; - return this; - } - - public ShortURL uri(URI uri) { - this.uri = uri; - return this; - } - - public ShortURL sponsor(String sponsor) { - this.sponsor = sponsor; - return this; - } - - public ShortURL created(Date created) { - this.created = created; - return this; - } - - public ShortURL owner(String owner) { - this.owner = owner; - return this; - } - - public ShortURL mode(Integer mode) { - this.mode = mode; - return this; - } - - public ShortURL safe(Boolean safe) { - this.safe = safe; - return this; - } - - public ShortURL ip(String ip) { - this.ip = ip; - return this; - } - - public ShortURL country(String country) { - this.country = country; - return this; - } -} diff --git a/demo/src/main/java/urlshortener/demo/repository/ClickRepository.java b/demo/src/main/java/urlshortener/demo/repository/ClickRepository.java deleted file mode 100644 index 3dec2ff9..00000000 --- a/demo/src/main/java/urlshortener/demo/repository/ClickRepository.java +++ /dev/null @@ -1,24 +0,0 @@ -package urlshortener.demo.repository; - -import java.util.List; - -import urlshortener.demo.domain.Click; - -public interface ClickRepository { - - List findByHash(String hash); - - Long clicksByHash(String hash); - - Click save(Click cl); - - void update(Click cl); - - void delete(Long id); - - void deleteAll(); - - Long count(); - - List list(Long limit, Long offset); -} diff --git a/demo/src/main/java/urlshortener/demo/repository/ClickRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/ClickRepositoryImpl.java deleted file mode 100644 index 2886db2d..00000000 --- a/demo/src/main/java/urlshortener/demo/repository/ClickRepositoryImpl.java +++ /dev/null @@ -1,151 +0,0 @@ -package urlshortener.demo.repository; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.DirectFieldAccessor; -import org.springframework.dao.DuplicateKeyException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.stereotype.Repository; -import urlshortener.demo.domain.Click; - -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.sql.Types; -import java.util.Collections; -import java.util.List; - - -@Repository -public class ClickRepositoryImpl implements ClickRepository { - - private static final Logger log = LoggerFactory - .getLogger(urlshortener.demo.repository.ClickRepositoryImpl.class); - - private static final RowMapper rowMapper = (rs, rowNum) -> new Click() - .id(rs.getLong("id")).hash(rs.getString("hash")) - .created(rs.getDate("created")).referrer(rs.getString("referrer")).browser(rs.getString("browser")).platform(rs.getString("platform")) - .ip(rs.getString("ip")).country(rs.getString("country")); - - private JdbcTemplate jdbc; - - public ClickRepositoryImpl(JdbcTemplate jdbc) { - this.jdbc = jdbc; - } - - @Override - public List findByHash(String hash) { - try { - return jdbc.query("SELECT * FROM click WHERE hash=?", - new Object[] { hash }, rowMapper); - } catch (Exception e) { - log.debug("When select for hash " + hash, e); - return Collections.emptyList(); - } - } - - @Override - public Click save(final Click cl) { - try { - KeyHolder holder = new GeneratedKeyHolder(); - jdbc.update(conn -> { - PreparedStatement ps = conn - .prepareStatement( - "INSERT INTO CLICK VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - Statement.RETURN_GENERATED_KEYS); - ps.setNull(1, Types.BIGINT); - ps.setString(2, cl.getHash()); - ps.setDate(3, cl.getCreated()); - ps.setString(4, cl.getReferrer()); - ps.setString(5, cl.getBrowser()); - ps.setString(6, cl.getPlatform()); - ps.setString(7, cl.getIp()); - ps.setString(8, cl.getCountry()); - return ps; - }, holder); - if (holder.getKey() != null) { - new DirectFieldAccessor(cl).setPropertyValue("id", holder.getKey() - .longValue()); - } else { - log.debug("Key from database is null"); - } - } catch (DuplicateKeyException e) { - log.debug("When insert for click with id " + cl.getId(), e); - return cl; - } catch (Exception e) { - log.debug("When insert a click", e); - return null; - } - return cl; - } - - @Override - public void update(Click cl) { - log.info("ID2: {} navegador: {} SO: {} Date: {}", cl.getId(), cl.getBrowser(), cl.getPlatform(), cl.getCreated()); - try { - jdbc.update( - "update click set hash=?, created=?, referrer=?, browser=?, platform=?, ip=?, country=? where id=?", - cl.getHash(), cl.getCreated(), cl.getReferrer(), - cl.getBrowser(), cl.getPlatform(), cl.getIp(), - cl.getCountry(), cl.getId()); - - } catch (Exception e) { - log.info("When update for id " + cl.getId(), e); - } - } - - @Override - public void delete(Long id) { - try { - jdbc.update("delete from click where id=?", id); - } catch (Exception e) { - log.debug("When delete for id " + id, e); - } - } - - @Override - public void deleteAll() { - try { - jdbc.update("delete from click"); - } catch (Exception e) { - log.debug("When delete all", e); - } - } - - @Override - public Long count() { - try { - return jdbc - .queryForObject("select count(*) from click", Long.class); - } catch (Exception e) { - log.debug("When counting", e); - } - return -1L; - } - - @Override - public List list(Long limit, Long offset) { - try { - return jdbc.query("SELECT * FROM click LIMIT ? OFFSET ?", - new Object[] { limit, offset }, rowMapper); - } catch (Exception e) { - log.debug("When select for limit " + limit + " and offset " - + offset, e); - return Collections.emptyList(); - } - } - - @Override - public Long clicksByHash(String hash) { - try { - return jdbc - .queryForObject("select count(*) from click where hash = ?", new Object[]{hash}, Long.class); - } catch (Exception e) { - log.debug("When counting hash "+hash, e); - } - return -1L; - } - -} diff --git a/demo/src/main/java/urlshortener/demo/repository/ShortURLRepository.java b/demo/src/main/java/urlshortener/demo/repository/ShortURLRepository.java deleted file mode 100644 index d06877e9..00000000 --- a/demo/src/main/java/urlshortener/demo/repository/ShortURLRepository.java +++ /dev/null @@ -1,25 +0,0 @@ -package urlshortener.demo.repository; - -import java.util.List; - -import urlshortener.demo.domain.ShortURL; - -public interface ShortURLRepository { - - ShortURL findByKey(String id); - - List findByTarget(String target); - - ShortURL save(ShortURL su); - - ShortURL mark(ShortURL urlSafe, boolean safeness); - - void update(ShortURL su); - - void delete(String id); - - Long count(); - - List list(Long limit, Long offset); - -} diff --git a/demo/src/main/java/urlshortener/demo/repository/ShortURLRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/ShortURLRepositoryImpl.java deleted file mode 100644 index 3fe315a5..00000000 --- a/demo/src/main/java/urlshortener/demo/repository/ShortURLRepositoryImpl.java +++ /dev/null @@ -1,131 +0,0 @@ -package urlshortener.demo.repository; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.DirectFieldAccessor; -import org.springframework.dao.DuplicateKeyException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.stereotype.Repository; -import urlshortener.demo.domain.ShortURL; - -import java.util.Collections; -import java.util.List; - -@Repository -public class ShortURLRepositoryImpl implements ShortURLRepository { - - private static final Logger log = LoggerFactory - .getLogger(ShortURLRepositoryImpl.class); - - private static final RowMapper rowMapper = (rs, rowNum) -> new ShortURL() - .hash(rs.getString("hash")).target(rs.getString("target")) - .sponsor(rs.getString("sponsor")).created(rs.getDate("created")) - .owner(rs.getString("owner")).mode(rs.getInt("mode")) - .safe(rs.getBoolean("safe")).ip(rs.getString("ip")) - .country(rs.getString("country")); - private JdbcTemplate jdbc; - - public ShortURLRepositoryImpl(JdbcTemplate jdbc) { - this.jdbc = jdbc; - } - - @Override - public ShortURL findByKey(String id) { - try { - return jdbc.queryForObject("SELECT * FROM shorturl WHERE hash=?", - rowMapper, id); - } catch (Exception e) { - log.debug("When select for key {}", id, e); - return null; - } - } - - @Override - public ShortURL save(ShortURL su) { - try { - jdbc.update("INSERT INTO shorturl VALUES (?,?,?,?,?,?,?,?,?)", - su.getHash(), su.getTarget(), su.getSponsor(), - su.getCreated(), su.getOwner(), su.getMode(), su.getSafe(), - su.getIP(), su.getCountry()); - } catch (DuplicateKeyException e) { - log.debug("When insert for key {}", su.getHash(), e); - return su; - } catch (Exception e) { - log.debug("When insert", e); - return null; - } - return su; - } - - @Override - public ShortURL mark(ShortURL su, boolean safeness) { - try { - jdbc.update("UPDATE shorturl SET safe=? WHERE hash=?", safeness, - su.getHash()); - ShortURL res = new ShortURL(); - BeanUtils.copyProperties(su, res); - new DirectFieldAccessor(res).setPropertyValue("safe", safeness); - return res; - } catch (Exception e) { - log.debug("When update", e); - return null; - } - } - - @Override - public void update(ShortURL su) { - try { - jdbc.update( - "update shorturl set target=?, sponsor=?, created=?, owner=?, mode=?, safe=?, ip=?, country=? where hash=?", - su.getTarget(), su.getSponsor(), su.getCreated(), - su.getOwner(), su.getMode(), su.getSafe(), su.getIP(), - su.getCountry(), su.getHash()); - } catch (Exception e) { - log.debug("When update for hash {}", su.getHash(), e); - } - } - - @Override - public void delete(String hash) { - try { - jdbc.update("delete from shorturl where hash=?", hash); - } catch (Exception e) { - log.debug("When delete for hash {}", hash, e); - } - } - - @Override - public Long count() { - try { - return jdbc.queryForObject("select count(*) from shorturl", - Long.class); - } catch (Exception e) { - log.debug("When counting", e); - } - return -1L; - } - - @Override - public List list(Long limit, Long offset) { - try { - return jdbc.query("SELECT * FROM shorturl LIMIT ? OFFSET ?", - new Object[] { limit, offset }, rowMapper); - } catch (Exception e) { - log.debug("When select for limit {} and offset {}", limit, offset, e); - return Collections.emptyList(); - } - } - - @Override - public List findByTarget(String target) { - try { - return jdbc.query("SELECT * FROM shorturl WHERE target = ?", - new Object[] { target }, rowMapper); - } catch (Exception e) { - log.debug("When select for target " + target , e); - return Collections.emptyList(); - } - } -} diff --git a/demo/src/main/java/urlshortener/demo/web/UrlShortenerController.java b/demo/src/main/java/urlshortener/demo/web/UrlShortenerController.java deleted file mode 100755 index d64ced63..00000000 --- a/demo/src/main/java/urlshortener/demo/web/UrlShortenerController.java +++ /dev/null @@ -1,101 +0,0 @@ -package urlshortener.demo.web; - -import com.google.common.hash.Hashing; -import org.apache.commons.validator.routines.UrlValidator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import urlshortener.demo.domain.Click; -import urlshortener.demo.domain.ShortURL; -import urlshortener.demo.repository.ClickRepository; -import urlshortener.demo.repository.ShortURLRepository; - -import javax.servlet.http.HttpServletRequest; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.sql.Date; -import java.util.UUID; - -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; - -@RestController -public class UrlShortenerController { - private static final Logger LOG = LoggerFactory - .getLogger(UrlShortenerController.class); - @Autowired - protected ShortURLRepository shortURLRepository; - - @Autowired - protected ClickRepository clickRepository; - - @RequestMapping(value = "/{id:(?!link|index).*}", method = RequestMethod.GET) - public ResponseEntity redirectTo(@PathVariable String id, - HttpServletRequest request) { - ShortURL l = shortURLRepository.findByKey(id); - if (l != null) { - createAndSaveClick(id, extractIP(request)); - return createSuccessfulRedirectToResponse(l); - } else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - } - - private void createAndSaveClick(String hash, String ip) { - Click cl = new Click().hash(hash).created(new Date(System.currentTimeMillis())).ip(ip); - cl=clickRepository.save(cl); - LOG.info(cl!=null?"["+hash+"] saved with id ["+cl.getId()+"]":"["+hash+"] was not saved"); - } - - private String extractIP(HttpServletRequest request) { - return request.getRemoteAddr(); - } - - private ResponseEntity createSuccessfulRedirectToResponse(ShortURL l) { - HttpHeaders h = new HttpHeaders(); - h.setLocation(URI.create(l.getTarget())); - return new ResponseEntity<>(h, HttpStatus.valueOf(l.getMode())); - } - - @RequestMapping(value = "/link", method = RequestMethod.POST) - public ResponseEntity shortener(@RequestParam("url") String url, - @RequestParam(value = "sponsor", required = false) String sponsor, - HttpServletRequest request) { - ShortURL su = createAndSaveIfValid(url, sponsor, UUID - .randomUUID().toString(), extractIP(request)); - if (su != null) { - HttpHeaders h = new HttpHeaders(); - h.setLocation(su.getUri()); - return new ResponseEntity<>(su, h, HttpStatus.CREATED); - } else { - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); - } - } - - private ShortURL createAndSaveIfValid(String url, String sponsor, - String owner, String ip) { - UrlValidator urlValidator = new UrlValidator(new String[] { "http", - "https" }); - if (urlValidator.isValid(url)) { - String id = Hashing.murmur3_32() - .hashString(url, StandardCharsets.UTF_8).toString(); - ShortURL su = new ShortURL().hash(id).target(url) - .uri(linkTo( - methodOn(UrlShortenerController.class).redirectTo( - id, null)).toUri()) - .sponsor(sponsor) - .created(new Date(System.currentTimeMillis())) - .owner(owner) - .mode(HttpStatus.TEMPORARY_REDIRECT.value()) - .safe(true) - .ip(ip); - return shortURLRepository.save(su); - } else { - return null; - } - } -} diff --git a/demo/src/test/java/urlshortener/demo/repository/ClickRepositoryTests.java b/demo/src/test/java/urlshortener/demo/repository/ClickRepositoryTests.java deleted file mode 100644 index 277bd301..00000000 --- a/demo/src/test/java/urlshortener/demo/repository/ClickRepositoryTests.java +++ /dev/null @@ -1,85 +0,0 @@ -package urlshortener.demo.repository; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import urlshortener.demo.domain.Click; -import urlshortener.demo.repository.fixture.ClickFixture; -import urlshortener.demo.repository.fixture.ShortURLFixture; - -import static org.junit.Assert.*; -import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.HSQL; - -public class ClickRepositoryTests { - - private EmbeddedDatabase db; - private ClickRepository repository; - private JdbcTemplate jdbc; - - @Before - public void setup() { - db = new EmbeddedDatabaseBuilder().setType(HSQL) - .addScript("schema-hsqldb.sql").build(); - jdbc = new JdbcTemplate(db); - ShortURLRepository shortUrlRepository = new ShortURLRepositoryImpl(jdbc); - shortUrlRepository.save(ShortURLFixture.url1()); - shortUrlRepository.save(ShortURLFixture.url2()); - repository = new ClickRepositoryImpl(jdbc); - } - - @Test - public void thatSavePersistsTheClickURL() { - Click click = repository.save(ClickFixture.click(ShortURLFixture.url1())); - assertSame(jdbc.queryForObject("select count(*) from CLICK", - Integer.class), 1); - assertNotNull(click); - assertNotNull(click.getId()); - } - - @Test - public void thatErrorsInSaveReturnsNull() { - assertNull(repository.save(ClickFixture.click(ShortURLFixture.badUrl()))); - assertSame(jdbc.queryForObject("select count(*) from CLICK", - Integer.class), 0); - } - - @Test - public void thatFindByKeyReturnsAURL() { - repository.save(ClickFixture.click(ShortURLFixture.url1())); - repository.save(ClickFixture.click(ShortURLFixture.url2())); - repository.save(ClickFixture.click(ShortURLFixture.url1())); - repository.save(ClickFixture.click(ShortURLFixture.url2())); - repository.save(ClickFixture.click(ShortURLFixture.url1())); - assertEquals(repository.findByHash(ShortURLFixture.url1().getHash()).size(), 3); - assertEquals(repository.findByHash(ShortURLFixture.url2().getHash()).size(), 2); - } - - @Test - public void thatFindByKeyReturnsEmpty() { - repository.save(ClickFixture.click(ShortURLFixture.url1())); - repository.save(ClickFixture.click(ShortURLFixture.url2())); - repository.save(ClickFixture.click(ShortURLFixture.url1())); - repository.save(ClickFixture.click(ShortURLFixture.url2())); - repository.save(ClickFixture.click(ShortURLFixture.url1())); - assertEquals(repository.findByHash(ShortURLFixture.badUrl().getHash()).size(), 0); - } - - @Test - public void thatDeleteDelete() { - Long id1 = repository.save(ClickFixture.click(ShortURLFixture.url1())).getId(); - Long id2 = repository.save(ClickFixture.click(ShortURLFixture.url2())).getId(); - repository.delete(id1); - assertEquals(repository.count().intValue(), 1); - repository.delete(id2); - assertEquals(repository.count().intValue(), 0); - } - - @After - public void shutdown() { - db.shutdown(); - } - -} diff --git a/demo/src/test/java/urlshortener/demo/repository/ShortURLRepositoryTests.java b/demo/src/test/java/urlshortener/demo/repository/ShortURLRepositoryTests.java deleted file mode 100644 index 08bdd82e..00000000 --- a/demo/src/test/java/urlshortener/demo/repository/ShortURLRepositoryTests.java +++ /dev/null @@ -1,129 +0,0 @@ -package urlshortener.demo.repository; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import urlshortener.demo.domain.ShortURL; - -import java.util.List; - -import static org.junit.Assert.*; -import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.HSQL; -import static urlshortener.demo.repository.fixture.ShortURLFixture.*; - -public class ShortURLRepositoryTests { - - private EmbeddedDatabase db; - private ShortURLRepository repository; - private JdbcTemplate jdbc; - - @Before - public void setup() { - db = new EmbeddedDatabaseBuilder().setType(HSQL) - .addScript("schema-hsqldb.sql").build(); - jdbc = new JdbcTemplate(db); - repository = new ShortURLRepositoryImpl(jdbc); - } - - @Test - public void thatSavePersistsTheShortURL() { - assertNotNull(repository.save(url1())); - assertSame(jdbc.queryForObject("select count(*) from SHORTURL", - Integer.class), 1); - } - - @Test - public void thatSaveSponsor() { - assertNotNull(repository.save(urlSponsor())); - assertSame(jdbc.queryForObject("select sponsor from SHORTURL", - String.class), urlSponsor().getSponsor()); - } - - @Test - public void thatSaveSafe() { - assertNotNull(repository.save(urlSafe())); - assertSame( - jdbc.queryForObject("select safe from SHORTURL", Boolean.class), - true); - repository.mark(urlSafe(), false); - assertSame( - jdbc.queryForObject("select safe from SHORTURL", Boolean.class), - false); - repository.mark(urlSafe(), true); - assertSame( - jdbc.queryForObject("select safe from SHORTURL", Boolean.class), - true); - } - - @Test - public void thatSaveADuplicateHashIsSafelyIgnored() { - repository.save(url1()); - assertNotNull(repository.save(url1())); - assertSame(jdbc.queryForObject("select count(*) from SHORTURL", - Integer.class), 1); - } - - @Test - public void thatErrorsInSaveReturnsNull() { - assertNull(repository.save(badUrl())); - assertSame(jdbc.queryForObject("select count(*) from SHORTURL", - Integer.class), 0); - } - - @Test - public void thatFindByKeyReturnsAURL() { - repository.save(url1()); - repository.save(url2()); - ShortURL su = repository.findByKey(url1().getHash()); - assertNotNull(su); - assertSame(su.getHash(), url1().getHash()); - } - - @Test - public void thatFindByKeyReturnsNullWhenFails() { - repository.save(url1()); - assertNull(repository.findByKey(url2().getHash())); - } - - @Test - public void thatFindByTargetReturnsURLs() { - repository.save(url1()); - repository.save(url2()); - repository.save(url3()); - List sul = repository.findByTarget(url1().getTarget()); - assertEquals(sul.size(), 2); - sul = repository.findByTarget(url3().getTarget()); - assertEquals(sul.size(), 1); - sul = repository.findByTarget("dummy"); - assertEquals(sul.size(), 0); - } - - @Test - public void thatDeleteDelete() { - repository.save(url1()); - repository.save(url2()); - repository.delete(url1().getHash()); - assertEquals(repository.count().intValue(), 1); - repository.delete(url2().getHash()); - assertEquals(repository.count().intValue(), 0); - } - - @Test - public void thatUpdateUpdate() { - repository.save(url1()); - ShortURL su = repository.findByKey(url1().getHash()); - assertEquals(su.getTarget(), "http://www.unizar.es/"); - repository.update(url1modified()); - su = repository.findByKey(url1().getHash()); - assertEquals(su.getTarget(), "http://www.unizar.org/"); - } - - @After - public void shutdown() { - db.shutdown(); - } - -} diff --git a/demo/src/test/java/urlshortener/demo/repository/fixture/ClickFixture.java b/demo/src/test/java/urlshortener/demo/repository/fixture/ClickFixture.java deleted file mode 100644 index ad20eef1..00000000 --- a/demo/src/test/java/urlshortener/demo/repository/fixture/ClickFixture.java +++ /dev/null @@ -1,11 +0,0 @@ -package urlshortener.demo.repository.fixture; - -import urlshortener.demo.domain.Click; -import urlshortener.demo.domain.ShortURL; - -public class ClickFixture { - - public static Click click(ShortURL su) { - return new Click().hash(su.getHash()); - } -} diff --git a/demo/src/test/java/urlshortener/demo/repository/fixture/ShortURLFixture.java b/demo/src/test/java/urlshortener/demo/repository/fixture/ShortURLFixture.java deleted file mode 100644 index fd1ab01f..00000000 --- a/demo/src/test/java/urlshortener/demo/repository/fixture/ShortURLFixture.java +++ /dev/null @@ -1,34 +0,0 @@ -package urlshortener.demo.repository.fixture; - -import urlshortener.demo.domain.ShortURL; - -public class ShortURLFixture { - - public static ShortURL url1() { - return new ShortURL().hash("1").target("http://www.unizar.es/").safe(false); - } - - public static ShortURL url1modified() { - return new ShortURL().hash("1").target("http://www.unizar.org/").safe(false); - } - - public static ShortURL url2() { - return new ShortURL().hash("2").target("http://www.unizar.es/").safe(false); - } - - public static ShortURL url3() { - return new ShortURL().hash("3").target("http://www.google.es").safe(false); - } - - public static ShortURL badUrl() { - return new ShortURL(); - } - - public static ShortURL urlSponsor() { - return new ShortURL().hash("3").sponsor("sponsor").safe(false); - } - - public static ShortURL urlSafe() { - return new ShortURL().hash("4").sponsor("sponsor").safe(true); - } -} diff --git a/demo/src/test/java/urlshortener/demo/web/UrlShortenerTests.java b/demo/src/test/java/urlshortener/demo/web/UrlShortenerTests.java deleted file mode 100644 index d1c53184..00000000 --- a/demo/src/test/java/urlshortener/demo/web/UrlShortenerTests.java +++ /dev/null @@ -1,115 +0,0 @@ -package urlshortener.demo.web; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import urlshortener.demo.domain.ShortURL; -import urlshortener.demo.repository.ClickRepository; -import urlshortener.demo.repository.ShortURLRepository; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -import static urlshortener.demo.web.fixture.ShortURLFixture.someUrl; - -public class UrlShortenerTests { - - private MockMvc mockMvc; - - @Mock - private ClickRepository clickRepository; - - @Mock - private ShortURLRepository shortURLRepository; - - @InjectMocks - private UrlShortenerController urlShortener; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - this.mockMvc = MockMvcBuilders.standaloneSetup(urlShortener).build(); - } - - @Test - public void thatRedirectToReturnsTemporaryRedirectIfKeyExists() - throws Exception { - when(shortURLRepository.findByKey("someKey")).thenReturn(someUrl()); - when(clickRepository.save(any())).thenAnswer((InvocationOnMock invocation) -> invocation.getArguments()[0]); - - mockMvc.perform(get("/{id}", "someKey")).andDo(print()) - .andExpect(status().isTemporaryRedirect()) - .andExpect(redirectedUrl("http://example.com/")); - } - - @Test - public void thatRedirecToReturnsNotFoundIdIfKeyDoesNotExist() - throws Exception { - when(shortURLRepository.findByKey("someKey")).thenReturn(null); - - mockMvc.perform(get("/{id}", "someKey")).andDo(print()) - .andExpect(status().isNotFound()); - } - - @Test - public void thatShortenerCreatesARedirectIfTheURLisOK() throws Exception { - configureTransparentSave(); - - mockMvc.perform(post("/link").param("url", "http://example.com/")) - .andDo(print()) - .andExpect(redirectedUrl("http://localhost/f684a3c4")) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.hash", is("f684a3c4"))) - .andExpect(jsonPath("$.uri", is("http://localhost/f684a3c4"))) - .andExpect(jsonPath("$.target", is("http://example.com/"))) - .andExpect(jsonPath("$.sponsor", is(nullValue()))); - } - - @Test - public void thatShortenerCreatesARedirectWithSponsor() throws Exception { - configureTransparentSave(); - - mockMvc.perform( - post("/link").param("url", "http://example.com/").param( - "sponsor", "http://sponsor.com/")).andDo(print()) - .andExpect(redirectedUrl("http://localhost/f684a3c4")) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.hash", is("f684a3c4"))) - .andExpect(jsonPath("$.uri", is("http://localhost/f684a3c4"))) - .andExpect(jsonPath("$.target", is("http://example.com/"))) - .andExpect(jsonPath("$.sponsor", is("http://sponsor.com/"))); - } - - @Test - public void thatShortenerFailsIfTheURLisWrong() throws Exception { - configureTransparentSave(); - - mockMvc.perform(post("/link").param("url", "someKey")).andDo(print()) - .andExpect(status().isBadRequest()); - } - - @Test - public void thatShortenerFailsIfTheRepositoryReturnsNull() throws Exception { - when(shortURLRepository.save(any(ShortURL.class))) - .thenReturn(null); - - mockMvc.perform(post("/link").param("url", "someKey")).andDo(print()) - .andExpect(status().isBadRequest()); - } - - private void configureTransparentSave() { - when(shortURLRepository.save(any(ShortURL.class))) - .then((Answer) invocation -> (ShortURL) invocation.getArguments()[0]); - } -} diff --git a/demo/src/test/java/urlshortener/demo/web/fixture/ShortURLFixture.java b/demo/src/test/java/urlshortener/demo/web/fixture/ShortURLFixture.java deleted file mode 100644 index 3c6b1570..00000000 --- a/demo/src/test/java/urlshortener/demo/web/fixture/ShortURLFixture.java +++ /dev/null @@ -1,10 +0,0 @@ -package urlshortener.demo.web.fixture; - -import urlshortener.demo.domain.ShortURL; - -public class ShortURLFixture { - - public static ShortURL someUrl() { - return new ShortURL().hash("someKey").target("http://example.com/").mode(307).safe(true); - } -} From c206f8159f6cb1388d33fc90da8ac45f401b3b83 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:36:03 +0100 Subject: [PATCH 068/125] Cleanup code --- .../urlshortener/demo/config/HomeController.java | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 demo/src/main/java/urlshortener/demo/config/HomeController.java diff --git a/demo/src/main/java/urlshortener/demo/config/HomeController.java b/demo/src/main/java/urlshortener/demo/config/HomeController.java deleted file mode 100644 index 4b6bbd5b..00000000 --- a/demo/src/main/java/urlshortener/demo/config/HomeController.java +++ /dev/null @@ -1,15 +0,0 @@ -package urlshortener.demo.config; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * Home redirection to swagger api documentation - */ -@Controller -public class HomeController { - @RequestMapping(value = "/swagger") - public String index() { - return "redirect:swagger-ui.html"; - } -} From d15118898740cd83419f38f17fcc08c187b89cfd Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:42:31 +0100 Subject: [PATCH 069/125] Create URIItem tests --- .../urlshortener/demo/domain/URIItemTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/domain/URIItemTest.java diff --git a/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java b/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java new file mode 100644 index 00000000..5b714247 --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java @@ -0,0 +1,53 @@ +package urlshortener.demo.domain; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class URIItemTest { + @Test + public void testURIItemID(){ + URIItem base = new URIItem().id("abc"); + + assertEquals("abc", base.getId()); + base.setId("abcd"); + assertEquals("abcd", base.getId()); + } + + @Test + public void testURIItemRedirection(){ + URIItem base = new URIItem().redirection("abc"); + + assertEquals("abc", base.getRedirection()); + base.setRedirection("abcd"); + assertEquals("abcd", base.getRedirection()); + } + + @Test + public void testURIItemEquals(){ + URIItem base = new URIItem().id("abc"); + URIItem base2 = new URIItem().id("abc"); + URIItem base3 = new URIItem().id("abcd"); + + assertEquals(base, base); + assertNotEquals(base, null); + assertNotEquals(base, "abc"); + assertEquals(base, base2); + assertNotEquals(base, base3); + } + + @Test + public void testURIItemCheckHashcode(){ + URIItem base = new URIItem().id("abc"); + + assertEquals(92625985, base.hashCode()); + } + + @Test + public void testURIItemCheckToString(){ + URIItem base = new URIItem().id("abc"); + + assertEquals("class URIItem {\n id: abc\n redirection: null\n hashpass: null\n}", base.toString()); + } +} From 6b6726da5b7dd125ef1f087f50821db48a5aee5e Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 16:54:16 +0100 Subject: [PATCH 070/125] Update URIItem tests --- demo/src/test/java/urlshortener/demo/domain/URIItemTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java b/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java index 5b714247..17f773c0 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java +++ b/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java @@ -29,12 +29,14 @@ public void testURIItemEquals(){ URIItem base = new URIItem().id("abc"); URIItem base2 = new URIItem().id("abc"); URIItem base3 = new URIItem().id("abcd"); + URIItem base4 = new URIItem().id("abc").redirection("abcd"); assertEquals(base, base); assertNotEquals(base, null); assertNotEquals(base, "abc"); assertEquals(base, base2); assertNotEquals(base, base3); + assertNotEquals(base, base4); } @Test From a61b64a1c8e78fd102501a3208765483305b71ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Fern=C3=A1ndez=20Melic?= Date: Wed, 12 Dec 2018 17:19:37 +0100 Subject: [PATCH 071/125] QR feature finished and tests added --- .../demo/controller/impl/QrApiController.java | 12 ++++-- .../controller/impl/UriApiController.java | 24 +++++++++-- .../java/urlshortener/demo/web/QrTests.java | 41 +++++++++++++++---- .../java/urlshortener/demo/web/UriTests.java | 4 ++ 4 files changed, 68 insertions(+), 13 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java index 16dc592a..e903a6d2 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java @@ -53,14 +53,20 @@ public ResponseEntity getQR(@ApiParam(value = "",required=true) @PathVar // and return int int w = StringChecker.checkString2Int(width); int h = StringChecker.checkString2Int(height); + + // If uri is not in the URIRepository return 404 + if (!this.uriRepository.contains(id)){ + return new ResponseEntity(HttpStatus.NOT_FOUND); + } // Default qr is required, so it's saved if the uri is shorthed - if(w==500 && h==500){ - qr = this.qrRepository.get(id); + if(w==500 && h==500){ + URIItem uriItem = this.uriRepository.get(id); + qr = this.qrRepository.get(uriItem.getRedirection()); }else{ URIItem uriItem = this.uriRepository.get(id); qr = new QRItem(); - qr.setUri(uriItem.getId()); + qr.setUri(uriItem.getRedirection()); qr.convertBase64(w, h); } diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index fc7f7ee8..53178158 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -12,10 +12,12 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import urlshortener.demo.controller.UriApi; +import urlshortener.demo.domain.QRItem; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; import urlshortener.demo.exception.IncorrectHashPassException; import urlshortener.demo.exception.UnknownEntityException; +import urlshortener.demo.repository.QRRepository; import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.ParameterUtils; import urlshortener.demo.utils.StringUtils; @@ -30,12 +32,15 @@ @Controller public class UriApiController implements UriApi { - //Limit to K redirections in one hour + // Limit to K redirections in one hour private static final long MAX_REDIRECTION_TIME = 3600000L; - //Limit to 100 redirections in X ms. + // Limit to 100 redirections in X ms. private static final long MAX_REDIRECTIONS = 100; + // Default size of QR code + private static final int QR_SIZE = 500; + private static final Logger log = LoggerFactory.getLogger(UriApiController.class); private final ObjectMapper objectMapper; @@ -43,12 +48,15 @@ public class UriApiController implements UriApi { private final HttpServletRequest request; private final URIRepository uriService; + + private final QRRepository qrService; @org.springframework.beans.factory.annotation.Autowired - public UriApiController(ObjectMapper objectMapper, HttpServletRequest request, URIRepository uriService) { + public UriApiController(ObjectMapper objectMapper, HttpServletRequest request, URIRepository uriService, QRRepository qrService) { this.objectMapper = objectMapper; this.request = request; this.uriService = uriService; + this.qrService = qrService; } public ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URICreate body,@ApiParam(value = "",required=true) @PathVariable("name") String name) { @@ -58,6 +66,16 @@ public ResponseEntity changeURI(@ApiParam(value = "Optional description URIItem item = (URIItem) new URIItem().id(name).redirection(body.getUri()).hashpass(StringUtils.randomHash()); uriService.add(item); + + // Save default QR to QRRepository if it doesn't already exist + if(!qrService.contains(body.getUri())){ + QRItem qrItem = new QRItem(); + qrItem.setUri(body.getUri()); + qrItem.convertBase64(QR_SIZE, QR_SIZE); + + this.qrService.add(qrItem); + } + return new ResponseEntity(item, HttpStatus.CREATED); } diff --git a/demo/src/test/java/urlshortener/demo/web/QrTests.java b/demo/src/test/java/urlshortener/demo/web/QrTests.java index 553869c5..8369fcd1 100644 --- a/demo/src/test/java/urlshortener/demo/web/QrTests.java +++ b/demo/src/test/java/urlshortener/demo/web/QrTests.java @@ -1,6 +1,7 @@ package urlshortener.demo.web; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.util.JSONPObject; import com.jayway.jsonpath.JsonPath; import org.hamcrest.core.IsNot; @@ -12,12 +13,25 @@ import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import net.minidev.json.JSONObject; +import net.minidev.json.parser.JSONParser; import urlshortener.demo.controller.impl.QrApiController; +import urlshortener.demo.controller.impl.UriApiController; +import urlshortener.demo.domain.QRItem; +import urlshortener.demo.domain.URICreate; +import urlshortener.demo.domain.URIItem; +import urlshortener.demo.web.MockUtils; +import urlshortener.demo.repository.QRRepository; +import urlshortener.demo.repository.URIRepository; +import urlshortener.demo.controller.advice.BaseControllerAdvice; import javax.servlet.http.HttpServletRequest; import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -34,29 +48,42 @@ public class QrTests { @Mock private HttpServletRequest request; + @Mock + private URIRepository uriRepository; + + @Mock + private QRRepository qrRepository; + @InjectMocks private QrApiController qrApiController; @Before public void setup() { MockitoAnnotations.initMocks(this); - this.mockMvc = MockMvcBuilders.standaloneSetup(qrApiController).build(); + this.mockMvc = MockMvcBuilders.standaloneSetup(qrApiController) + .setControllerAdvice(new BaseControllerAdvice()).build(); } @Test public void uriGetWorks() throws Exception { - mockMvc.perform(get("/qr/{id}/", "www.google.es")) + URIItem uriItem = new URIItem().id("googleHash").redirection("www.google.es"); + QRItem qrItem = new QRItem().uri(uriItem.getRedirection()); + qrItem.convertBase64(500, 500); + + when(uriRepository.get("googleHash")).thenReturn(uriItem); + when(uriRepository.contains("googleHash")).thenReturn(true); + when(qrRepository.get(uriItem.getRedirection())).thenReturn(qrItem); + + mockMvc.perform(get("/qr/{id}/", "googleHash")) .andDo(print()) .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(jsonPath("$.uri", is("www.google.es"))) - .andExpect(jsonPath("$.qr", is("iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AQAAAADjreInAAABg0lEQVR42u3cO3KDMBAAUGVcuOQIOQpHs4/mo/gIlCkyUcb8JAEJJplJEb0tgadyZ3clEeKvogs8z/M8z/M8z/M8z/P83/iPUMQpf9DEt/Jtw/M8X/iUVt4GH+M1tPHe+1N6e+d5nl/565xuTpsLPqLleZ7f90O88jzPH/NFucLzPL/jV+XKJd7m/HO8f+J5vhq/mr/m85OfzG95nq/Db8Xq84P7xzzP1+HHcuVRnQz5p/dT/RLje3jZWJDneb7wTf95yMclxfxkL//wPF+ZH9NNyj/jQOWRf7q8IQpjQuJ5nl/mn5jKlWncGsI5kdtO/cLzfHW+jyG7dPmotR39WNBcvtq/4Xm+cp9Hcf4se9A+Ob/leb4av9r/3Vpwr//heb5Wnx4v7s90U/+Tb+jwPM8vs0txf+bSj0vm/uf78yM8z/Pz/ZnU7iwWbHie55/zQ/2yOz/heb5mv+p/rkfOv/M8X6/fuH83nT87lwdKGp7nef+P5nme53me53me53me/+f+E5W4ETCek3pPAAAAAElFTkSuQmCC"))); + .andExpect(jsonPath("$.qr").value(qrItem.getQr())) + .andExpect(jsonPath("$.uri").value(qrItem.getUri())); } @Test public void uriGetError() throws Exception { - mockMvc.perform(get("/qr/{id}/", "")) - .andDo(print()) + mockMvc.perform(get("/qr/{id}/", "googleHash")) .andExpect(status().isNotFound()); } diff --git a/demo/src/test/java/urlshortener/demo/web/UriTests.java b/demo/src/test/java/urlshortener/demo/web/UriTests.java index 5bdc89b8..29b9fc41 100644 --- a/demo/src/test/java/urlshortener/demo/web/UriTests.java +++ b/demo/src/test/java/urlshortener/demo/web/UriTests.java @@ -15,6 +15,7 @@ import urlshortener.demo.domain.URIItem; import urlshortener.demo.exception.CannotAddEntityException; import urlshortener.demo.repository.URIRepository; +import urlshortener.demo.repository.QRRepository; import javax.servlet.http.HttpServletRequest; @@ -40,6 +41,9 @@ public class UriTests { @Mock private URIRepository service; + @Mock + private QRRepository qrService; + @InjectMocks private UriApiController uriApiController; From 0a826747a27a5c5b8dccf0f942b8f5261cbc67eb Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 21:46:25 +0100 Subject: [PATCH 072/125] Check also URI hashpass --- demo/src/test/java/urlshortener/demo/domain/URIItemTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java b/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java index 17f773c0..c6e0dce6 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java +++ b/demo/src/test/java/urlshortener/demo/domain/URIItemTest.java @@ -30,6 +30,7 @@ public void testURIItemEquals(){ URIItem base2 = new URIItem().id("abc"); URIItem base3 = new URIItem().id("abcd"); URIItem base4 = new URIItem().id("abc").redirection("abcd"); + URIItem base5 = (URIItem) new URIItem().id("abc").hashpass("abcd"); assertEquals(base, base); assertNotEquals(base, null); @@ -37,6 +38,7 @@ public void testURIItemEquals(){ assertEquals(base, base2); assertNotEquals(base, base3); assertNotEquals(base, base4); + assertNotEquals(base, base5); } @Test From 6ee22b08a9a0e5e54636ef5d7fbd6946a23351b2 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 21:53:01 +0100 Subject: [PATCH 073/125] Add URIUpdate tests --- .../demo/domain/URIUpdateTests.java | 44 ++++++++++++++----- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java index e2a2fea6..06af78ee 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java +++ b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java @@ -4,25 +4,47 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; public class URIUpdateTests { @Test - public void testOK(){ - URIUpdate uriUpdate1 = new URIUpdate(); - URIUpdate uriUpdate2 = uriUpdate1.newName("abc"); - URIUpdate uriUpdate3 = (URIUpdate) uriUpdate2.hashpass("abcd"); - - assertEquals(uriUpdate3, uriUpdate1); - assertEquals(uriUpdate3, uriUpdate2); - assertEquals("abc", uriUpdate1.getNewName()); - assertEquals("abcd", uriUpdate1.getHashpass()); + public void testNewName(){ + URIUpdate base = new URIUpdate().newName("abc"); + + assertEquals("abc", base.getNewName()); + base.setNewName("abcd"); + assertEquals("abcd", base.getNewName()); + } + + @Test + public void testHashpass(){ + URIUpdate base = (URIUpdate) new URIUpdate().hashpass("abc"); + + assertEquals("abc", base.getHashpass()); + base.setHashpass("abcd"); + assertEquals("abcd", base.getHashpass()); + } + + @Test + public void testURIUpdateEquals(){ + URIUpdate base = new URIUpdate().newName("abc"); + URIUpdate base2 = new URIUpdate().newName("abc"); + URIUpdate base3 = new URIUpdate().newName("abcd"); + URIUpdate base4 = (URIUpdate) new URIUpdate().newName("abc").hashpass("abcd"); + + assertEquals(base, base); + assertNotEquals(base, null); + assertNotEquals(base, "abc"); + assertEquals(base, base2); + assertNotEquals(base, base3); + assertNotEquals(base, base4); } @Test public void testToString(){ - URIUpdate uriUpdate1 = (URIUpdate) new URIUpdate().newName("abc").hashpass("abcd"); - assertEquals("class URIUpdate {\n newName: abc\n hashpass: abcd\n}", uriUpdate1.toString()); + URIUpdate uriUpdate1 = new URIUpdate().newName("abc"); + assertEquals("class URIUpdate {\n newName: abc\n hashpass: null\n}", uriUpdate1.toString()); } } From 7987d07f0293c916dc45449b9fddb40d1c490109 Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 22:00:38 +0100 Subject: [PATCH 074/125] Add URIUpdate hashcode test and deactivate 2 tests we are not using now --- demo/src/test/java/urlshortener/demo/SystemTests.java | 5 +++++ .../test/java/urlshortener/demo/domain/URIUpdateTests.java | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/demo/src/test/java/urlshortener/demo/SystemTests.java b/demo/src/test/java/urlshortener/demo/SystemTests.java index 10e29f53..4dbf7455 100755 --- a/demo/src/test/java/urlshortener/demo/SystemTests.java +++ b/demo/src/test/java/urlshortener/demo/SystemTests.java @@ -3,6 +3,7 @@ import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.ReadContext; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -55,7 +56,9 @@ public void testCss() { } @Test + @Ignore public void testCreateLink() throws Exception { + //TODO Reactivate before technical review!! ResponseEntity entity = postLink("http://example.com/"); assertThat(entity.getStatusCode(), is(HttpStatus.CREATED)); @@ -69,7 +72,9 @@ public void testCreateLink() throws Exception { } @Test + @Ignore public void testRedirection() throws Exception { + //TODO Reactivate before technical review postLink("http://example.com/"); ResponseEntity entity = restTemplate.getForEntity( "/f684a3c4", String.class); diff --git a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java index 06af78ee..da7b3221 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java +++ b/demo/src/test/java/urlshortener/demo/domain/URIUpdateTests.java @@ -47,4 +47,10 @@ public void testToString(){ assertEquals("class URIUpdate {\n newName: abc\n hashpass: null\n}", uriUpdate1.toString()); } + @Test + public void testHashCode(){ + URIUpdate uriUpdate1 = new URIUpdate().newName("abc"); + assertEquals(2987935, uriUpdate1.hashCode()); + } + } From 17eb874083c2c3b732838744b2ce6a4c4a658ead Mon Sep 17 00:00:00 2001 From: lAngel Date: Wed, 12 Dec 2018 22:36:34 +0100 Subject: [PATCH 075/125] Test Exceptions --- .../demo/exceptions/ExceptionTest.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/exceptions/ExceptionTest.java diff --git a/demo/src/test/java/urlshortener/demo/exceptions/ExceptionTest.java b/demo/src/test/java/urlshortener/demo/exceptions/ExceptionTest.java new file mode 100644 index 00000000..fd29ea12 --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/exceptions/ExceptionTest.java @@ -0,0 +1,18 @@ +package urlshortener.demo.exceptions; + +import org.junit.Test; +import urlshortener.demo.exception.NotFoundException; + +import static org.junit.Assert.assertEquals; + +public class ExceptionTest { + + @Test + public void testNotFoundException(){ + String MSG = "Test message"; + NotFoundException ex = new NotFoundException(100, MSG); + + assertEquals(MSG, ex.getMessage()); + } + +} From 1d90981ab2660b058d4a049f527f73ac0653966a Mon Sep 17 00:00:00 2001 From: lAngel Date: Thu, 13 Dec 2018 08:27:56 +0100 Subject: [PATCH 076/125] Add URICreate tests --- .../demo/domain/URICreateTest.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/domain/URICreateTest.java diff --git a/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java b/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java new file mode 100644 index 00000000..2c381a5c --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java @@ -0,0 +1,46 @@ +package urlshortener.demo.domain; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class URICreateTest { + + @Test + public void testURICreateUri(){ + URICreate base = new URICreate().uri("abc"); + + assertEquals("abc", base.getUri()); + base.setUri("abcd"); + assertEquals("abcd", base.getUri()); + } + + @Test + public void testURICreateEquals(){ + URICreate base = new URICreate().uri("abc"); + URICreate base2 = new URICreate().uri("abc"); + URICreate base3 = new URICreate().uri("abcd"); + + assertEquals(base, base); + assertNotEquals(base, null); + assertNotEquals(base, "abc"); + assertEquals(base, base2); + assertNotEquals(base, base3); + } + + @Test + public void testURICreateCheckHashcode(){ + URICreate base = new URICreate().uri("abc"); + + assertEquals(96385, base.hashCode()); + } + + @Test + public void testURICreateCheckToString(){ + URICreate base = new URICreate().uri("abc"); + + assertEquals("class URICreate {\n uri: abc\n}", base.toString()); + } + +} From 1b89bc5a3dde64861f4a72552d1f34939cd3bfcd Mon Sep 17 00:00:00 2001 From: lAngel Date: Thu, 13 Dec 2018 08:43:07 +0100 Subject: [PATCH 077/125] Add ApiResponseMessage tests --- .../demo/utils/ApiResponseMessageTest.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/utils/ApiResponseMessageTest.java diff --git a/demo/src/test/java/urlshortener/demo/utils/ApiResponseMessageTest.java b/demo/src/test/java/urlshortener/demo/utils/ApiResponseMessageTest.java new file mode 100644 index 00000000..d6fb9526 --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/utils/ApiResponseMessageTest.java @@ -0,0 +1,59 @@ +package urlshortener.demo.utils; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class ApiResponseMessageTest { + + private ApiResponseMessage responseEmpty, responseError, responseWarn, responseInfo, responseOK, responseBusy; + + @Before + public void init(){ + responseEmpty = new ApiResponseMessage(); + responseError = new ApiResponseMessage(ApiResponseMessage.ERROR, "ERROR"); + responseWarn = new ApiResponseMessage(ApiResponseMessage.WARNING, "WARN"); + responseInfo = new ApiResponseMessage(ApiResponseMessage.INFO, "INFO"); + responseOK = new ApiResponseMessage(ApiResponseMessage.OK, "OK"); + responseBusy = new ApiResponseMessage(ApiResponseMessage.TOO_BUSY, "BUSY"); + } + + @Test + public void testCodeAndMessage(){ + assertEquals(0, responseEmpty.getCode()); + assertEquals(ApiResponseMessage.ERROR, responseError.getCode()); + assertEquals(ApiResponseMessage.WARNING, responseWarn.getCode()); + assertEquals(ApiResponseMessage.INFO, responseInfo.getCode()); + assertEquals(ApiResponseMessage.OK, responseOK.getCode()); + assertEquals(ApiResponseMessage.TOO_BUSY, responseBusy.getCode()); + + assertEquals("ERROR", responseError.getMessage()); + } + + @Test + public void testType(){ + assertNull(responseEmpty.getType()); + assertEquals("error", responseError.getType()); + assertEquals("warning", responseWarn.getType()); + assertEquals("info", responseInfo.getType()); + assertEquals("ok", responseOK.getType()); + assertEquals("too busy", responseBusy.getType()); + assertEquals("unknown", new ApiResponseMessage(-1, "ABC").getType()); + + assertEquals("ERROR", responseError.getMessage()); + + } + + @Test + public void testSetters(){ + responseEmpty.setCode(responseError.getCode()); + responseEmpty.setMessage(responseError.getMessage()); + responseEmpty.setType(responseError.getType()); + + assertEquals(responseError.getCode(), responseEmpty.getCode()); + assertEquals(responseError.getMessage(), responseEmpty.getMessage()); + assertEquals(responseError.getType(), responseEmpty.getType()); + } +} From 35b3d6459f4330a827dc6e2be44e1ff50435df88 Mon Sep 17 00:00:00 2001 From: lAngel Date: Thu, 13 Dec 2018 08:44:53 +0100 Subject: [PATCH 078/125] Improve toString() test --- .../test/java/urlshortener/demo/domain/URICreateTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java b/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java index 2c381a5c..4a10ef9a 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java +++ b/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java @@ -39,8 +39,11 @@ public void testURICreateCheckHashcode(){ @Test public void testURICreateCheckToString(){ URICreate base = new URICreate().uri("abc"); - assertEquals("class URICreate {\n uri: abc\n}", base.toString()); + + base = new URICreate().uri("null"); + assertEquals("class URICreate {\n uri: null\n}", base.toString()); + } } From 19f04211b1588a6e7ab89c13ef27a7454241a940 Mon Sep 17 00:00:00 2001 From: lAngel Date: Thu, 13 Dec 2018 08:51:17 +0100 Subject: [PATCH 079/125] Improve toString() test (now it's really improved) --- demo/src/test/java/urlshortener/demo/domain/URICreateTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java b/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java index 4a10ef9a..f1539e1a 100644 --- a/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java +++ b/demo/src/test/java/urlshortener/demo/domain/URICreateTest.java @@ -41,7 +41,7 @@ public void testURICreateCheckToString(){ URICreate base = new URICreate().uri("abc"); assertEquals("class URICreate {\n uri: abc\n}", base.toString()); - base = new URICreate().uri("null"); + base = new URICreate().uri(null); assertEquals("class URICreate {\n uri: null\n}", base.toString()); } From e94b0959baef8d9415be6330986aedd69a71eada Mon Sep 17 00:00:00 2001 From: lAngel Date: Thu, 13 Dec 2018 15:13:14 +0100 Subject: [PATCH 080/125] Add ErrorItem tests --- .../demo/domain/ErrorItemTest.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 demo/src/test/java/urlshortener/demo/domain/ErrorItemTest.java diff --git a/demo/src/test/java/urlshortener/demo/domain/ErrorItemTest.java b/demo/src/test/java/urlshortener/demo/domain/ErrorItemTest.java new file mode 100644 index 00000000..41e4a04b --- /dev/null +++ b/demo/src/test/java/urlshortener/demo/domain/ErrorItemTest.java @@ -0,0 +1,47 @@ +package urlshortener.demo.domain; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class ErrorItemTest { + + @Test + public void testErrorItem(){ + ErrorItem base = new ErrorItem().errorInfo("ABC"); + + assertEquals("ABC", base.getErrorInfo()); + base.setErrorInfo("ABCD"); + assertEquals("ABCD", base.getErrorInfo()); + } + + @Test + public void testErrorItemEquals(){ + ErrorItem base = new ErrorItem().errorInfo("abc"); + ErrorItem base2 = new ErrorItem().errorInfo("abc"); + ErrorItem base3 = new ErrorItem().errorInfo("abcd"); + + assertEquals(base, base); + assertNotEquals(base, null); + assertNotEquals(base, "abc"); + assertEquals(base, base2); + assertNotEquals(base, base3); + } + + @Test + public void testErrorItemHashcode(){ + ErrorItem base = new ErrorItem().errorInfo("abc"); + + assertEquals(96385, base.hashCode()); + } + + @Test + public void testErrorItemToString(){ + ErrorItem base = new ErrorItem().errorInfo("abc"); + ErrorItem base2 = new ErrorItem().errorInfo(null); + assertEquals("class ErrorItem {\n errorInfo: abc\n}", base.toString()); + assertEquals("class ErrorItem {\n errorInfo: null\n}", base2.toString()); + } + +} From 748dccdcc0ca1caae69ecc2377c769926219faab Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Thu, 13 Dec 2018 16:01:03 +0100 Subject: [PATCH 081/125] Merge conflict solved --- .gitignore | 1 + .../urlshortener/demo/controller/impl/UriApiController.java | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8ba30af0..27a84f60 100644 --- a/.gitignore +++ b/.gitignore @@ -25,5 +25,6 @@ team/.settings/org.eclipse.buildship.core.prefs team/.settings/org.eclipse.jdt.core.prefs team/bin/main/urlshortener/team/Application.class .vscode +demo/bin app.properties \ No newline at end of file diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 1c3a03cb..7c2e0cc7 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -18,6 +18,7 @@ import urlshortener.demo.exception.InvalidRequestParametersException; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; +import urlshortener.demo.utils.CheckAlive; import urlshortener.demo.utils.ParameterUtils; import urlshortener.demo.utils.StringUtils; @@ -135,7 +136,7 @@ public ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVari return new ResponseEntity(HttpStatus.NOT_FOUND); } - } catch (URISyntaxException | e) { + } catch (URISyntaxException e) { throw new InvalidRequestParametersException(HttpStatus.BAD_REQUEST.value(), ""); } catch (ProtocolException e) { e.printStackTrace(); From 6aacfa9756666192d74fe96cb4151ceb5391f4b5 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Thu, 13 Dec 2018 16:16:38 +0100 Subject: [PATCH 082/125] Merge conflict conflict solved --- .../demo/controller/impl/UriApiController.java | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 7c2e0cc7..74d79fe9 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -116,13 +116,8 @@ public ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVari throw new UnknownEntityException(1, "Unknown URI: " + id); } - if(uriService.getRedirectionAmount(id, MAX_REDIRECTION_TIME) > MAX_REDIRECTIONS){ - return new ResponseEntity<>(HttpStatus.TOO_MANY_REQUESTS); - } - redirection = item.getRedirection(); - try { if (c.makeRequest(redirection) == 200){ //OK @@ -136,16 +131,15 @@ public ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVari return new ResponseEntity(HttpStatus.NOT_FOUND); } - } catch (URISyntaxException e) { + } catch (URISyntaxException | IOException e) { throw new InvalidRequestParametersException(HttpStatus.BAD_REQUEST.value(), ""); - } catch (ProtocolException e) { - e.printStackTrace(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); } + if(uriService.getRedirectionAmount(id, MAX_REDIRECTION_TIME) > MAX_REDIRECTIONS){ + return new ResponseEntity<>(HttpStatus.TOO_MANY_REQUESTS); + } + + HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(location); From 65827052b4b13a53fe1e6c7bbd9f68a1a099affe Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Thu, 13 Dec 2018 16:28:53 +0100 Subject: [PATCH 083/125] Check test changed --- .../demo/controller/impl/CheckApiController.java | 7 ++----- .../demo/controller/CheckApiControllerIntegrationTest.java | 2 ++ 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 7352acac..15f3e9ba 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.PathVariable; import urlshortener.demo.controller.CheckApi; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.CheckAlive; @@ -49,11 +50,7 @@ public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVa return new ResponseEntity(httpStatus); - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (ProtocolException e) { - e.printStackTrace(); - } catch (IOException e) { + } catch (IOException | UnknownEntityException e) { e.printStackTrace(); } diff --git a/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java index b0175784..1a491873 100644 --- a/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java @@ -54,4 +54,6 @@ public void checkURITest_null_URI_throws_UnknownEntityException() { public void checkURITest_empty_URI_throws_UnknownEntityException() { ResponseEntity responseEntity = api.checkURI(""); } + + } From 23ba398cd2df168842d91273b4df4327df25dfd2 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Thu, 13 Dec 2018 16:34:00 +0100 Subject: [PATCH 084/125] Check test changed --- .../urlshortener/demo/controller/impl/CheckApiController.java | 2 -- .../demo/controller/CheckApiControllerIntegrationTest.java | 2 -- 2 files changed, 4 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 15f3e9ba..5c180c4d 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -16,8 +16,6 @@ import javax.servlet.http.HttpServletRequest; import java.io.IOException; -import java.net.MalformedURLException; -import java.net.ProtocolException; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-21T05:15:43.072Z[GMT]") diff --git a/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java index 1a491873..f2466a4d 100644 --- a/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java @@ -1,7 +1,5 @@ package urlshortener.demo.controller; - -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; From 9ecd84f171de1cc4235b2bc49a775884a3ee508a Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Thu, 13 Dec 2018 17:33:57 +0100 Subject: [PATCH 085/125] Check test changed --- .../demo/controller/impl/CheckApiController.java | 7 +++---- .../java/urlshortener/demo/utils/CheckAlive.java | 4 +++- .../CheckApiControllerIntegrationTest.java | 12 ++++++++++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 5c180c4d..307cefd2 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.PathVariable; import urlshortener.demo.controller.CheckApi; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.exception.InvalidRequestParametersException; import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.CheckAlive; @@ -48,10 +49,8 @@ public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVa return new ResponseEntity(httpStatus); - } catch (IOException | UnknownEntityException e) { - e.printStackTrace(); + } catch (IOException e) { + throw new InvalidRequestParametersException(HttpStatus.BAD_REQUEST.value(), "There was a problem with the parameters."); } - - return new ResponseEntity(HttpStatus.BAD_REQUEST); } } diff --git a/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java b/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java index 982baede..a3020e8d 100644 --- a/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java +++ b/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java @@ -2,10 +2,12 @@ import java.io.IOException; import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; import java.net.URL; public class CheckAlive { - public int makeRequest(String s) throws IOException { + public int makeRequest(String s) throws IOException { URL url = new URL(s); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); diff --git a/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java index f2466a4d..a4e5c150 100644 --- a/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/CheckApiControllerIntegrationTest.java @@ -8,6 +8,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.exception.InvalidRequestParametersException; import urlshortener.demo.repository.URIRepository; import static org.junit.Assert.assertEquals; @@ -53,5 +54,16 @@ public void checkURITest_empty_URI_throws_UnknownEntityException() { ResponseEntity responseEntity = api.checkURI(""); } + @Test(expected = InvalidRequestParametersException.class) + public void checkURITest_invalid_URL(){ + URIItem uri = new URIItem(); + + uri.setId("2"); + uri.setHashpass("1"); + uri.setRedirection("http://localhost:1111"); + repo.add(uri); + + api.checkURI("2"); + } } From 8cb94c549c2c1d341efca06b83a873d0c8664b64 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Thu, 13 Dec 2018 17:41:27 +0100 Subject: [PATCH 086/125] Check test changed --- .../urlshortener/demo/controller/impl/CheckApiController.java | 1 - demo/src/main/java/urlshortener/demo/utils/CheckAlive.java | 2 -- 2 files changed, 3 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 307cefd2..13afec26 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -11,7 +11,6 @@ import urlshortener.demo.controller.CheckApi; import urlshortener.demo.domain.URIItem; import urlshortener.demo.exception.InvalidRequestParametersException; -import urlshortener.demo.exception.UnknownEntityException; import urlshortener.demo.repository.URIRepository; import urlshortener.demo.utils.CheckAlive; diff --git a/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java b/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java index a3020e8d..fe468095 100644 --- a/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java +++ b/demo/src/main/java/urlshortener/demo/utils/CheckAlive.java @@ -2,8 +2,6 @@ import java.io.IOException; import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; import java.net.URL; public class CheckAlive { From 8a9f49114af6b86b9ef8e5b71394093cf2a3dcec Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Fri, 14 Dec 2018 11:44:37 +0100 Subject: [PATCH 087/125] UriApiController has been modified in order to achieve a 100% coverage of the ode with the tests. The main functionality has not been modified, but the file had to be modified due to the check functionality. --- .../demo/controller/impl/UriApiController.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 74d79fe9..7e74be44 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -74,15 +74,9 @@ public ResponseEntity changeURI(@ApiParam(value = "Optional description } else { return new ResponseEntity(HttpStatus.BAD_REQUEST); } - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (ProtocolException e) { - e.printStackTrace(); } catch (IOException e) { - e.printStackTrace(); + throw new InvalidRequestParametersException(HttpStatus.BAD_REQUEST.value(), "There was a problem with the parameters."); } - - return new ResponseEntity(HttpStatus.BAD_REQUEST); } public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body) { From 04721cdee0d2894e34aa7ec09a0a97b558a06e60 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Fri, 14 Dec 2018 11:49:21 +0100 Subject: [PATCH 088/125] UriApiController has been modified in order to achieve a 100% coverage of the ode with the tests. The main functionality has not been modified, but the file had to be modified due to the check functionality. --- .../urlshortener/demo/controller/impl/UriApiController.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 7e74be44..e7870474 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -25,8 +25,6 @@ import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.io.IOException; -import java.net.MalformedURLException; -import java.net.ProtocolException; import java.net.URI; import java.net.URISyntaxException; From 0750a3193cbdb17b10abe30a0e3f45e115b71f30 Mon Sep 17 00:00:00 2001 From: lAngel Date: Fri, 14 Dec 2018 13:29:46 +0100 Subject: [PATCH 089/125] Add Spring boot actuator library --- build.gradle | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build.gradle b/build.gradle index 3c7d4c20..74136210 100644 --- a/build.gradle +++ b/build.gradle @@ -105,6 +105,8 @@ project(':demo') { compile 'org.webjars:bootstrap:3.3.5' compile 'org.webjars:jquery:2.1.4' + // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuator + compile 'org.springframework.boot:spring-boot-starter-actuator' // Testing framework testCompile 'org.springframework.boot:spring-boot-starter-test' From 3010821843f9728320618323f391de3b73817734 Mon Sep 17 00:00:00 2001 From: lAngel Date: Fri, 14 Dec 2018 13:30:05 +0100 Subject: [PATCH 090/125] Retrieve count of items in repository --- .../java/urlshortener/demo/repository/AbstractRepository.java | 4 ++++ .../main/java/urlshortener/demo/repository/IRepository.java | 2 ++ 2 files changed, 6 insertions(+) diff --git a/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java b/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java index 91d2aa3f..2bcc0112 100644 --- a/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java @@ -55,4 +55,8 @@ public boolean contains(K key){ return uris.containsKey(key); } + @Override + public int getCount() { + return uris.size(); + } } diff --git a/demo/src/main/java/urlshortener/demo/repository/IRepository.java b/demo/src/main/java/urlshortener/demo/repository/IRepository.java index 7d622fcc..e65eed7e 100644 --- a/demo/src/main/java/urlshortener/demo/repository/IRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/IRepository.java @@ -15,4 +15,6 @@ public interface IRepository> { long getNextID(); boolean contains(K key); + + int getCount(); } From ce0e62ad3d419ea273e3d9eb29839cb18460daf2 Mon Sep 17 00:00:00 2001 From: lAngel Date: Fri, 14 Dec 2018 13:30:22 +0100 Subject: [PATCH 091/125] Expose all actuator endpoints --- demo/src/main/resources/application.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/demo/src/main/resources/application.properties b/demo/src/main/resources/application.properties index ca4b8b41..0ece12d5 100755 --- a/demo/src/main/resources/application.properties +++ b/demo/src/main/resources/application.properties @@ -4,3 +4,4 @@ spring.datasource.url=jdbc:hsqldb:mem:. spring.datasource.username=sa spring.datasource.password= spring.datasource.driverClassName=org.hsqldb.jdbcDriver +management.endpoints.web.exposure.include=* From 8b01be0f93c93e996ba059b24a23348e70c539bd Mon Sep 17 00:00:00 2001 From: lAngel Date: Fri, 14 Dec 2018 13:30:35 +0100 Subject: [PATCH 092/125] Add more info to /info endpoint --- .../stats/StatsInfoActuatorContributor.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 demo/src/main/java/urlshortener/demo/stats/StatsInfoActuatorContributor.java diff --git a/demo/src/main/java/urlshortener/demo/stats/StatsInfoActuatorContributor.java b/demo/src/main/java/urlshortener/demo/stats/StatsInfoActuatorContributor.java new file mode 100644 index 00000000..c258bc8c --- /dev/null +++ b/demo/src/main/java/urlshortener/demo/stats/StatsInfoActuatorContributor.java @@ -0,0 +1,39 @@ +package urlshortener.demo.stats; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.info.Info; +import org.springframework.boot.actuate.info.InfoContributor; +import org.springframework.stereotype.Component; +import urlshortener.demo.repository.IRepository; +import urlshortener.demo.repository.QRRepository; +import urlshortener.demo.repository.URIRepository; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class StatsInfoActuatorContributor implements InfoContributor { + + private final URIRepository uriRepository; + private final QRRepository qrRepository; + + @Autowired + public StatsInfoActuatorContributor(URIRepository uriRepository, QRRepository qrRepository) { + this.uriRepository = uriRepository; + this.qrRepository = qrRepository; + } + + private Map getStatsFor(IRepository repository){ + Map details = new HashMap<>(); + details.put("amount", repository.getCount()); + //userDetails.put("inactive", uriRepository.countByStatus(0)); + return details; + } + + @Override + public void contribute(Info.Builder builder) { + builder.withDetail("uri", getStatsFor(uriRepository)); + builder.withDetail("qr", getStatsFor(qrRepository)); + } +} + From 3455cb17eee7f92f01a73fde9c0ae3a231e47646 Mon Sep 17 00:00:00 2001 From: lAngel Date: Fri, 14 Dec 2018 13:39:59 +0100 Subject: [PATCH 093/125] Move QrItem tests to its correct location --- .../QrApiControllerIntegrationTest.java | 145 ------------------ .../urlshortener/demo/domain/QRItemTest.java | 145 ++++++++++++++++++ 2 files changed, 145 insertions(+), 145 deletions(-) diff --git a/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java index 22e9668a..6f459a17 100644 --- a/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java @@ -1,14 +1,9 @@ package urlshortener.demo.controller; -import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import urlshortener.demo.domain.QRItem; -import urlshortener.demo.utils.*; - -import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest @@ -18,146 +13,6 @@ public class QrApiControllerIntegrationTest { @Autowired private QrApi api; - @Test - public void getQRTest() throws Exception { - String id = "www.google.es"; - QRItem qr = new QRItem(); - qr.setUri(id); - qr.convertBase64(500, 500); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - // When any incorrect param is passed, such as a null param, negative param, zero param or smaller than - // 30 param, the QR is generated with a standar 500px size. - @Test - public void nullWidthTest() throws Exception { - String id = "www.google.es"; - String width = null; - QRItem qr = new QRItem(); - int w = StringChecker.checkString2Int(width); - - qr.setUri(id); - qr.convertBase64(w, 500); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - @Test - public void nullHeigthTest() throws Exception { - String id = "www.google.es"; - String height = null; - QRItem qr = new QRItem(); - int h = StringChecker.checkString2Int(height); - - qr.setUri(id); - qr.convertBase64(500, h); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - @Test - public void negativeWidthTest() throws Exception { - String id = "www.google.es"; - String width = "-5"; - QRItem qr = new QRItem(); - int w = StringChecker.checkString2Int(width); - - qr.setUri(id); - qr.convertBase64(w, 500); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - @Test - public void negativeHeightTest() throws Exception { - String id = "www.google.es"; - String height = "-34"; - QRItem qr = new QRItem(); - int h = StringChecker.checkString2Int(height); - - qr.setUri(id); - qr.convertBase64(500, h); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - @Test - public void zeroWidthTest() throws Exception { - String id = "www.google.es"; - String width = "0"; - QRItem qr = new QRItem(); - int w = StringChecker.checkString2Int(width); - - qr.setUri(id); - qr.convertBase64(w, 500); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - @Test - public void zeroHeightTest() throws Exception { - String id = "www.google.es"; - String height = "0"; - QRItem qr = new QRItem(); - int h = StringChecker.checkString2Int(height); - - qr.setUri(id); - qr.convertBase64(500, h); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - @Test - public void smallerThan30WidthTest() throws Exception { - String id = "www.google.es"; - String width = "27"; - QRItem qr = new QRItem(); - int w = StringChecker.checkString2Int(width); - - qr.setUri(id); - qr.convertBase64(w, 500); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - @Test - public void smallerThan30heightTest() throws Exception { - String id = "www.google.es"; - String height = "27"; - QRItem qr = new QRItem(); - int h = StringChecker.checkString2Int(height); - - qr.setUri(id); - qr.convertBase64(500, h); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - - @Test - public void greaterThan2048WidthTest() throws Exception { - String id = "www.google.es"; - String width = "2049"; - QRItem qr = new QRItem(); - int w = StringChecker.checkString2Int(width); - - qr.setUri(id); - qr.convertBase64(w, 500); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } - @Test - public void greaterThan2048heightTest() throws Exception { - String id = "www.google.es"; - String height = "2049"; - QRItem qr = new QRItem(); - int h = StringChecker.checkString2Int(height); - - qr.setUri(id); - qr.convertBase64(500, h); - - assertEquals(EXPECTED_QR_CODE, qr.getQr()); - } } diff --git a/demo/src/test/java/urlshortener/demo/domain/QRItemTest.java b/demo/src/test/java/urlshortener/demo/domain/QRItemTest.java index 2ea934f3..4d025df4 100644 --- a/demo/src/test/java/urlshortener/demo/domain/QRItemTest.java +++ b/demo/src/test/java/urlshortener/demo/domain/QRItemTest.java @@ -1,12 +1,15 @@ package urlshortener.demo.domain; import org.junit.Test; +import urlshortener.demo.utils.StringChecker; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class QRItemTest { + private static final String EXPECTED_QR_CODE = "iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AQAAAADjreInAAABg0lEQVR42u3cO3KDMBAAUGVcuOQIOQpHs4/mo/gIlCkyUcb8JAEJJplJEb0tgadyZ3clEeKvogs8z/M8z/M8z/M8z/P83/iPUMQpf9DEt/Jtw/M8X/iUVt4GH+M1tPHe+1N6e+d5nl/565xuTpsLPqLleZ7f90O88jzPH/NFucLzPL/jV+XKJd7m/HO8f+J5vhq/mr/m85OfzG95nq/Db8Xq84P7xzzP1+HHcuVRnQz5p/dT/RLje3jZWJDneb7wTf95yMclxfxkL//wPF+ZH9NNyj/jQOWRf7q8IQpjQuJ5nl/mn5jKlWncGsI5kdtO/cLzfHW+jyG7dPmotR39WNBcvtq/4Xm+cp9Hcf4se9A+Ob/leb4av9r/3Vpwr//heb5Wnx4v7s90U/+Tb+jwPM8vs0txf+bSj0vm/uf78yM8z/Pz/ZnU7iwWbHie55/zQ/2yOz/heb5mv+p/rkfOv/M8X6/fuH83nT87lwdKGp7nef+P5nme53me53me53me/+f+E5W4ETCek3pPAAAAAElFTkSuQmCC"; + @Test public void checkQRQR(){ QRItem qrItem = new QRItem().qr("qr"); @@ -53,4 +56,146 @@ public void testQRtoString(){ QRItem base = new QRItem().uri("abc"); assertEquals("class QRItem {\n uri: abc\n qr: null\n}", base.toString()); } + + @Test + public void getQRTest() { + String id = "www.google.es"; + QRItem qr = new QRItem(); + qr.setUri(id); + qr.convertBase64(500, 500); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + // When any incorrect param is passed, such as a null param, negative param, zero param or smaller than + // 30 param, the QR is generated with a standar 500px size. + @Test + public void nullWidthTest() { + String id = "www.google.es"; + String width = null; + QRItem qr = new QRItem(); + int w = StringChecker.checkString2Int(width); + + qr.setUri(id); + qr.convertBase64(w, 500); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void nullHeigthTest() { + String id = "www.google.es"; + String height = null; + QRItem qr = new QRItem(); + int h = StringChecker.checkString2Int(height); + + qr.setUri(id); + qr.convertBase64(500, h); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void negativeWidthTest() { + String id = "www.google.es"; + String width = "-5"; + QRItem qr = new QRItem(); + int w = StringChecker.checkString2Int(width); + + qr.setUri(id); + qr.convertBase64(w, 500); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void negativeHeightTest() { + String id = "www.google.es"; + String height = "-34"; + QRItem qr = new QRItem(); + int h = StringChecker.checkString2Int(height); + + qr.setUri(id); + qr.convertBase64(500, h); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void zeroWidthTest() { + String id = "www.google.es"; + String width = "0"; + QRItem qr = new QRItem(); + int w = StringChecker.checkString2Int(width); + + qr.setUri(id); + qr.convertBase64(w, 500); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void zeroHeightTest() { + String id = "www.google.es"; + String height = "0"; + QRItem qr = new QRItem(); + int h = StringChecker.checkString2Int(height); + + qr.setUri(id); + qr.convertBase64(500, h); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void smallerThan30WidthTest() { + String id = "www.google.es"; + String width = "27"; + QRItem qr = new QRItem(); + int w = StringChecker.checkString2Int(width); + + qr.setUri(id); + qr.convertBase64(w, 500); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void smallerThan30heightTest() { + String id = "www.google.es"; + String height = "27"; + QRItem qr = new QRItem(); + int h = StringChecker.checkString2Int(height); + + qr.setUri(id); + qr.convertBase64(500, h); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void greaterThan2048WidthTest() { + String id = "www.google.es"; + String width = "2049"; + QRItem qr = new QRItem(); + int w = StringChecker.checkString2Int(width); + + qr.setUri(id); + qr.convertBase64(w, 500); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } + + @Test + public void greaterThan2048heightTest() { + String id = "www.google.es"; + String height = "2049"; + QRItem qr = new QRItem(); + int h = StringChecker.checkString2Int(height); + + qr.setUri(id); + qr.convertBase64(500, h); + + assertEquals(EXPECTED_QR_CODE, qr.getQr()); + } } From 8af0b5cbfaf791a1e5ae267c5f99068ca46b4059 Mon Sep 17 00:00:00 2001 From: lAngel Date: Fri, 14 Dec 2018 13:59:39 +0100 Subject: [PATCH 094/125] Move QRid from redirection to actual getID() --- .../demo/controller/impl/QrApiController.java | 2 +- .../QrApiControllerIntegrationTest.java | 45 +++++++++++++++++++ .../java/urlshortener/demo/web/QrTests.java | 22 ++------- 3 files changed, 50 insertions(+), 19 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java index e903a6d2..6ff6d21f 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java @@ -62,7 +62,7 @@ public ResponseEntity getQR(@ApiParam(value = "",required=true) @PathVar // Default qr is required, so it's saved if the uri is shorthed if(w==500 && h==500){ URIItem uriItem = this.uriRepository.get(id); - qr = this.qrRepository.get(uriItem.getRedirection()); + qr = this.qrRepository.get(uriItem.getId()); }else{ URIItem uriItem = this.uriRepository.get(id); qr = new QRItem(); diff --git a/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java index 6f459a17..a117e282 100644 --- a/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java @@ -1,9 +1,20 @@ package urlshortener.demo.controller; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; +import urlshortener.demo.domain.QRItem; +import urlshortener.demo.domain.URIItem; +import urlshortener.demo.repository.QRRepository; +import urlshortener.demo.repository.URIRepository; + +import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest @@ -13,6 +24,40 @@ public class QrApiControllerIntegrationTest { @Autowired private QrApi api; + @Autowired + private URIRepository uriRepository; + + @Autowired + private QRRepository qrRepository; + + private QRItem qr; + private URIItem uri; + + @Before + public void setup(){ + String id = "google"; + String redirection = "www.google.es"; + uri = new URIItem().id(id).redirection(redirection); + qr = new QRItem(); + qr.setUri(id); + qr.convertBase64(500, 500); + + uriRepository.add(uri); + qrRepository.add(qr); + } + + @After + public void cleanup(){ + qrRepository.remove(qr.getId()); + uriRepository.remove(uri.getId()); + + } + @Test + public void test500pxWidthAndHeight(){ + ResponseEntity response = api.getQR("google"); + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertEquals(qr, response.getBody()); + } } diff --git a/demo/src/test/java/urlshortener/demo/web/QrTests.java b/demo/src/test/java/urlshortener/demo/web/QrTests.java index 8369fcd1..b2f19d45 100644 --- a/demo/src/test/java/urlshortener/demo/web/QrTests.java +++ b/demo/src/test/java/urlshortener/demo/web/QrTests.java @@ -1,41 +1,27 @@ package urlshortener.demo.web; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.util.JSONPObject; -import com.jayway.jsonpath.JsonPath; - -import org.hamcrest.core.IsNot; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; +import urlshortener.demo.controller.advice.BaseControllerAdvice; import urlshortener.demo.controller.impl.QrApiController; -import urlshortener.demo.controller.impl.UriApiController; import urlshortener.demo.domain.QRItem; -import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; -import urlshortener.demo.web.MockUtils; import urlshortener.demo.repository.QRRepository; import urlshortener.demo.repository.URIRepository; -import urlshortener.demo.controller.advice.BaseControllerAdvice; import javax.servlet.http.HttpServletRequest; -import static org.hamcrest.Matchers.is; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; public class QrTests { @@ -72,7 +58,7 @@ public void uriGetWorks() throws Exception { when(uriRepository.get("googleHash")).thenReturn(uriItem); when(uriRepository.contains("googleHash")).thenReturn(true); - when(qrRepository.get(uriItem.getRedirection())).thenReturn(qrItem); + when(qrRepository.get(uriItem.getId())).thenReturn(qrItem); mockMvc.perform(get("/qr/{id}/", "googleHash")) .andDo(print()) From 9f05c866ea470dbb420cc3edbec9c60cc5cea1ec Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Fri, 14 Dec 2018 17:23:40 +0100 Subject: [PATCH 095/125] Fixed unreachable code error. --- .../controller/impl/UriApiController.java | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 5b02b776..8f0036ff 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -74,7 +74,14 @@ public ResponseEntity changeURI(@ApiParam(value = "Optional description try { if (Integer.valueOf(c.makeRequest(item.getRedirection())) == 200) { uriService.add(item); - + // Save default QR to QRRepository if it doesn't already exist + if(!qrService.contains(body.getUri())){ + QRItem qrItem = new QRItem(); + qrItem.setUri(body.getUri()); + qrItem.convertBase64(QR_SIZE, QR_SIZE); + + this.qrService.add(qrItem); + } return new ResponseEntity(item, HttpStatus.CREATED); } else { return new ResponseEntity(HttpStatus.BAD_REQUEST); @@ -82,18 +89,6 @@ public ResponseEntity changeURI(@ApiParam(value = "Optional description } catch (IOException e) { throw new InvalidRequestParametersException(HttpStatus.BAD_REQUEST.value(), "There was a problem with the parameters."); } - uriService.add(item); - - // Save default QR to QRRepository if it doesn't already exist - if(!qrService.contains(body.getUri())){ - QRItem qrItem = new QRItem(); - qrItem.setUri(body.getUri()); - qrItem.convertBase64(QR_SIZE, QR_SIZE); - - this.qrService.add(qrItem); - } - - return new ResponseEntity(item, HttpStatus.CREATED); } public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body) { From e4436e6304b87c21b46c133cad44a83c1781c577 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Fern=C3=A1ndez=20Melic?= Date: Thu, 10 Jan 2019 18:05:41 +0100 Subject: [PATCH 096/125] Frontend feature init --- demo/src/main/resources/static/index.html | 164 ---------------------- 1 file changed, 164 deletions(-) diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index 20640275..d62daacd 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -66,170 +66,6 @@

Build a landing page for your business or project and generate - -
-
-
-
-
-
- -
-

Fully Responsive

-

This theme will look great on any device, no matter the size!

-
-
-
-
-
- -
-

Bootstrap 4 Ready

-

Featuring the latest build of the new Bootstrap 4 framework!

-
-
-
-
-
- -
-

Easy to Use

-

Ready to use with your own content, or customize the source files!

-
-
-
-
-
- - -
-
-
- -
-
-

Fully Responsive Design

-

When you use a theme created by Start Bootstrap, you know that the theme will look great on any device, whether it's a phone, tablet, or desktop the page will behave responsively!

-
-
-
-
-
-

Updated For Bootstrap 4

-

Newly improved, and full of great utility classes, Bootstrap 4 is leading the way in mobile responsive web development! All of the themes on Start Bootstrap are now using Bootstrap 4!

-
-
-
-
-
-

Easy to Use & Customize

-

Landing Page is just HTML and CSS with a splash of SCSS for users who demand some deeper customization options. Out of the box, just add your content and images, and your new landing page will be ready to go!

-
-
-
-
- - -
-
-

What people are saying...

-
-
-
- -
Margaret E.
-

"This is fantastic! Thanks so much guys!"

-
-
-
-
- -
Fred S.
-

"Bootstrap is amazing. I've been using it to create lots of super nice landing pages."

-
-
-
-
- -
Sarah W.
-

"Thanks so much for making these free resources available to us!"

-
-
-
-
-
- - -
-
-
-
-
-

Ready to get started? Sign up now!

-
-
-
-
-
- -
-
- -
-
-
-
-
-
-
- - - - From 4f3489cdf8678c9b0caebca73363e5602a3c461f Mon Sep 17 00:00:00 2001 From: robertoccu Date: Thu, 10 Jan 2019 18:09:20 +0100 Subject: [PATCH 097/125] Change /link to /uri --- demo/src/main/resources/static/index.html | 4 ++-- demo/src/main/resources/static/js/app.js | 13 +++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index d62daacd..ea09194a 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -49,8 +49,8 @@

Build a landing page for your business or project and generate
- +
diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index 36082e23..c7aebf08 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -4,20 +4,21 @@ $(document).ready( function(event) { event.preventDefault(); $.ajax({ - type : "POST", - url : "/link", - data : $(this).serialize(), + type : "PUT", + url : "/uri", + contentType: "application/json", + data: JSON.stringify({"uri":"http://google.es"}), // access in body success : function(msg) { $("#result").html( ""); }, error : function() { $("#result").html( - "
ERROR
"); + "
ERROR -> " + $("#urlInput").accessKeyLabel + "
"); } }); }); From 224b472d6e4254537b3de59b656ba33b64ce0e8b Mon Sep 17 00:00:00 2001 From: robertoccu Date: Thu, 10 Jan 2019 18:25:55 +0100 Subject: [PATCH 098/125] Basic URI shortener form working --- demo/src/main/resources/static/index.html | 2 +- demo/src/main/resources/static/js/app.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index ea09194a..bc1836eb 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -50,7 +50,7 @@

Build a landing page for your business or project and generate
+ title="Enter a URL" placeholder="http:// Your URI here">
diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index c7aebf08..568a5a19 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -7,7 +7,7 @@ $(document).ready( type : "PUT", url : "/uri", contentType: "application/json", - data: JSON.stringify({"uri":"http://google.es"}), // access in body + data: JSON.stringify({"uri":$("#urlInput").val()}), // access in body success : function(msg) { $("#result").html( ""); + "
ERROR: \"" + $("#urlInput").val() + "\" isn't a valid URI.
"); } }); }); From 9cd81f03a7830d2cdcc03ba597f26e6a3708ebda Mon Sep 17 00:00:00 2001 From: robertoccu Date: Thu, 10 Jan 2019 18:32:09 +0100 Subject: [PATCH 099/125] Minor design changes --- demo/src/main/resources/static/index.html | 9 ++++----- demo/src/main/resources/static/js/app.js | 4 ++-- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index bc1836eb..ba008024 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -8,7 +8,7 @@ - URL Shortener + TinyURI @@ -33,8 +33,7 @@
@@ -52,14 +51,14 @@

Build a landing page for your business or project and generate + class="btn btn-lg btn-primary" type="submit">Short URI


-
+
diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index 568a5a19..cd2a34fa 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -9,7 +9,7 @@ $(document).ready( contentType: "application/json", data: JSON.stringify({"uri":$("#urlInput").val()}), // access in body success : function(msg) { - $("#result").html( + $("#shortenerResult").html( ""); }, error : function() { - $("#result").html( + $("#shortenerResult").html( "
ERROR: \"" + $("#urlInput").val() + "\" isn't a valid URI.
"); } }); From 1b6f091525340f3c6f52e3a2a5318df1d7e54f50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Fern=C3=A1ndez=20Melic?= Date: Fri, 11 Jan 2019 12:55:42 +0100 Subject: [PATCH 100/125] QR search on repository based on redirection, no id (hash). Reverted to previous state --- .../demo/controller/impl/QrApiController.java | 2 +- .../QrApiControllerIntegrationTest.java | 62 ------------------- .../java/urlshortener/demo/web/QrTests.java | 2 +- 3 files changed, 2 insertions(+), 64 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java index 6ff6d21f..e903a6d2 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/QrApiController.java @@ -62,7 +62,7 @@ public ResponseEntity getQR(@ApiParam(value = "",required=true) @PathVar // Default qr is required, so it's saved if the uri is shorthed if(w==500 && h==500){ URIItem uriItem = this.uriRepository.get(id); - qr = this.qrRepository.get(uriItem.getId()); + qr = this.qrRepository.get(uriItem.getRedirection()); }else{ URIItem uriItem = this.uriRepository.get(id); qr = new QRItem(); diff --git a/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java b/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java index a117e282..8b137891 100644 --- a/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java +++ b/demo/src/test/java/urlshortener/demo/controller/QrApiControllerIntegrationTest.java @@ -1,63 +1 @@ -package urlshortener.demo.controller; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; -import urlshortener.demo.domain.QRItem; -import urlshortener.demo.domain.URIItem; -import urlshortener.demo.repository.QRRepository; -import urlshortener.demo.repository.URIRepository; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class QrApiControllerIntegrationTest { - - private static final String EXPECTED_QR_CODE = "iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AQAAAADjreInAAABg0lEQVR42u3cO3KDMBAAUGVcuOQIOQpHs4/mo/gIlCkyUcb8JAEJJplJEb0tgadyZ3clEeKvogs8z/M8z/M8z/M8z/P83/iPUMQpf9DEt/Jtw/M8X/iUVt4GH+M1tPHe+1N6e+d5nl/565xuTpsLPqLleZ7f90O88jzPH/NFucLzPL/jV+XKJd7m/HO8f+J5vhq/mr/m85OfzG95nq/Db8Xq84P7xzzP1+HHcuVRnQz5p/dT/RLje3jZWJDneb7wTf95yMclxfxkL//wPF+ZH9NNyj/jQOWRf7q8IQpjQuJ5nl/mn5jKlWncGsI5kdtO/cLzfHW+jyG7dPmotR39WNBcvtq/4Xm+cp9Hcf4se9A+Ob/leb4av9r/3Vpwr//heb5Wnx4v7s90U/+Tb+jwPM8vs0txf+bSj0vm/uf78yM8z/Pz/ZnU7iwWbHie55/zQ/2yOz/heb5mv+p/rkfOv/M8X6/fuH83nT87lwdKGp7nef+P5nme53me53me53me/+f+E5W4ETCek3pPAAAAAElFTkSuQmCC"; - @Autowired - private QrApi api; - - @Autowired - private URIRepository uriRepository; - - @Autowired - private QRRepository qrRepository; - - private QRItem qr; - private URIItem uri; - - @Before - public void setup(){ - String id = "google"; - String redirection = "www.google.es"; - uri = new URIItem().id(id).redirection(redirection); - qr = new QRItem(); - qr.setUri(id); - qr.convertBase64(500, 500); - - uriRepository.add(uri); - qrRepository.add(qr); - } - - @After - public void cleanup(){ - qrRepository.remove(qr.getId()); - uriRepository.remove(uri.getId()); - - } - - @Test - public void test500pxWidthAndHeight(){ - ResponseEntity response = api.getQR("google"); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(qr, response.getBody()); - } - -} diff --git a/demo/src/test/java/urlshortener/demo/web/QrTests.java b/demo/src/test/java/urlshortener/demo/web/QrTests.java index b2f19d45..f6069822 100644 --- a/demo/src/test/java/urlshortener/demo/web/QrTests.java +++ b/demo/src/test/java/urlshortener/demo/web/QrTests.java @@ -58,7 +58,7 @@ public void uriGetWorks() throws Exception { when(uriRepository.get("googleHash")).thenReturn(uriItem); when(uriRepository.contains("googleHash")).thenReturn(true); - when(qrRepository.get(uriItem.getId())).thenReturn(qrItem); + when(qrRepository.get(uriItem.getRedirection())).thenReturn(qrItem); mockMvc.perform(get("/qr/{id}/", "googleHash")) .andDo(print()) From df5a937e14283841e0a892e28b3921a38c6f298d Mon Sep 17 00:00:00 2001 From: robertoccu Date: Fri, 11 Jan 2019 16:00:18 +0100 Subject: [PATCH 101/125] Basic design for create, edit and delete URIS done --- .../resources/static/css/landing-page.css | 26 ++++++- .../resources/static/css/landing-page.min.css | 2 +- demo/src/main/resources/static/index.html | 77 ++++++++++++++++++- 3 files changed, 97 insertions(+), 8 deletions(-) diff --git a/demo/src/main/resources/static/css/landing-page.css b/demo/src/main/resources/static/css/landing-page.css index 4a122296..7465d935 100644 --- a/demo/src/main/resources/static/css/landing-page.css +++ b/demo/src/main/resources/static/css/landing-page.css @@ -20,8 +20,8 @@ h6 { header.masthead { position: relative; - background-color: #343a40; - background: url("../img/bg-masthead.jpg") no-repeat center center; + background-color: #294028; + /*background: url("../img/bg-masthead.jpg") no-repeat center center;*/ background-size: cover; padding-top: 8rem; padding-bottom: 8rem; @@ -104,8 +104,7 @@ header.masthead h1 { .call-to-action { position: relative; - background-color: #343a40; - background: url("../img/bg-masthead.jpg") no-repeat center center; + background-color: #3f4024; background-size: cover; padding-top: 7rem; padding-bottom: 7rem; @@ -121,6 +120,25 @@ header.masthead h1 { opacity: 0.3; } +.delete-uri { + position: relative; + background-color: #402722; + background-size: cover; + padding-top: 7rem; + padding-bottom: 7rem; +} + +.delete-uri .overlay { + position: absolute; + background-color: #212529; + height: 100%; + width: 100%; + top: 0; + left: 0; + opacity: 0.3; +} + + footer.footer { padding-top: 4rem; padding-bottom: 4rem; diff --git a/demo/src/main/resources/static/css/landing-page.min.css b/demo/src/main/resources/static/css/landing-page.min.css index be98144a..ad36fd11 100644 --- a/demo/src/main/resources/static/css/landing-page.min.css +++ b/demo/src/main/resources/static/css/landing-page.min.css @@ -2,4 +2,4 @@ * Start Bootstrap - Landing Page v5.0.0 (https://startbootstrap.com/template-overviews/landing-page) * Copyright 2013-2018 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-landing-page/blob/master/LICENSE) - */body{font-family:Lato,'Helvetica Neue',Helvetica,Arial,sans-serif}h1,h2,h3,h4,h5,h6{font-family:Lato,'Helvetica Neue',Helvetica,Arial,sans-serif;font-weight:700}header.masthead{position:relative;background-color:#343a40;background:url(../img/bg-masthead.jpg) no-repeat center center;background-size:cover;padding-top:8rem;padding-bottom:8rem}header.masthead .overlay{position:absolute;background-color:#212529;height:100%;width:100%;top:0;left:0;opacity:.3}header.masthead h1{font-size:2rem}@media (min-width:768px){header.masthead{padding-top:12rem;padding-bottom:12rem}header.masthead h1{font-size:3rem}}.showcase .showcase-text{padding:3rem}.showcase .showcase-img{min-height:30rem;background-size:cover}@media (min-width:768px){.showcase .showcase-text{padding:7rem}}.features-icons{padding-top:7rem;padding-bottom:7rem}.features-icons .features-icons-item{max-width:20rem}.features-icons .features-icons-item .features-icons-icon{height:7rem}.features-icons .features-icons-item .features-icons-icon i{font-size:4.5rem}.features-icons .features-icons-item:hover .features-icons-icon i{font-size:5rem}.testimonials{padding-top:7rem;padding-bottom:7rem}.testimonials .testimonial-item{max-width:18rem}.testimonials .testimonial-item img{max-width:12rem;-webkit-box-shadow:0 5px 5px 0 #adb5bd;box-shadow:0 5px 5px 0 #adb5bd}.call-to-action{position:relative;background-color:#343a40;background:url(../img/bg-masthead.jpg) no-repeat center center;background-size:cover;padding-top:7rem;padding-bottom:7rem}.call-to-action .overlay{position:absolute;background-color:#212529;height:100%;width:100%;top:0;left:0;opacity:.3}footer.footer{padding-top:4rem;padding-bottom:4rem} \ No newline at end of file + */body{font-family:Lato,'Helvetica Neue',Helvetica,Arial,sans-serif}h1,h2,h3,h4,h5,h6{font-family:Lato,'Helvetica Neue',Helvetica,Arial,sans-serif;font-weight:700}header.masthead{position:relative;background-color:#343a40;background:url(../img/bg-masthead.jpg) no-repeat center center;background-size:cover;padding-top:8rem;padding-bottom:8rem}header.masthead .overlay{position:absolute;background-color:#212529;height:100%;width:100%;top:0;left:0;opacity:.3}header.masthead h1{font-size:2rem}@media (min-width:768px){header.masthead{padding-top:12rem;padding-bottom:12rem}header.masthead h1{font-size:3rem}}.showcase .showcase-text{padding:3rem}.showcase .showcase-img{min-height:30rem;background-size:cover}@media (min-width:768px){.showcase .showcase-text{padding:7rem}}.features-icons{padding-top:7rem;padding-bottom:7rem}.features-icons .features-icons-item{max-width:20rem}.features-icons .features-icons-item .features-icons-icon{height:7rem}.features-icons .features-icons-item .features-icons-icon i{font-size:4.5rem}.features-icons .features-icons-item:hover .features-icons-icon i{font-size:5rem}.testimonials{padding-top:7rem;padding-bottom:7rem}.testimonials .testimonial-item{max-width:18rem}.testimonials .testimonial-item img{max-width:12rem;-webkit-box-shadow:0 5px 5px 0 #adb5bd;box-shadow:0 5px 5px 0 #adb5bd}.call-to-action{position:relative;background-color:#343a40;background-size:cover;padding-top:7rem;padding-bottom:7rem}.call-to-action .overlay{position:absolute;background-color:#212529;height:100%;width:100%;top:0;left:0;opacity:.3}footer.footer{padding-top:4rem;padding-bottom:4rem} \ No newline at end of file diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index ba008024..2ec1639f 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -19,7 +19,7 @@ - + @@ -34,16 +34,17 @@ - +
-

Build a landing page for your business or project and generate more leads!

+

Generate a short URI and a QR for your webpage

@@ -65,6 +66,76 @@

Build a landing page for your business or project and generate

+ +
+
+
+
+
+

Edit the name of your shortened URI

+
+
+ +
+ + + It starts with "http://tinyuri.xyz/". +
+
+ + + The HashPass is a private key given to you only at the creation of a new shortened URI. +
+
+ + + The name that will appear at the end of the URI. Example: http://tinyuri.xyz/myCoolNewName. +
+ + +
+
+
+
+ + +
+
+
+
+
+

Delete your shortened URI forever

+
+
+
+
+ + + It starts with "http://tinyuri.xyz/". +
+
+ + + The HashPass is a private key given to you only at the creation of a new shortened URI. +
+ +
+
+
+
+
+ + +
+
+
+
+

Created by Blue-Bash at Unizar.

+
+
+
+
+ From c2f495eb8d86cb887491d15ed7a700ab7851cba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Fern=C3=A1ndez=20Melic?= Date: Fri, 11 Jan 2019 17:34:16 +0100 Subject: [PATCH 102/125] QR support added to frontend --- .../urlshortener/demo/utils/StringChecker.java | 4 ++++ demo/src/main/resources/static/index.html | 10 +++++++++- demo/src/main/resources/static/js/app.js | 18 ++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/demo/src/main/java/urlshortener/demo/utils/StringChecker.java b/demo/src/main/java/urlshortener/demo/utils/StringChecker.java index ac3b5e97..1237f858 100644 --- a/demo/src/main/java/urlshortener/demo/utils/StringChecker.java +++ b/demo/src/main/java/urlshortener/demo/utils/StringChecker.java @@ -8,6 +8,10 @@ public static int checkString2Int(String string){ return 500; } + if (string == ""){ + return 500; + } + int num = Integer.parseInt(string); if(num < 30){ diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index 2ec1639f..be56e9bb 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -50,16 +50,24 @@

Generate a short URI and a QR for your webpage

+ title="Enter a URL" placeholder="https:// Your URI here">
+
+
+ + +

+
diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index cd2a34fa..6db86efa 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -15,6 +15,24 @@ $(document).ready( + "'>" + window.location.origin + "/uri/" + msg.id + ""); + + var width = $("#qrWidth").val(); + var height = $("#qrHeight").val(); + + $.ajax({ + type : "GET", + url : "/qr/" + msg.id + "?width=" + width + "&height=" + height, + contentType: "application/json", + success : function(msg) { + $("#QRResult").html( + ""); + }, + error : function() { + $("#QRResult").html( + "
Error retrieving QR Code
"); + } + }); + }, error : function() { $("#shortenerResult").html( From d2ac7342f3a3df8cda36ebca8b9064ee0b3daf4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Fern=C3=A1ndez=20Melic?= Date: Fri, 11 Jan 2019 18:21:18 +0100 Subject: [PATCH 103/125] Test fixed --- demo/src/test/java/urlshortener/demo/SystemTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/src/test/java/urlshortener/demo/SystemTests.java b/demo/src/test/java/urlshortener/demo/SystemTests.java index 4dbf7455..f5bec639 100755 --- a/demo/src/test/java/urlshortener/demo/SystemTests.java +++ b/demo/src/test/java/urlshortener/demo/SystemTests.java @@ -44,7 +44,7 @@ public void testHome() { ResponseEntity entity = restTemplate.getForEntity("http://localhost:"+port+"/", String.class); assertThat(entity.getStatusCode(), is(HttpStatus.OK)); assertTrue(entity.getHeaders().getContentType().isCompatibleWith(new MediaType("text", "html"))); - assertThat(entity.getBody(), containsString("URL")); + assertThat(entity.getBody(), containsString("<title>TinyURI")); } @Test From 39030ec6c16ebbcd6f66c6f0ea0ba1e3afb3f08d Mon Sep 17 00:00:00 2001 From: Roberto CCU <ccucraft@gmail.com> Date: Sun, 13 Jan 2019 20:49:23 +0100 Subject: [PATCH 104/125] Delete URI with hashpass working --- demo/src/main/resources/static/index.html | 26 +++-- demo/src/main/resources/static/js/app.js | 122 +++++++++++++++------- 2 files changed, 104 insertions(+), 44 deletions(-) diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index be56e9bb..d8ecfe6c 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -83,11 +83,11 @@ <h1 class="mb-5">Generate a short URI and a QR for your webpage</h1> <h2 class="mb-4">Edit the name of your shortened URI</h2> </div> <div class="col-md-10 col-lg-8 col-xl-6 mx-auto"> - <form> + <form id="nameEdit"> <div class="form-group"> - <label for="name_shortUriInput">Your shortened URI</label> - <input type="url" id="name_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/######"> - <small class="form-text text-muted">It starts with "http://tinyuri.xyz/".</small> + <label for="name_shortUriInput">Your shortened URI code</label> + <input type="text" id="name_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/######"> + <small class="form-text text-muted">After "http://tinyuri.xyz/".</small> </div> <div class="form-group"> <label for="name_hashPassInput">HashPass of your URI</label> @@ -102,6 +102,12 @@ <h2 class="mb-4">Edit the name of your shortened URI</h2> <button type="submit" class="btn btn-primary btn-warning">Apply changes</button> </form> </div> + <div class="col-md-10 col-lg-8 col-xl-7 mx-auto"> + <div class="col-sm-12 text-center"> + <br /> + <div id="nameEditResult"></div> + </div> + </div> </div> </div> </section> @@ -115,11 +121,11 @@ <h2 class="mb-4">Edit the name of your shortened URI</h2> <h2 class="mb-4">Delete your shortened URI forever</h2> </div> <div class="col-md-10 col-lg-8 col-xl-6 mx-auto"> - <form> + <form id="uriDelete"> <div class="form-group"> <label for="name_shortUriInput">Your shortened URI</label> - <input type="url" id="delete_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/######"> - <small class="form-text text-muted">It starts with "http://tinyuri.xyz/".</small> + <input type="text" id="delete_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/######"> + <small class="form-text text-muted">Starts with "http://tinyuri.xyz/".</small> </div> <div class="form-group"> <label for="name_hashPassInput">HashPass of your URI</label> @@ -129,6 +135,12 @@ <h2 class="mb-4">Delete your shortened URI forever</h2> <button type="submit" class="btn btn-primary btn-danger">Delete FOREVER your URI</button> </form> </div> + <div class="col-md-10 col-lg-8 col-xl-7 mx-auto"> + <div class="col-sm-12 text-center"> + <br /> + <div id="deleteUriResult"></div> + </div> + </div> </div> </div> </section> diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index 6db86efa..875c9788 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -1,43 +1,91 @@ $(document).ready( - function() { - $("#shortener").submit( - function(event) { - event.preventDefault(); - $.ajax({ - type : "PUT", - url : "/uri", - contentType: "application/json", - data: JSON.stringify({"uri":$("#urlInput").val()}), // access in body - success : function(msg) { - $("#shortenerResult").html( - "<div class='alert alert-success lead'><a target='_blank' href='" - + window.location.origin + "/uri/" + msg.id - + "'>" - + window.location.origin + "/uri/" + msg.id - + "</a></div>"); - - var width = $("#qrWidth").val(); - var height = $("#qrHeight").val(); + function () { + $("#shortener").submit( + function (event) { + event.preventDefault(); + $.ajax({ + type: "PUT", + url: "/uri", + contentType: "application/json", + data: JSON.stringify({"uri": $("#urlInput").val()}), // access in body + success: function (msg) { + $("#shortenerResult").html( + "<div class='alert alert-success lead'><a target='_blank' href='" + + window.location.origin + "/uri/" + msg.id + + "'>" + + window.location.origin + "/uri/" + msg.id + + "</a>" + + "</br>" + + "<p>This is your HashPass; a private key for editing and delete your URI: " + msg.hashpass + "</p>" + + "</div>"); - $.ajax({ - type : "GET", - url : "/qr/" + msg.id + "?width=" + width + "&height=" + height, - contentType: "application/json", - success : function(msg) { - $("#QRResult").html( - "<img src=\"data:image/jpeg;base64," + msg.qr + "\">"); - }, - error : function() { - $("#QRResult").html( - "<div class='alert alert-danger lead'>Error retrieving QR Code</div>"); - } - }); + var width = $("#qrWidth").val(); + var height = $("#qrHeight").val(); - }, - error : function() { - $("#shortenerResult").html( - "<div class='alert alert-danger lead'>ERROR: \"" + $("#urlInput").val() + "\" isn't a valid URI.</div>"); - } + $.ajax({ + type: "GET", + url: "/qr/" + msg.id + "?width=" + width + "&height=" + + height, + contentType: "application/json", + success: function (msg) { + $("#QRResult").html( + "<img src=\"data:image/jpeg;base64," + msg.qr + "\">"); + }, + error: function () { + $("#QRResult").html( + "<div class='alert alert-danger lead'>Error retrieving QR Code</div>"); + } }); + + }, + error: function () { + $("#shortenerResult").html( + "<div class='alert alert-danger lead'>ERROR: \"" + $( + "#urlInput").val() + "\" isn't a valid URI.</div>"); + } + }); + }); + $("#nameEdit").submit( + function (event) { + event.preventDefault(); + $.ajax({ + type: "PUT", + url: "/uri/" + $("#name_shortUriInput").val(), + contentType: "application/json", + data: JSON.stringify({"new-name": $("#name_newNameInput").val(), + "hashpass": $("#name_hashPassInput").val()}), // access in body + success: function (msg) { + $("#nameEditResult").html( + "<div class='alert alert-success lead'><a target='_blank' href='" + + window.location.origin + "/uri/" + msg.id + + "'>" + + window.location.origin + "/uri/" + msg.id + + "</a></div>"); + }, + error: function () { + $("#nameEditResult").html( + "<div class='alert alert-danger lead'>ERROR: Name or URI isn't valid.</div>"); + } + }); + }); + + $("#uriDelete").submit( + function (event) { + event.preventDefault(); + $.ajax({ + type: "DELETE", + url: "/uri/" + $("#delete_shortUriInput").val(), + headers: { + URIHashPass: $("#delete_hashPassInput").val() + }, + success: function () { + $("#deleteUriResult").html( + "<div class='alert alert-success lead'><p>Deleted</p></div>"); + }, + error: function () { + $("#deleteUriResult").html( + "<div class='alert alert-danger lead'>ERROR: ID or HashPass isn't valid.</div>"); + } }); + }); }); \ No newline at end of file From c66c7fd9f14ff4f2b35f2b00b1d18245f8d17a1e Mon Sep 17 00:00:00 2001 From: Roberto CCU <ccucraft@gmail.com> Date: Sun, 13 Jan 2019 21:05:16 +0100 Subject: [PATCH 105/125] Added option to short URI with a custom name. --- demo/src/main/resources/static/index.html | 10 ++++++---- demo/src/main/resources/static/js/app.js | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index d8ecfe6c..a0c25b36 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -60,6 +60,8 @@ <h1 class="mb-5">Generate a short URI and a QR for your webpage</h1> title="Enter QR width" placeholder="QR width"> <input id="qrHeight" type="text" class="center-block form-control input-lg" title="Enter QR Height" placeholder="QR height"> + <input id="customName" type="text" class="center-block form-control input-lg" + title="Enter custom name" placeholder="Custom name"> </div> </form> </div> @@ -86,7 +88,7 @@ <h2 class="mb-4">Edit the name of your shortened URI</h2> <form id="nameEdit"> <div class="form-group"> <label for="name_shortUriInput">Your shortened URI code</label> - <input type="text" id="name_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/######"> + <input type="text" id="name_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/uri/######"> <small class="form-text text-muted">After "http://tinyuri.xyz/".</small> </div> <div class="form-group"> @@ -123,9 +125,9 @@ <h2 class="mb-4">Delete your shortened URI forever</h2> <div class="col-md-10 col-lg-8 col-xl-6 mx-auto"> <form id="uriDelete"> <div class="form-group"> - <label for="name_shortUriInput">Your shortened URI</label> - <input type="text" id="delete_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/######"> - <small class="form-text text-muted">Starts with "http://tinyuri.xyz/".</small> + <label for="name_shortUriInput">Your shortened URI code</label> + <input type="text" id="delete_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/uri/######"> + <small class="form-text text-muted">Starts with "http://tinyuri.xyz/uri/".</small> </div> <div class="form-group"> <label for="name_hashPassInput">HashPass of your URI</label> diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index 875c9788..afd798a7 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -3,9 +3,10 @@ $(document).ready( $("#shortener").submit( function (event) { event.preventDefault(); + var name = $("#customName").val(); $.ajax({ type: "PUT", - url: "/uri", + url: "/uri/" + name, contentType: "application/json", data: JSON.stringify({"uri": $("#urlInput").val()}), // access in body success: function (msg) { @@ -45,7 +46,7 @@ $(document).ready( } }); }); - $("#nameEdit").submit( + $("#nameEdit").submit( // Implemented as API but not working function (event) { event.preventDefault(); $.ajax({ From d2a79dc56c25d873601a57800f39ac034b3c8f32 Mon Sep 17 00:00:00 2001 From: Roberto CCU <ccucraft@gmail.com> Date: Sun, 13 Jan 2019 21:18:01 +0100 Subject: [PATCH 106/125] Minor changes to design --- demo/src/main/resources/static/index.html | 22 +++++++++++----------- demo/src/main/resources/static/js/app.js | 12 ++++++------ 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index a0c25b36..791840c7 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -55,7 +55,7 @@ <h1 class="mb-5">Generate a short URI and a QR for your webpage</h1> class="btn btn-lg btn-primary" type="submit">Short URI</button></span> </div> <br/> - <div class="input-group input-group-lg col-sm-6"> + <div class="input-group input-group-lg col-lg-12"> <input id="qrWidth" type="text" class="center-block form-control input-lg" title="Enter QR width" placeholder="QR width"> <input id="qrHeight" type="text" class="center-block form-control input-lg" @@ -87,18 +87,18 @@ <h2 class="mb-4">Edit the name of your shortened URI</h2> <div class="col-md-10 col-lg-8 col-xl-6 mx-auto"> <form id="nameEdit"> <div class="form-group"> - <label for="name_shortUriInput">Your shortened URI code</label> - <input type="text" id="name_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/uri/######"> + <label for="nameShortUriInput">Your shortened URI code</label> + <input type="text" id="nameShortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/uri/######"> <small class="form-text text-muted">After "http://tinyuri.xyz/".</small> </div> <div class="form-group"> - <label for="name_hashPassInput">HashPass of your URI</label> - <input type="password" id="name_hashPassInput" class="form-control form-control-lg" placeholder="******"> + <label for="nameHashPassInput">HashPass of your URI</label> + <input type="password" id="nameHashPassInput" class="form-control form-control-lg" placeholder="******"> <small class="form-text text-muted">The HashPass is a private key given to you only at the creation of a new shortened URI.</small> </div> <div class="form-group"> - <label for="name_newNameInput">New name for the shortened URI</label> - <input type="text" id="name_newNameInput" class="form-control form-control-lg" placeholder="myCoolNewName"> + <label for="nameNewNameInput">New name for the shortened URI</label> + <input type="text" id="nameNewNameInput" class="form-control form-control-lg" placeholder="myCoolNewName"> <small class="form-text text-muted">The name that will appear at the end of the URI. Example: http://tinyuri.xyz/myCoolNewName.</small> </div> <button type="submit" class="btn btn-primary btn-warning">Apply changes</button> @@ -125,13 +125,13 @@ <h2 class="mb-4">Delete your shortened URI forever</h2> <div class="col-md-10 col-lg-8 col-xl-6 mx-auto"> <form id="uriDelete"> <div class="form-group"> - <label for="name_shortUriInput">Your shortened URI code</label> - <input type="text" id="delete_shortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/uri/######"> + <label for="deleteShortUriInput">Your shortened URI code</label> + <input type="text" id="deleteShortUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/uri/######"> <small class="form-text text-muted">Starts with "http://tinyuri.xyz/uri/".</small> </div> <div class="form-group"> - <label for="name_hashPassInput">HashPass of your URI</label> - <input type="password" id="delete_hashPassInput" class="form-control form-control-lg" placeholder="******"> + <label for="deleteHashPassInput">HashPass of your URI</label> + <input type="password" id="deleteHashPassInput" class="form-control form-control-lg" placeholder="******"> <small class="form-text text-muted">The HashPass is a private key given to you only at the creation of a new shortened URI.</small> </div> <button type="submit" class="btn btn-primary btn-danger">Delete FOREVER your URI</button> diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index afd798a7..2e05e51f 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -42,7 +42,7 @@ $(document).ready( error: function () { $("#shortenerResult").html( "<div class='alert alert-danger lead'>ERROR: \"" + $( - "#urlInput").val() + "\" isn't a valid URI.</div>"); + "#urlInput").val() + "\" isn't a valid URI or name is already taken.</div>"); } }); }); @@ -51,10 +51,10 @@ $(document).ready( event.preventDefault(); $.ajax({ type: "PUT", - url: "/uri/" + $("#name_shortUriInput").val(), + url: "/uri/" + $("#nameShortUriInput").val(), contentType: "application/json", - data: JSON.stringify({"new-name": $("#name_newNameInput").val(), - "hashpass": $("#name_hashPassInput").val()}), // access in body + data: JSON.stringify({"new-name": $("#nameNewNameInput").val(), + "hashpass": $("#nameHashPassInput").val()}), // access in body success: function (msg) { $("#nameEditResult").html( "<div class='alert alert-success lead'><a target='_blank' href='" @@ -75,9 +75,9 @@ $(document).ready( event.preventDefault(); $.ajax({ type: "DELETE", - url: "/uri/" + $("#delete_shortUriInput").val(), + url: "/uri/" + $("#deleteShortUriInput").val(), headers: { - URIHashPass: $("#delete_hashPassInput").val() + URIHashPass: $("#deleteHashPassInput").val() }, success: function () { $("#deleteUriResult").html( From 6b32ceaef849ca57feb3a768e5b1e4eb3fa64b20 Mon Sep 17 00:00:00 2001 From: Roberto CCU <ccucraft@gmail.com> Date: Sun, 13 Jan 2019 21:54:05 +0100 Subject: [PATCH 107/125] Added QR Viewer functionality. --- .../resources/static/css/landing-page.css | 18 +++++++++ demo/src/main/resources/static/index.html | 40 ++++++++++++++++++- demo/src/main/resources/static/js/app.js | 20 ++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/demo/src/main/resources/static/css/landing-page.css b/demo/src/main/resources/static/css/landing-page.css index 7465d935..41c93aac 100644 --- a/demo/src/main/resources/static/css/landing-page.css +++ b/demo/src/main/resources/static/css/landing-page.css @@ -120,6 +120,24 @@ header.masthead h1 { opacity: 0.3; } +.qrViewer { + position: relative; + background-color: #263940; + background-size: cover; + padding-top: 7rem; + padding-bottom: 7rem; +} + +.qrViewer .overlay { + position: absolute; + background-color: #212529; + height: 100%; + width: 100%; + top: 0; + left: 0; + opacity: 0.3; +} + .delete-uri { position: relative; background-color: #402722; diff --git a/demo/src/main/resources/static/index.html b/demo/src/main/resources/static/index.html index 791840c7..6ba5147b 100755 --- a/demo/src/main/resources/static/index.html +++ b/demo/src/main/resources/static/index.html @@ -52,7 +52,7 @@ <h1 class="mb-5">Generate a short URI and a QR for your webpage</h1> <input id="urlInput" type="text" class="center-block form-control input-lg" title="Enter a URL" placeholder="https:// Your URI here"> <span class="input-group-btn"><button - class="btn btn-lg btn-primary" type="submit">Short URI</button></span> + class="btn btn-lg btn-success" type="submit">Short URI</button></span> </div> <br/> <div class="input-group input-group-lg col-lg-12"> @@ -76,6 +76,44 @@ <h1 class="mb-5">Generate a short URI and a QR for your webpage</h1> </div> </header> + <!-- QR Viewer --> + <header class="qrViewer text-white text-center"> + <div class="overlay"></div> + <div class="container"> + <div class="row"> + <div class="col-xl-9 mx-auto"> + <h1 class="mb-5">Generate custom QR</h1> + </div> + <div class="col-md-10 col-lg-8 col-xl-6 mx-auto"> + <form id="qrViewer"> + <div class="form-group"> + <label for="qrUriInput">Your shortened URI code</label> + <input type="text" id="qrUriInput" class="form-control form-control-lg" placeholder="http://tinyuri.xyz/uri/######"> + <small class="form-text text-muted">After "http://tinyuri.xyz/uri/".</small> + </div> + <div class="form-group"> + <label for="qrWidthInput">QR Width</label> + <input type="number" id="qrWidthInput" class="form-control form-control-lg" > + <small class="form-text text-muted">Must be a integer number o left empty for default.</small> + </div> + <div class="form-group"> + <label for="qrHeightInput">QR Height</label> + <input type="number" id="qrHeightInput" class="form-control form-control-lg" > + <small class="form-text text-muted">Must be a integer number o left empty for default.</small> + </div> + <button type="submit" class="btn btn-primary btn-primary">Generate QR</button> + </form> + </div> + <div class="col-md-10 col-lg-8 col-xl-7 mx-auto"> + <div class="col-sm-12 text-center"> + <br /> + <div id="qrViewerResult"></div> + </div> + </div> + </div> + </div> + </header> + <!-- Edit URI --> <section class="call-to-action text-white text-center"> <div class="overlay"></div> diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index 2e05e51f..ff4b59a1 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -46,6 +46,26 @@ $(document).ready( } }); }); + + $("#qrViewer").submit( // Implemented as API but not working + function (event) { + event.preventDefault(); + $.ajax({ + type: "GET", + url: "/qr/" + $("#qrUriInput").val() + "?width=" + $("#qrWidthInput").val() + "&height=" + + $("#qrHeightInput").val(), + contentType: "application/json", + success: function (msg) { + $("#qrViewerResult").html( + "<img src=\"data:image/jpeg;base64," + msg.qr + "\">"); + }, + error: function () { + $("#qrViewerResult").html( + "<div class='alert alert-danger lead'>Error retrieving QR Code</div>"); + } + }); + }); + $("#nameEdit").submit( // Implemented as API but not working function (event) { event.preventDefault(); From 5fffff772b94235f661f951278ffb2a3a28b277a Mon Sep 17 00:00:00 2001 From: Roberto CCU <ccucraft@gmail.com> Date: Mon, 14 Jan 2019 00:41:44 +0100 Subject: [PATCH 108/125] Basic error pages for 429 (too many redirects), 404 and 500 error codes. --- .../src/main/resources/application.properties | 3 ++- demo/src/main/resources/public/error/404.html | 19 ++++++++++++++++++ demo/src/main/resources/public/error/429.html | 19 ++++++++++++++++++ demo/src/main/resources/public/error/500.html | 19 ++++++++++++++++++ .../resources/static/css/landing-page.css | 20 +++++++++++++++++++ 5 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 demo/src/main/resources/public/error/404.html create mode 100644 demo/src/main/resources/public/error/429.html create mode 100644 demo/src/main/resources/public/error/500.html diff --git a/demo/src/main/resources/application.properties b/demo/src/main/resources/application.properties index 0a134790..f2c7d68f 100755 --- a/demo/src/main/resources/application.properties +++ b/demo/src/main/resources/application.properties @@ -1,6 +1,7 @@ +server.error.whitelabel.enabled=false # Spring Datasource JDBC spring.datasource.platform=hsqldb spring.datasource.url=jdbc:hsqldb:mem:. spring.datasource.username=sa spring.datasource.password= -spring.datasource.driverClassName=org.hsqldb.jdbcDriver \ No newline at end of file +spring.datasource.driverClassName=org.hsqldb.jdbcDriver diff --git a/demo/src/main/resources/public/error/404.html b/demo/src/main/resources/public/error/404.html new file mode 100644 index 00000000..57388072 --- /dev/null +++ b/demo/src/main/resources/public/error/404.html @@ -0,0 +1,19 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <title>TinyURI 404 Error + + + + +

NOT FOUND

+

You shouldn't be here

+Return to TinyURI + + + \ No newline at end of file diff --git a/demo/src/main/resources/public/error/429.html b/demo/src/main/resources/public/error/429.html new file mode 100644 index 00000000..8de9392f --- /dev/null +++ b/demo/src/main/resources/public/error/429.html @@ -0,0 +1,19 @@ + + + + TinyURI 429 Error + + + + +

TOO MANY REQUEST

+

Relax and try again later

+Return to TinyURI + + + \ No newline at end of file diff --git a/demo/src/main/resources/public/error/500.html b/demo/src/main/resources/public/error/500.html new file mode 100644 index 00000000..ea162d8a --- /dev/null +++ b/demo/src/main/resources/public/error/500.html @@ -0,0 +1,19 @@ + + + + TinyURI 500 Error + + + + +

SERVER ERROR

+

Ops! This is our fault

+Return to TinyURI + + + \ No newline at end of file diff --git a/demo/src/main/resources/static/css/landing-page.css b/demo/src/main/resources/static/css/landing-page.css index 41c93aac..0e9ab57e 100644 --- a/demo/src/main/resources/static/css/landing-page.css +++ b/demo/src/main/resources/static/css/landing-page.css @@ -156,6 +156,26 @@ header.masthead h1 { opacity: 0.3; } +.error { + position: absolute; + height: 100%; + width: 100%; + background-color: #712c2b; + background-size: cover; + padding-top: 7rem; + padding-bottom: 7rem; +} + +.error .overlay { + position: absolute; + background-color: #212529; + height: 100%; + width: 100%; + top: 0; + left: 0; + opacity: 0.3; +} + footer.footer { padding-top: 4rem; From 7476ae03c82f5fe3a87cabf7b53c02434aaf3917 Mon Sep 17 00:00:00 2001 From: robertoccu Date: Mon, 14 Jan 2019 08:22:23 +0100 Subject: [PATCH 109/125] Fix: QR doesn't show after error query --- demo/src/main/resources/static/js/app.js | 1 + 1 file changed, 1 insertion(+) diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index ff4b59a1..0cf23c65 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -43,6 +43,7 @@ $(document).ready( $("#shortenerResult").html( "
ERROR: \"" + $( "#urlInput").val() + "\" isn't a valid URI or name is already taken.
"); + $("#QRResult").html("
"); } }); }); From 5521def8477fd671ab6bde818d59cb2834343555 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Mon, 14 Jan 2019 09:00:54 +0100 Subject: [PATCH 110/125] Periodic check and getURI check done --- .../controller/impl/UriApiController.java | 14 ++++++- .../demo/repository/AbstractRepository.java | 26 +++++++++++++ .../demo/repository/URIRepository.java | 12 +++++- .../repository/impl/URIRepositoryImpl.java | 20 ++++++---- .../demo/schedule/checkSchedule.java | 38 +++++++++++-------- 5 files changed, 85 insertions(+), 25 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 8f0036ff..7b646a47 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -29,6 +29,8 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import java.util.Date; +import java.util.Map; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-21T05:15:43.072Z[GMT]") @@ -114,7 +116,7 @@ public ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVari String accept = request.getHeader("Accept"); CheckAlive c = new CheckAlive(); URI location = null; - + Map fechas = uriService.getAllFechas(); String redirection; URIItem item = uriService.get(id); @@ -129,11 +131,21 @@ public ResponseEntity getURI(@ApiParam(value = "",required=true) @PathVari //OK //Para esa URI, se registra la fecha actual como útima fecha en la que estuvo viva location = new URI(redirection); + uriService.removeFecha(item.getId()); + uriService.addFecha(item.getId(), new Date()); } else { //Cualquier otra cosa aparte de un código 200 significará que la URI está muerta //Se obtiene la última vez que la URI estuvo viva // -Si la diferencia entre la fecha actual y la fecha recuperada es >= K, entonces la URI se borra + long actual = System.currentTimeMillis(); + long fechaUri = fechas.get(item.getId()).getTime(); + long diff = actual - fechaUri; + long days = diff / (604800000); + if (days >= 7.0){ + uriService.remove(item.getId()); + } + return new ResponseEntity(HttpStatus.NOT_FOUND); } diff --git a/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java b/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java index 91d2aa3f..53df9a0d 100644 --- a/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/AbstractRepository.java @@ -5,6 +5,7 @@ import urlshortener.demo.exception.CannotAddEntityException; import urlshortener.demo.exception.UnknownEntityException; +import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -12,6 +13,29 @@ public class AbstractRepository> implements IReposito private long nextID = 0; private Map uris = new HashMap<>(); + private Map fechas = new HashMap<>(); + + public Map getAllUris(){ + return uris; + } + + public Map getAllFechas() { + return fechas; + } + + public void removeFecha(K hash){ + if(!fechas.containsKey(hash)){ + throw new UnknownEntityException(HttpStatus.NOT_FOUND.value(), "Cannot fetch date with uri hash " + hash); + } + fechas.remove(hash); + } + + public void addFecha(K hash, Date fecha){ + if(fechas.containsKey(hash)){ + throw new UnknownEntityException(HttpStatus.NOT_FOUND.value(), "Cannot add date with uri hash " + hash); + } + fechas.put(hash, fecha); + } @Override public void add(V uri) { @@ -20,6 +44,7 @@ public void add(V uri) { } uris.put(uri.getId(), uri); + fechas.put(uri.getId(), new Date()); nextID++; } @@ -38,6 +63,7 @@ public void remove(K hash) { throw new UnknownEntityException(HttpStatus.NOT_FOUND.value(), "Cannot fetch uri with hash " + hash); } uris.remove(hash); + fechas.remove(hash); } @Override diff --git a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java index d6de94d8..2896b413 100644 --- a/demo/src/main/java/urlshortener/demo/repository/URIRepository.java +++ b/demo/src/main/java/urlshortener/demo/repository/URIRepository.java @@ -1,10 +1,18 @@ package urlshortener.demo.repository; import urlshortener.demo.domain.URIItem; -import java.util.List; + +import java.util.Date; +import java.util.Map; public interface URIRepository extends IRepository { - List checkURI(); + Map getAllURIS(); + + Map getAllFechas(); + + void removeFecha(String id); + + void addFecha(String id, Date fecha); long getRedirectionAmount(String hash, long timeFromNow); diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index b3d86fed..32311c75 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -7,20 +7,26 @@ import urlshortener.demo.repository.AbstractRepository; import urlshortener.demo.repository.URIRepository; -import java.util.ArrayList; -import java.util.List; -import java.util.HashMap; -import java.util.Map; +import java.util.*; @Repository public class URIRepositoryImpl extends AbstractRepository implements URIRepository { + private Map stats = new HashMap<>(); @Override - public List checkURI() { - return new ArrayList<>(); + public Map getAllURIS() { + return super.getAllUris(); } - private Map stats = new HashMap<>(); + @Override + public void removeFecha(String id) { + super.removeFecha(id); + } + + @Override + public void addFecha(String id, Date fecha) { + super.addFecha(id, fecha); + } @Override public long getRedirectionAmount(String hash, long timeFromNow) { diff --git a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java index bd6ddf18..be6d5775 100644 --- a/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java +++ b/demo/src/main/java/urlshortener/demo/schedule/checkSchedule.java @@ -9,12 +9,15 @@ import urlshortener.demo.utils.CheckAlive; import java.io.IOException; -import java.util.List; +import java.util.Collection; +import java.util.Date; +import java.util.Map; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2018-11-21T05:15:43.072Z[GMT]") @Component public class checkSchedule { + private final int CHECK_RATE = 86400000; private static final Logger log = LoggerFactory.getLogger(checkSchedule.class); @@ -25,31 +28,36 @@ public checkSchedule(URIRepository uriService) { this.uriService = uriService; } - @Scheduled(fixedRate = 86400) - public void check() throws IOException { + @Scheduled(fixedRate = CHECK_RATE) + public void check() throws IOException, InterruptedException { CheckAlive c = new CheckAlive(); - //HAY QUE CAMBIAR ESTE FRAGMENTO DE CÓDIGO Y RECUPERAR LA LISTA DE LA BD REAL - List uris = uriService.checkURI(); + Map uris = uriService.getAllURIS(); + Collection soloUris = uris.values(); + Map fechas = uriService.getAllFechas(); log.info("Comienza el checkeo de las URI..."); - for (int i=0; i < uris.size(); i++){ - log.info("COMPROBANDO URI " + uris.get(i).getRedirection()); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if (c.makeRequest(uris.get(i).getRedirection()) == 200){ - log.info("La URI " + uris.get(i).getRedirection() + " está viva."); + for (URIItem i: soloUris){ + log.info("COMPROBANDO URI " + i.getRedirection()); + if (c.makeRequest(i.getRedirection()) == 200){ + log.info("La URI " + i.getRedirection() + " está viva."); //OK //Para esa URI, se registra la fecha actual como útima fecha en la que estuvo viva + uriService.removeFecha(i.getId()); + uriService.addFecha(i.getId(), new Date()); } else { - log.info("La URI " + uris.get(i).getRedirection() + " no responde."); + log.info("La URI " + i.getRedirection() + " no responde."); //Cualquier otra cosa aparte de un código 200 significará que la URI está muerta //Se obtiene la última vez que la URI estuvo viva // -Si la diferencia entre la fecha actual y la fecha recuperada es >= K, entonces la URI se borra + long actual = System.currentTimeMillis(); + long fechaUri = fechas.get(i.getId()).getTime(); + long diff = actual - fechaUri; + long days = diff / (604800000); + if (days >= 7.0){ + uriService.remove(i.getId()); + } } } } From dcb3a7cc66623158569189c3890ebfed4dbcf58f Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Mon, 14 Jan 2019 09:07:37 +0100 Subject: [PATCH 111/125] Periodic check and getURI check done --- .../demo/repository/impl/URIRepositoryImpl.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java index 32311c75..48499302 100644 --- a/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java +++ b/demo/src/main/java/urlshortener/demo/repository/impl/URIRepositoryImpl.java @@ -18,16 +18,6 @@ public Map getAllURIS() { return super.getAllUris(); } - @Override - public void removeFecha(String id) { - super.removeFecha(id); - } - - @Override - public void addFecha(String id, Date fecha) { - super.addFecha(id, fecha); - } - @Override public long getRedirectionAmount(String hash, long timeFromNow) { URIStats statsData = this.stats.get(hash); From 39e5472be48c568b458cd4df6a16cc7bef4c904e Mon Sep 17 00:00:00 2001 From: robertoccu Date: Mon, 14 Jan 2019 09:59:17 +0100 Subject: [PATCH 112/125] Implemented PUT /uri/{name} and changed PUT /uri/ to POST /uri/ --- .../urlshortener/demo/controller/UriApi.java | 18 ++++++++-- .../controller/impl/UriApiController.java | 33 +++++++++++++++---- demo/src/main/resources/static/js/app.js | 2 +- 3 files changed, 44 insertions(+), 9 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/UriApi.java b/demo/src/main/java/urlshortener/demo/controller/UriApi.java index b1f27835..b36f0ecd 100644 --- a/demo/src/main/java/urlshortener/demo/controller/UriApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/UriApi.java @@ -5,6 +5,7 @@ import org.springframework.web.bind.annotation.*; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.domain.URIUpdate; import javax.validation.Valid; @@ -21,7 +22,8 @@ public interface UriApi { produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PUT) - ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URICreate body,@ApiParam(value = "",required=true) @PathVariable("name") String name); + public ResponseEntity changeUri(@ApiParam(value = "update info", required=true ) @Valid @RequestBody URIUpdate body, + @ApiParam(value = "actual name", required=true) @PathVariable("name") String name); @ApiOperation(value = "Creates a new redirection", nickname = "createURI", notes = "Create a new URI redirection ", response = URIItem.class, tags={ "F0 - The app will short, storage and get URI's", }) @@ -32,9 +34,21 @@ public interface UriApi { @RequestMapping(value = "/uri", produces = { "application/json" }, consumes = { "application/json" }, - method = RequestMethod.PUT) + method = RequestMethod.POST) ResponseEntity createURI(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body); + @ApiOperation(value = "Creates a new redirection with a custom name", nickname = "createURIWithName", notes = "Create a new URI redirection with a custom name", response = URIItem.class, tags={ "F0 - The app will short, storage and get URI's", }) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "The URI redirection has been successfully created", response = URIItem.class), + @ApiResponse(code = 400, message = "The URI was not reachable", response = URIItem.class) + }) + @RequestMapping(value = "/uri/{name}", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.POST) + ResponseEntity createURIwithName(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body, + @ApiParam(value = "actual name", required=true) @PathVariable("name") String name); + @ApiOperation(value = "Deletes an existing URI and its content.", nickname = "deleteURI", notes = "Remove a URI redirection ", tags={ "F0 - The app will short, storage and get URI's", }) @ApiResponses(value = { diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 8f0036ff..45bdbd49 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -15,6 +15,7 @@ import urlshortener.demo.domain.QRItem; import urlshortener.demo.domain.URICreate; import urlshortener.demo.domain.URIItem; +import urlshortener.demo.domain.URIUpdate; import urlshortener.demo.exception.IncorrectHashPassException; import urlshortener.demo.exception.InvalidRequestParametersException; import urlshortener.demo.exception.UnknownEntityException; @@ -62,22 +63,36 @@ public UriApiController(ObjectMapper objectMapper, HttpServletRequest request, U this.qrService = qrService; } - public ResponseEntity changeURI(@ApiParam(value = "Optional description in *Markdown*" ,required=true ) @Valid @RequestBody URICreate body,@ApiParam(value = "",required=true) @PathVariable("name") String name) { + public ResponseEntity changeUri(@ApiParam(value = "update info", required=true ) @Valid @RequestBody URIUpdate body, + @ApiParam(value = "actual name", required=true) @PathVariable("name") String name) { String accept = request.getHeader("Accept"); + + URIItem actualUri = uriService.get(name); + URICreate uri = new URICreate().uri(actualUri.getRedirection()); + + if(!actualUri.checkHashPass(body.getHashpass())) { + throw new IncorrectHashPassException(HttpStatus.BAD_REQUEST.value(), "Given hashpass doesn't match " + actualUri.getId() + " hashpass."); + } + + return createNewUri(uri,body.getNewName()); + + } + + public ResponseEntity createNewUri(URICreate uri, String name) { CheckAlive c = new CheckAlive(); ParameterUtils.checkParameter(name); - ParameterUtils.checkParameter(body.getUri()); + ParameterUtils.checkParameter(uri.getUri()); - URIItem item = (URIItem) new URIItem().id(name).redirection(body.getUri()).hashpass(StringUtils.randomHash()); + URIItem item = (URIItem) new URIItem().id(name).redirection(uri.getUri()).hashpass(StringUtils.randomHash()); try { if (Integer.valueOf(c.makeRequest(item.getRedirection())) == 200) { uriService.add(item); // Save default QR to QRRepository if it doesn't already exist - if(!qrService.contains(body.getUri())){ + if(!qrService.contains(uri.getUri())){ QRItem qrItem = new QRItem(); - qrItem.setUri(body.getUri()); + qrItem.setUri(uri.getUri()); qrItem.convertBase64(QR_SIZE, QR_SIZE); this.qrService.add(qrItem); @@ -93,7 +108,13 @@ public ResponseEntity changeURI(@ApiParam(value = "Optional description public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body) { String accept = request.getHeader("Accept"); - return changeURI(body, Long.toHexString(uriService.getNextID())); + return createNewUri(body, Long.toHexString(uriService.getNextID())); + } + + public ResponseEntity createURIwithName(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body, + @ApiParam(value = "actual name", required=true) @PathVariable("name") String name) { + String accept = request.getHeader("Accept"); + return createNewUri(body, name); } public ResponseEntity deleteURI(@ApiParam(value = "",required=true) @PathVariable("id") String id, @RequestHeader("URIHashPass") String hashpass) { diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index 0cf23c65..8b940940 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -5,7 +5,7 @@ $(document).ready( event.preventDefault(); var name = $("#customName").val(); $.ajax({ - type: "PUT", + type: "POST", url: "/uri/" + name, contentType: "application/json", data: JSON.stringify({"uri": $("#urlInput").val()}), // access in body From fa054eed00a79a41c177981cb63bc12ec4216aac Mon Sep 17 00:00:00 2001 From: robertoccu Date: Mon, 14 Jan 2019 12:09:22 +0100 Subject: [PATCH 113/125] Changes in methods and URICreate. - URICreate now has "name" field. - Create a URI with a name now uses PUT /uri and use "name" field of URICreate. - Other: Create URI with POST /uri and Change name with PUT /uri/{name} --- .../urlshortener/demo/controller/UriApi.java | 7 ++--- .../controller/impl/UriApiController.java | 7 ++--- .../urlshortener/demo/domain/URICreate.java | 31 ++++++++++++++++--- demo/src/main/resources/static/js/app.js | 8 +++-- .../UriApiControllerIntegrationTest.java | 10 +++--- .../demo/domain/URICreateTest.java | 6 ++-- .../java/urlshortener/demo/web/UriTests.java | 17 +++++----- 7 files changed, 53 insertions(+), 33 deletions(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/UriApi.java b/demo/src/main/java/urlshortener/demo/controller/UriApi.java index b36f0ecd..5da840b2 100644 --- a/demo/src/main/java/urlshortener/demo/controller/UriApi.java +++ b/demo/src/main/java/urlshortener/demo/controller/UriApi.java @@ -42,12 +42,11 @@ public ResponseEntity changeUri(@ApiParam(value = "update info", requir @ApiResponse(code = 201, message = "The URI redirection has been successfully created", response = URIItem.class), @ApiResponse(code = 400, message = "The URI was not reachable", response = URIItem.class) }) - @RequestMapping(value = "/uri/{name}", + @RequestMapping(value = "/uri", produces = { "application/json" }, consumes = { "application/json" }, - method = RequestMethod.POST) - ResponseEntity createURIwithName(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body, - @ApiParam(value = "actual name", required=true) @PathVariable("name") String name); + method = RequestMethod.PUT) + ResponseEntity createURIwithName(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body); @ApiOperation(value = "Deletes an existing URI and its content.", nickname = "deleteURI", notes = "Remove a URI redirection ", tags={ "F0 - The app will short, storage and get URI's", }) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java index 45bdbd49..1a5a3bf1 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/UriApiController.java @@ -78,7 +78,7 @@ public ResponseEntity changeUri(@ApiParam(value = "update info", requir } - public ResponseEntity createNewUri(URICreate uri, String name) { + private ResponseEntity createNewUri(URICreate uri, String name) { CheckAlive c = new CheckAlive(); ParameterUtils.checkParameter(name); @@ -111,10 +111,9 @@ public ResponseEntity createURI(@ApiParam(value = "URI" ,required=true return createNewUri(body, Long.toHexString(uriService.getNextID())); } - public ResponseEntity createURIwithName(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body, - @ApiParam(value = "actual name", required=true) @PathVariable("name") String name) { + public ResponseEntity createURIwithName(@ApiParam(value = "URI" ,required=true ) @Valid @RequestBody URICreate body) { String accept = request.getHeader("Accept"); - return createNewUri(body, name); + return createNewUri(body, body.getName()); } public ResponseEntity deleteURI(@ApiParam(value = "",required=true) @PathVariable("id") String id, @RequestHeader("URIHashPass") String hashpass) { diff --git a/demo/src/main/java/urlshortener/demo/domain/URICreate.java b/demo/src/main/java/urlshortener/demo/domain/URICreate.java index 2ac07925..b5a35661 100644 --- a/demo/src/main/java/urlshortener/demo/domain/URICreate.java +++ b/demo/src/main/java/urlshortener/demo/domain/URICreate.java @@ -17,6 +17,9 @@ public class URICreate { @JsonProperty("uri") private String uri = null; + @JsonProperty("name") + private String name = ""; + public URICreate uri(String uri) { this.uri = uri; return this; @@ -28,8 +31,6 @@ public URICreate uri(String uri) { **/ @ApiModelProperty(example = "https://google.es/", required = true, value = "") @NotNull - - public String getUri() { return uri; } @@ -38,6 +39,25 @@ public void setUri(String uri) { this.uri = uri; } + /** + * Get uri + * @return uri + **/ + @ApiModelProperty(example = "https://google.es/", required = true, value = "") + @NotNull + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public URICreate name(String name) { + this.name = name; + return this; + } + @Override public boolean equals(java.lang.Object o) { @@ -48,20 +68,21 @@ public boolean equals(java.lang.Object o) { return false; } URICreate urICreate = (URICreate) o; - return Objects.equals(this.uri, urICreate.uri); + return Objects.equals(this.uri, urICreate.uri) && Objects.equals(this.name, urICreate.name); } @Override public int hashCode() { - return Objects.hash(uri); + return Objects.hash(uri,name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class URICreate {\n"); - + sb.append(" uri: ").append(toIndentedString(uri)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index 8b940940..efe35ad2 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -4,11 +4,13 @@ $(document).ready( function (event) { event.preventDefault(); var name = $("#customName").val(); + var type = ""; + if ($("#customName").val() === "") {type = "POST"} else {type = "PUT"} $.ajax({ - type: "POST", - url: "/uri/" + name, + type: type, + url: "/uri", contentType: "application/json", - data: JSON.stringify({"uri": $("#urlInput").val()}), // access in body + data: JSON.stringify({"uri": $("#urlInput").val(), "name" : name}), // access in body success: function (msg) { $("#shortenerResult").html( "
- + -
+ +
+
+
+
+
+

Check availability of your URI

+
+
+
+
+ + + After "http://tinyuri.xyz/". +
+ +
+
+
+
+
+
+
+
+
+
+
+
diff --git a/demo/src/main/resources/static/js/app.js b/demo/src/main/resources/static/js/app.js index efe35ad2..ed4ebf98 100755 --- a/demo/src/main/resources/static/js/app.js +++ b/demo/src/main/resources/static/js/app.js @@ -112,4 +112,21 @@ $(document).ready( } }); }); + + $("#check").submit( + function (event) { + event.preventDefault(); + $.ajax({ + type: "GET", + url: "/check/" + $("#checkUriInput").val(), + success: function () { + $("#checkUriResult").html( + "

URI is available

"); + }, + error: function () { + $("#checkUriResult").html( + "
URI not available.
"); + } + }); + }); }); \ No newline at end of file diff --git a/demo/src/main/resources/static/stats.html b/demo/src/main/resources/static/stats.html index d58a799a..bd5e582b 100644 --- a/demo/src/main/resources/static/stats.html +++ b/demo/src/main/resources/static/stats.html @@ -47,7 +47,9 @@
+

Stats of TinyURI services

+

1.025.485

@@ -90,5 +92,16 @@

Stats of TinyURI services

+ +
+
+
+
+

Created by Blue-Bash at Unizar.

+
+
+
+
+ \ No newline at end of file From 60fb073fb22b94608d3d8ff85979c8342a5100c2 Mon Sep 17 00:00:00 2001 From: Alberto <697589@unizar.es> Date: Mon, 14 Jan 2019 22:07:13 +0100 Subject: [PATCH 119/125] 404 code in GET /check/id added (before this, it returned 200 or any other code, but not specifically 404 in the case that the uri was dead) --- .../urlshortener/demo/controller/impl/CheckApiController.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java index 13afec26..d913f4db 100644 --- a/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java +++ b/demo/src/main/java/urlshortener/demo/controller/impl/CheckApiController.java @@ -46,8 +46,10 @@ public ResponseEntity checkURI(@ApiParam(value = "",required=true) @PathVa try { HttpStatus httpStatus = HttpStatus.valueOf(c.makeRequest(uri.getRedirection())); + if (httpStatus != HttpStatus.OK) { + return new ResponseEntity(HttpStatus.NOT_FOUND); + } return new ResponseEntity(httpStatus); - } catch (IOException e) { throw new InvalidRequestParametersException(HttpStatus.BAD_REQUEST.value(), "There was a problem with the parameters."); } From 569915bf5b19ddee15341c298320e4648588c8f9 Mon Sep 17 00:00:00 2001 From: Roberto CCU Date: Mon, 14 Jan 2019 23:31:27 +0100 Subject: [PATCH 120/125] First commit for WebSocket implementation on Front-End --- demo/src/main/resources/static/js/stats.js | 54 ++++++++++++++++++++++ demo/src/main/resources/static/stats.html | 21 +++++---- 2 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 demo/src/main/resources/static/js/stats.js diff --git a/demo/src/main/resources/static/js/stats.js b/demo/src/main/resources/static/js/stats.js new file mode 100644 index 00000000..629d4888 --- /dev/null +++ b/demo/src/main/resources/static/js/stats.js @@ -0,0 +1,54 @@ +var stompClient = null; + +function setConnected(connected) { + if (connected) { + $("#uriStats").show(); + $("#disconnectAlert").hide(); + } + else { + $("#uriStats").hide(); + $("#disconnectAlert").show(); + } + $("#greetings").html(""); +} + +function connect() { + var socket = new SockJS('/gs-guide-websocket'); // TODO: Change "/gs-guide-websocket" + stompClient = Stomp.over(socket); + stompClient.connect({}, function (frame) { + setConnected(true); + console.log('Connected: ' + frame); + stompClient.subscribe('/topic/greetings', function (greeting) { // TODO: Change "/topic/greetings" + updateStats(JSON.parse(greeting.body).content); + }); + }); +} + +function disconnect() { + if (stompClient !== null) { + stompClient.disconnect(); + } + setConnected(false); + console.log("Disconnected"); +} + +function updateStats(stats) { // TODO: Implement with stats JSON values + $("#accessedURI").val("accURI"); + + $("#shortenedURI").val("shoURI"); + $("#deletedURI").val("delURI"); + $("#workingURI").val("worURI"); + + $("#generatedQR").val("genQR"); + $("#deleteQR").val("delQR"); + $("#workingQR").val("worQR"); +} + +$(function () { + $("form").on('submit', function (e) { + e.preventDefault(); + }); + $( "#connect" ).click(function() { connect(); }); + $( "#disconnect" ).click(function() { disconnect(); }); + $( "#send" ).click(function() { sendName(); }); +}); \ No newline at end of file diff --git a/demo/src/main/resources/static/stats.html b/demo/src/main/resources/static/stats.html index bd5e582b..e88f1051 100644 --- a/demo/src/main/resources/static/stats.html +++ b/demo/src/main/resources/static/stats.html @@ -21,12 +21,16 @@ + + +