├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── docker │ ├── Dockerfile │ ├── docker-compose.yml │ ├── elasticsearch │ │ └── elasticsearch.yml │ └── wrapper.sh ├── java │ └── com │ │ └── userCrud │ │ ├── Application.java │ │ ├── config │ │ ├── AppConfig.java │ │ └── SwaggerConfig.java │ │ ├── controller │ │ ├── IndexController.java │ │ └── UserController.java │ │ ├── dao │ │ ├── AbstractDAO.java │ │ ├── ICrudDAO.java │ │ └── UserDAO.java │ │ ├── dto │ │ ├── SearchDTO.java │ │ └── UserSearchDTO.java │ │ ├── model │ │ ├── AbstractTimeStampModel.java │ │ ├── IModel.java │ │ └── User.java │ │ └── service │ │ ├── ICrudService.java │ │ └── UserService.java └── resources │ ├── application.yml │ ├── logback.xml │ └── schema-mysql.sql └── test ├── java └── com │ └── userCrud │ └── ApplicationTest.java └── resources └── logback-test.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.sw? 2 | .#* 3 | *# 4 | *~ 5 | .DS_Store 6 | .classpath 7 | .project 8 | .settings 9 | bin 10 | build 11 | target 12 | dependency-reduced-pom.xml 13 | *.sublime-* 14 | /scratch 15 | /data/* 16 | .gradle 17 | README.html 18 | .idea 19 | *.iml 20 | *.log 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot API 2 | 3 | This is a simple API showing how to properly create and document an API. 4 | 5 | ## Tech Stack 6 | 7 | This project is built with: 8 | 9 | - Java 8 -> Language 10 | - Spring Boot -> Main Framework 11 | - MySql -> Main Database 12 | - H2(In Memory DB) -> Test Database 13 | - Logback -> Logging Framework 14 | - ElasticSearch -> NoSQL Database used to store Logs asynchronously 15 | 16 | ## Requirements 17 | 18 | To run this project you'll need to download the following: 19 | 20 | - [Java](https://www.java.com/en/download/) 21 | - [Gradle](https://gradle.org/install) 22 | - [Docker](https://docs.docker.com/engine/installation/) 23 | 24 | And if you want to run it stand alone you'll need to download [MySQL](https://www.mysql.com/downloads/) and configure the `application.properties` configuration file to point to the right db configuration(port, host, dbName, dbUser and dbPass) 25 | 26 | ## Running the Project With Docker 27 | 28 | After having all the requirements, the first step is to generate the docker Image. To generate the docker image, go to the root of the project and run 29 | 30 | - `$ ./gradlew buildDocker` 31 | 32 | Then you'll need to run the `docker.compose.yml` file that's on the directory `src/main/docker` through the following command: 33 | 34 | - `$ cd src/main/docker/` 35 | - `$ docker-compose up` 36 | 37 | After that you'll be able to start. 38 | 39 | ### Testing 40 | 41 | By default, gradle run all tests when you build it. But you can use the following command to run it: 42 | 43 | - `$ gradle test` 44 | 45 | You can also use [JUnit](http://junit.org/junit4/) if you prefer. 46 | 47 | ### Api Documentation (Swagger) 48 | 49 | - If you access the root URL (` http://localhost:8080/ `) you'll be redirected to the API Documentation 50 | - To access the api documentation directly, run the application and access : ` http://localhost:8080/swagger-ui.html ` 51 | 52 | - Through this documentation, you'll be able to make requests, as you'll see on the next topic. 53 | 54 | ### Endpoints 55 | 56 | Currently it contains a basic crud of a User. 57 | 58 | #### Adding a User (POST http://localhost:8080/users). 59 | 60 | You can add a user doing a Post, here's an example using curl : 61 | 62 | - `curl -H "Content-Type: application/json" -X POST -d '{"name":"First User","role":"admin"}' http://localhost:8080/users` 63 | - `curl -H "Content-Type: application/json" -X POST -d '{"name":"Second User","role":"admin"}' http://localhost:8080/users` 64 | - `curl -H "Content-Type: application/json" -X POST -d '{"name":"Third User","role":"marketing"}' http://localhost:8080/users` 65 | - `curl -H "Content-Type: application/json" -X POST -d '{"name":"Fourth User","role":"marketing"}' http://localhost:8080/users` 66 | 67 | #### Getting all Users (GET http://localhost:8080/users). 68 | 69 | You can get all users doing a Get. It also works with multiple query parameters(examples: `/users?role=admin`, `/users?role=admin,marketing`, `/users?id=1,4&role=admin,marketing`). 70 | 71 | Here are some examples using curl : 72 | 73 | - `curl -X GET http://localhost:8080/users` 74 | - `curl -X GET http://localhost:8080/users?role=admin` 75 | - `curl -X GET http://localhost:8080/users?role=admin,marketing` 76 | - `curl -X GET http://localhost:8080/users?id=1,3,4&role=admin,marketing` 77 | 78 | #### Updating a User (PUT http://localhost:8080/users/ID_OF_THE_USER). 79 | 80 | Here's an example on how to change the property `name` of the user with the `id=1`: 81 | 82 | - `curl -H "Content-Type: application/json" -X PUT -d '{"name":"First User"}' http://localhost:8080/users/1` 83 | 84 | #### Deleting a User (PUT http://localhost:8080/users/ID_OF_THE_USER). 85 | 86 | Here's an example on how to delete the user with the `id=4`: 87 | 88 | - `curl -X DELETE http://localhost:8080/users/4` 89 | 90 | 91 | ### Accessing the Logs(Elasticsearch) 92 | 93 | Through an Async Appender used on the spring Logback solution(Appender better defined on the file `src/main/resources/logback.xml`), we send the logs to Elasticsearch.The logs coming from the main api are defined with the index name `logs-YYYY-MM-DD`. 94 | By default(defined on the docker-compose.yml file), we can see the elasticsearch through the following links: 95 | 96 | - See all indexes available: `http://localhost:9200/_cat/indices?v` 97 | 98 | - See all record from the main api logs : `http://localhost:9200/logs-2017-06-13/_search?pretty=true&q=*:*&sort=@timestamp:desc`. You can also sort and filter through whatever field you have available. For better understand Elasticsearch take a look at the [Elasticsearch Documentation](https://www.elastic.co/guide/en/elasticsearch/reference/5.0/index.html). Don't forget to change the `YYYY-MM-DD` on the Url path according to the current day. 99 | 100 | 101 | ## Commands to run without Docker (and through the terminal) 102 | 103 | 104 | - To build the project run from the root folder of the project the following: `$ gradle build` 105 | - To run the project do : `$ java -jar build/libs/user-crud-0.1.0.jar`. Be aware that the jar name is defined inside the gradle.build script and might be able to change. 106 | - To run the tests: `$ gradle test` 107 | 108 | ## Access the api 109 | 110 | After having the project running, you can access the api through [curl](https://curl.haxx.se/download.html) or any other http handler you prefer. 111 | 112 | It runs by default on the `http://localhost:8080/`. 113 | 114 | 115 | ## Things to improve/do 116 | 117 | - Improve the logs: Instead of only having Elasticsearch populated with the logs, we could use the ELK(Elasticsearch, Logstash and Kibana) solution to provide a better visualization of logs, and perhaps metrics. 118 | 119 | - Populate Elasticsearch with posts as well and then point the user to get data from Elasticsearch and use MySql only to Write. I believe this approach improves the performance quite a lot. 120 | 121 | - Use UUID instead of Long as the main ID of all models. 122 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | dependencies { 6 | classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE") 7 | classpath("se.transmode.gradle:gradle-docker:1.2") 8 | } 9 | } 10 | 11 | apply plugin: 'java' 12 | apply plugin: 'eclipse' 13 | apply plugin: 'idea' 14 | apply plugin: 'org.springframework.boot' 15 | apply plugin: 'docker' 16 | 17 | task copyWrapper(type: Copy) { 18 | from("src/main/docker/wrapper.sh") 19 | into("build/docker") 20 | } 21 | 22 | task buildDocker(type: Docker, dependsOn: build) { 23 | dependsOn copyWrapper 24 | push = false 25 | applicationName = "marcogbarcellos/user-crud" 26 | dockerfile = file('src/main/docker/Dockerfile') 27 | doFirst { 28 | copy { 29 | from jar 30 | into stageDir 31 | } 32 | } 33 | } 34 | 35 | jar { 36 | baseName = 'user-crud' 37 | version = '0.1.0' 38 | } 39 | 40 | repositories { 41 | mavenCentral() 42 | } 43 | 44 | sourceCompatibility = 1.8 45 | targetCompatibility = 1.8 46 | 47 | dependencies { 48 | 49 | compile("org.springframework.boot:spring-boot-starter-web") 50 | compile("org.springframework.boot:spring-boot-starter-actuator") 51 | compile("org.springframework.boot:spring-boot-starter-data-jpa") 52 | compile("mysql:mysql-connector-java") 53 | compile("io.springfox:springfox-swagger2:2.7.0") 54 | compile("io.springfox:springfox-swagger-ui:2.7.0") 55 | compile("com.internetitem:logback-elasticsearch-appender:1.5") 56 | // tag::test[] 57 | testCompile("junit:junit") 58 | testCompile("com.h2database:h2") 59 | testCompile("org.springframework.boot:spring-boot-starter-test") 60 | // end::test[] 61 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcogbarcellos/springboot-crud-mysql-elastic-docker/909767ace46f6b18c59c12f9d075b88c8e177464/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Jun 09 16:48:04 EDT 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 165 | if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then 166 | cd "$(dirname "$0")" 167 | fi 168 | 169 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 170 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'userCrud' 2 | -------------------------------------------------------------------------------- /src/main/docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM java:8 2 | ADD user-crud-0.1.0.jar app.jar 3 | ADD wrapper.sh wrapper.sh 4 | RUN bash -c 'chmod +x /wrapper.sh' 5 | RUN bash -c 'touch /app.jar' 6 | ENTRYPOINT ["/bin/bash", "/wrapper.sh"] -------------------------------------------------------------------------------- /src/main/docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2.1' 2 | 3 | services: 4 | elasticsearch: 5 | image: elasticsearch:5.4 6 | volumes: 7 | - ./elasticsearch/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml 8 | ports: 9 | - "9200:9200" 10 | - "9300:9300" 11 | environment: 12 | ES_JAVA_OPTS: "-Xmx256m -Xms256m" 13 | 14 | mysql: 15 | image: mysql:5.7 16 | environment: 17 | - MYSQL_ROOT_PASSWORD=p4SSW0rd 18 | - MYSQL_DATABASE=usercrud 19 | - MYSQL_USER=dbuser 20 | - MYSQL_PASSWORD=dbp4ss 21 | 22 | user-crud: 23 | image: marcogbarcellos/user-crud:latest 24 | depends_on: 25 | - mysql 26 | - elasticsearch 27 | ports: 28 | - 8080:8080 29 | environment: 30 | - DATABASE_HOST=mysql 31 | - DATABASE_USER=dbuser 32 | - DATABASE_PASSWORD=dbp4ss 33 | - DATABASE_NAME=usercrud 34 | - DATABASE_PORT=3306 35 | - ELASTIC_SEARCH_URL=http://elasticsearch:9200/_bulk 36 | 37 | -------------------------------------------------------------------------------- /src/main/docker/elasticsearch/elasticsearch.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ## Default Elasticsearch configuration from elasticsearch-docker. 3 | ## from https://github.com/elastic/elasticsearch-docker/blob/master/build/elasticsearch/elasticsearch.yml 4 | # 5 | cluster.name: "docker-cluster" 6 | network.host: 0.0.0.0 7 | 8 | # minimum_master_nodes need to be explicitly set when bound on a public IP 9 | # set to 1 to allow single node clusters 10 | # Details: https://github.com/elastic/elasticsearch/pull/17288 11 | discovery.zen.minimum_master_nodes: 1 12 | 13 | ## Use single node discovery in order to disable production mode and avoid bootstrap checks 14 | ## see https://www.elastic.co/guide/en/elasticsearch/reference/current/bootstrap-checks.html 15 | discovery.type: single-node 16 | 17 | ## Disable X-Pack 18 | ## see https://www.elastic.co/guide/en/x-pack/current/xpack-settings.html 19 | ## https://www.elastic.co/guide/en/x-pack/current/installing-xpack.html#xpack-enabling 20 | # 21 | #xpack.security.enabled: false 22 | #xpack.monitoring.enabled: false 23 | #xpack.ml.enabled: false 24 | #xpack.graph.enabled: false 25 | #xpack.watcher.enabled: false 26 | -------------------------------------------------------------------------------- /src/main/docker/wrapper.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while ! exec 6<>/dev/tcp/${DATABASE_HOST}/${DATABASE_PORT}; do 4 | echo "Trying to connect to MySQL at ${DATABASE_HOST}:${DATABASE_PORT}..." 5 | sleep 10 6 | done 7 | 8 | java -Djava.security.egd=file:/dev/./urandom -Dspring.profiles.active=container -jar /app.jar -------------------------------------------------------------------------------- /src/main/java/com/userCrud/Application.java: -------------------------------------------------------------------------------- 1 | package com.userCrud; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 7 | 8 | @SpringBootApplication 9 | @EnableSwagger2 10 | public class Application { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(Application.class, args); 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /src/main/java/com/userCrud/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.scheduling.annotation.EnableAsync; 5 | 6 | @Configuration 7 | @EnableAsync 8 | public class AppConfig { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.config; 2 | 3 | 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | import static springfox.documentation.builders.PathSelectors.regex; 8 | 9 | import springfox.documentation.builders.ApiInfoBuilder; 10 | import springfox.documentation.builders.RequestHandlerSelectors; 11 | import springfox.documentation.service.ApiInfo; 12 | import springfox.documentation.service.Contact; 13 | import springfox.documentation.spi.DocumentationType; 14 | import springfox.documentation.spring.web.plugins.Docket; 15 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 16 | 17 | @Configuration 18 | @EnableSwagger2 19 | public class SwaggerConfig { 20 | @Bean 21 | public Docket productApi() { 22 | 23 | return new Docket(DocumentationType.SWAGGER_2) 24 | .select() 25 | .apis(RequestHandlerSelectors.basePackage("com.userCrud.controller")) 26 | .paths(regex("/user.*")) 27 | .build() 28 | .apiInfo(apiInfo()); 29 | } 30 | private ApiInfo apiInfo() { 31 | return new ApiInfoBuilder() 32 | .title("User API Documentation") 33 | .description("Spring Boot REST Explorer - Swagger") 34 | .contact(new Contact("Marco Barcellos", "https://github.com/marcogbarcellos", "marcogbarcellos@gmail.com")) 35 | .version("0.1") 36 | .build(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/controller/IndexController.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.controller; 2 | 3 | 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | 10 | @Controller 11 | public class IndexController { 12 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 13 | @RequestMapping(value = "", method = RequestMethod.GET) 14 | public String index(){ 15 | logger.info("Redirecting to Swagger Documentation page"); 16 | return "redirect:swagger-ui.html"; 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/com/userCrud/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.controller; 2 | import java.util.List; 3 | 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpHeaders; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.DeleteMapping; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.PutMapping; 15 | import org.springframework.web.bind.annotation.RequestBody; 16 | import org.springframework.web.bind.annotation.RequestMapping; 17 | import org.springframework.web.bind.annotation.ResponseBody; 18 | import org.springframework.web.bind.annotation.RestController; 19 | import org.springframework.web.util.UriComponentsBuilder; 20 | 21 | import com.userCrud.dto.UserSearchDTO; 22 | import com.userCrud.model.User; 23 | import com.userCrud.service.ICrudService; 24 | 25 | import io.swagger.annotations.Api; 26 | import io.swagger.annotations.ApiImplicitParam; 27 | import io.swagger.annotations.ApiImplicitParams; 28 | import io.swagger.annotations.ApiOperation; 29 | import io.swagger.annotations.ApiResponse; 30 | import io.swagger.annotations.ApiResponses; 31 | 32 | @RestController 33 | @RequestMapping("users") 34 | @Api(value="userCrud", description="User operations(CRUD)") 35 | public class UserController { 36 | 37 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 38 | 39 | @Autowired 40 | private ICrudService userService; 41 | 42 | 43 | @ApiOperation(value = "Find a specific user through Id", response = User.class) 44 | @ApiResponses(value = { 45 | @ApiResponse(code = 200, message = "Success", response = User.class), 46 | @ApiResponse(code = 400, message = "Bad Request"), 47 | @ApiResponse(code = 404, message = "Not Found"), 48 | @ApiResponse(code = 403, message = "Forbidden"), 49 | @ApiResponse(code = 409, message = "Conflict"), 50 | @ApiResponse(code = 500, message = "Failure")}) 51 | @GetMapping("/{id}") 52 | public ResponseEntity getUserById(@PathVariable("id") Long id) { 53 | User user = userService.getById(id); 54 | if (user != null) { 55 | logger.info("User with Id "+id+" found"); 56 | return new ResponseEntity(user, HttpStatus.OK); 57 | } 58 | logger.warn("User with Id "+id+" NOT found"); 59 | return new ResponseEntity(HttpStatus.NOT_FOUND); 60 | } 61 | 62 | @ApiOperation(value = "Find all users(And filter)", response = User[].class) 63 | @ApiImplicitParams({ 64 | @ApiImplicitParam(name = "id", value = "Users ids", required = false, dataType = "string", paramType = "query"), 65 | @ApiImplicitParam(name = "name", value = "Users names", required = false, dataType = "string", paramType = "query"), 66 | @ApiImplicitParam(name = "role", value = "Users roles", required = false, dataType = "string", paramType = "query") 67 | }) 68 | @ApiResponses(value = { 69 | @ApiResponse(code = 200, message = "Success", response = User.class), 70 | @ApiResponse(code = 400, message = "Bad Request"), 71 | @ApiResponse(code = 401, message = "Unauthorized"), 72 | @ApiResponse(code = 403, message = "Forbidden"), 73 | @ApiResponse(code = 409, message = "Conflict"), 74 | @ApiResponse(code = 500, message = "Failure")}) 75 | @GetMapping() 76 | @ResponseBody 77 | public ResponseEntity> getAllUsers(UserSearchDTO dto) { 78 | logger.info("Getting users throught SearchDTO: "+dto); 79 | List list = userService.getAll(dto); 80 | return new ResponseEntity>(list, HttpStatus.OK); 81 | } 82 | 83 | @ApiOperation(value = "Insert a new user") 84 | @ApiResponses(value = { 85 | @ApiResponse(code = 201, message = "Success"), 86 | @ApiResponse(code = 400, message = "Bad Request"), 87 | @ApiResponse(code = 403, message = "Forbidden"), 88 | @ApiResponse(code = 409, message = "Conflict"), 89 | @ApiResponse(code = 500, message = "Failure")}) 90 | @PostMapping() 91 | public ResponseEntity addUser(@RequestBody User user, UriComponentsBuilder builder) { 92 | boolean flag = userService.add(user); 93 | if (flag == false) { 94 | logger.error("User not inserted"); 95 | return new ResponseEntity(HttpStatus.CONFLICT); 96 | } 97 | logger.info("User inserted succesfully"); 98 | HttpHeaders headers = new HttpHeaders(); 99 | headers.setLocation(builder.path("/user/{id}").buildAndExpand(user.getId()).toUri()); 100 | return new ResponseEntity(headers, HttpStatus.CREATED); 101 | } 102 | 103 | @ApiOperation(value = "Update an existing user through Id") 104 | @ApiResponses(value = { 105 | @ApiResponse(code = 200, message = "Success", response = User.class), 106 | @ApiResponse(code = 400, message = "Bad Request"), 107 | @ApiResponse(code = 403, message = "Forbidden"), 108 | @ApiResponse(code = 404, message = "Not Found"), 109 | @ApiResponse(code = 409, message = "Conflict"), 110 | @ApiResponse(code = 500, message = "Failure")}) 111 | @PutMapping("/{id}") 112 | public ResponseEntity updateUser(@PathVariable("id") Long id, @RequestBody User user) { 113 | user.setId(id); 114 | user = userService.update(user); 115 | if ( user != null ) { 116 | logger.info("User edited successfully:"+user); 117 | return new ResponseEntity(user, HttpStatus.OK); 118 | } 119 | logger.warn("User with id not found"); 120 | return new ResponseEntity(HttpStatus.NOT_FOUND); 121 | } 122 | 123 | @ApiOperation(value = "Delete an existing user through Id") 124 | @ApiResponses(value = { 125 | @ApiResponse(code = 204, message = "Success"), 126 | @ApiResponse(code = 400, message = "Bad Request"), 127 | @ApiResponse(code = 403, message = "Forbidden"), 128 | @ApiResponse(code = 404, message = "Not Found"), 129 | @ApiResponse(code = 409, message = "Conflict"), 130 | @ApiResponse(code = 500, message = "Failure")}) 131 | @DeleteMapping("/{id}") 132 | public ResponseEntity deleteUser(@PathVariable("id") Long id) { 133 | logger.info("Deleting user with id '"+id+"'"); 134 | boolean userDeleted = userService.delete(id); 135 | if ( userDeleted ) { 136 | return new ResponseEntity(HttpStatus.NO_CONTENT); 137 | } 138 | return new ResponseEntity(HttpStatus.NOT_FOUND); 139 | } 140 | 141 | } -------------------------------------------------------------------------------- /src/main/java/com/userCrud/dao/AbstractDAO.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.dao; 2 | 3 | import java.lang.reflect.ParameterizedType; 4 | import java.util.List; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.PersistenceContext; 8 | 9 | import com.userCrud.model.IModel; 10 | 11 | public abstract class AbstractDAO implements ICrudDAO { 12 | 13 | @PersistenceContext 14 | protected EntityManager entityManager; 15 | 16 | protected Class classType; 17 | 18 | @SuppressWarnings("unchecked") 19 | public AbstractDAO() { 20 | classType = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; 21 | } 22 | 23 | @Override 24 | public T getById(long id) { 25 | T obj = entityManager.find(classType, id); 26 | return obj != null ? obj: null; 27 | } 28 | 29 | @Override 30 | public void add(T obj) { 31 | entityManager.persist(obj); 32 | } 33 | 34 | @Override 35 | public T update(T obj) { 36 | if ( getById(obj.getId()) != null ) { 37 | return (T) entityManager.merge(obj); 38 | } 39 | return null; 40 | } 41 | 42 | @Override 43 | public boolean delete(long id) { 44 | T objToRemov = getById(id); 45 | if ( objToRemov != null ) { 46 | objToRemov.setActivated(false); 47 | entityManager.merge(objToRemov); 48 | return true; 49 | } 50 | return false; 51 | } 52 | 53 | @SuppressWarnings("unchecked") 54 | @Override 55 | public List getAll() { 56 | return entityManager.createQuery("Select t from " + classType.getSimpleName() + " t").getResultList(); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/dao/ICrudDAO.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.dao; 2 | 3 | import java.util.List; 4 | 5 | import com.userCrud.dto.SearchDTO; 6 | import com.userCrud.model.IModel; 7 | 8 | public interface ICrudDAO { 9 | 10 | T getById(long id); 11 | void add(T obj); 12 | T update(T obj); 13 | boolean delete(long id); 14 | List getAll(); 15 | List getAllWithFilter(SearchDTO dto); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/dao/UserDAO.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.dao; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.PersistenceContext; 8 | import javax.persistence.Query; 9 | import javax.transaction.Transactional; 10 | 11 | import org.springframework.stereotype.Repository; 12 | 13 | import com.userCrud.dto.SearchDTO; 14 | import com.userCrud.dto.UserSearchDTO; 15 | import com.userCrud.model.User; 16 | 17 | @Transactional 18 | @Repository 19 | public class UserDAO extends AbstractDAO{ 20 | 21 | @PersistenceContext 22 | private EntityManager entityManager; 23 | 24 | @Override 25 | public User getById(long userId) { 26 | User user = entityManager.find(User.class, userId); 27 | return ( user != null && user.getActivated() ) ? user : null; 28 | } 29 | 30 | @Override 31 | public void add(User user) { 32 | user.setActivated(true); 33 | entityManager.persist(user); 34 | } 35 | 36 | @Override 37 | public User update(User user) { 38 | User userToUpdate = getById(user.getId()); 39 | if ( userToUpdate != null && user.getName() != null ) { 40 | userToUpdate.setName(user.getName()); 41 | } 42 | if ( userToUpdate != null && user.getRole() != null ) { 43 | userToUpdate.setRole(user.getRole()); 44 | } 45 | return (User) entityManager.merge(userToUpdate); 46 | } 47 | 48 | @Override 49 | public boolean delete(long userId) { 50 | User userToRemove = getById(userId); 51 | if ( userToRemove != null ) { 52 | userToRemove.setActivated(false); 53 | entityManager.merge(userToRemove); 54 | return true; 55 | } 56 | return false; 57 | } 58 | 59 | @SuppressWarnings("unchecked") 60 | @Override 61 | public List getAllWithFilter(SearchDTO dto) { 62 | UserSearchDTO userDto = (UserSearchDTO) dto; 63 | 64 | String hql = " FROM User as u WHERE u.activated=true "; 65 | 66 | //validating and adding parameters(if they exist) 67 | if ( userDto.getId() != null && userDto.getId().length > 0 ) { 68 | hql += " AND u.id in (:ids) "; 69 | } 70 | if ( userDto.getName() != null && userDto.getName().length > 0 ) { 71 | hql += " AND u.name in (:names) "; 72 | } 73 | if ( userDto.getRole() != null && userDto.getRole().length > 0 ) { 74 | hql += " AND u.role in (:roles) "; 75 | } 76 | 77 | hql += " ORDER BY u.updatedAt DESC"; 78 | Query query = entityManager.createQuery(hql); 79 | //setting query arguments after having it defined 80 | if ( userDto.getId() != null && userDto.getId().length > 0 ) { 81 | hql += " AND u.id in (:ids) "; 82 | query.setParameter("ids", Arrays.asList(userDto.getId())); 83 | } 84 | if ( userDto.getName() != null && userDto.getName().length > 0 ) { 85 | query.setParameter("names", Arrays.asList(userDto.getName())); 86 | } 87 | if ( userDto.getRole() != null && userDto.getRole().length > 0 ) { 88 | query.setParameter("roles", Arrays.asList(userDto.getRole())); 89 | } 90 | 91 | return (List) query.getResultList(); 92 | } 93 | 94 | public boolean userExists(String title, String role) { 95 | String hql = "FROM User as u WHERE u.name = ? and u.role= ?"; 96 | int count = entityManager.createQuery(hql).setParameter(1, title) 97 | .setParameter(2, role).getResultList().size(); 98 | return count > 0 ? true : false; 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/dto/SearchDTO.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.dto; 2 | 3 | public interface SearchDTO { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/dto/UserSearchDTO.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.dto; 2 | 3 | /** 4 | * This Object is used to transport/validate information from the http requests 5 | * to ensure that only valid information can be persisted. 6 | */ 7 | public final class UserSearchDTO implements SearchDTO { 8 | 9 | private Long[] id; 10 | 11 | private String[] name; 12 | 13 | private String[] role; 14 | 15 | public Long[] getId() { 16 | return id; 17 | } 18 | 19 | public void setId(Long[] id) { 20 | this.id = id; 21 | } 22 | 23 | public String[] getName() { 24 | return name; 25 | } 26 | 27 | public void setName(String[] name) { 28 | this.name = name; 29 | } 30 | 31 | public String[] getRole() { 32 | return role; 33 | } 34 | 35 | public void setRole(String[] role) { 36 | this.role = role; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return "User DTO{" + 42 | "id=" + id + 43 | ", name=" + name + 44 | ", role=" + role + 45 | '}'; 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /src/main/java/com/userCrud/model/AbstractTimeStampModel.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.MappedSuperclass; 11 | import javax.persistence.PrePersist; 12 | import javax.persistence.PreUpdate; 13 | 14 | import io.swagger.annotations.ApiModelProperty; 15 | 16 | @MappedSuperclass 17 | @SuppressWarnings("serial") 18 | public class AbstractTimeStampModel implements IModel { 19 | 20 | @Id 21 | @GeneratedValue(strategy=GenerationType.AUTO) 22 | @ApiModelProperty(hidden = true) 23 | protected Long id; 24 | 25 | @Column(name = "created_at") 26 | @ApiModelProperty(hidden = true) 27 | private Date createdAt; 28 | 29 | @Column(name = "updated_at") 30 | @ApiModelProperty(hidden = true) 31 | private Date updatedAt; 32 | 33 | @Column(name = "activated") 34 | @ApiModelProperty(hidden = true) 35 | private Boolean activated; 36 | 37 | public Long getId() { 38 | return id; 39 | } 40 | 41 | public void setId(Long id) { 42 | this.id = id; 43 | } 44 | 45 | public Date getCreatedAt() { 46 | return createdAt; 47 | } 48 | 49 | public void setCreatedAt(Date createdAt) { 50 | this.createdAt = createdAt; 51 | } 52 | 53 | public Date getUpdatedAt() { 54 | return updatedAt; 55 | } 56 | 57 | public void setUpdatedAt(Date updatedAt) { 58 | this.updatedAt = updatedAt; 59 | } 60 | 61 | public Boolean getActivated() { 62 | return activated; 63 | } 64 | 65 | public void setActivated(Boolean activated) { 66 | this.activated = activated; 67 | } 68 | 69 | @PrePersist 70 | public void onPrePersist() { 71 | this.createdAt = this.updatedAt = new Date(); 72 | } 73 | 74 | @PreUpdate 75 | public void onPreUpdate() { 76 | this.updatedAt = new Date(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/model/IModel.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.model; 2 | 3 | import java.io.Serializable; 4 | 5 | public interface IModel extends Serializable { 6 | public Long getId(); 7 | public void setId(Long id); 8 | public Boolean getActivated(); 9 | public void setActivated(Boolean activated); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/model/User.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.model; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.GenerationType; 7 | import javax.persistence.Id; 8 | import javax.persistence.Table; 9 | 10 | import io.swagger.annotations.ApiModelProperty; 11 | 12 | @Entity 13 | @Table(name = "users") 14 | public class User extends AbstractTimeStampModel { 15 | 16 | private static final long serialVersionUID = 1L; 17 | 18 | @Column(name = "name", nullable = false) 19 | private String name; 20 | 21 | @Column(name = "role", nullable = false) 22 | private String role; 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public String getRole() { 33 | return role; 34 | } 35 | 36 | public void setRole(String role) { 37 | this.role = role; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return "User{" + 43 | "id=" + id + 44 | ", name=" + name + 45 | ", role=" + role + 46 | '}'; 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /src/main/java/com/userCrud/service/ICrudService.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.service; 2 | 3 | import java.util.List; 4 | 5 | import com.userCrud.dto.SearchDTO; 6 | 7 | public interface ICrudService { 8 | List getAll(SearchDTO dto); 9 | T getById(long id); 10 | boolean add(T obj); 11 | T update(T obj); 12 | boolean delete(long id); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/userCrud/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.userCrud.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import com.userCrud.dao.UserDAO; 9 | import com.userCrud.dto.SearchDTO; 10 | import com.userCrud.dto.UserSearchDTO; 11 | import com.userCrud.model.User; 12 | 13 | @Service 14 | public class UserService implements ICrudService { 15 | 16 | @Autowired 17 | private UserDAO userDAO; 18 | 19 | @Override 20 | public User getById(long userId) { 21 | User obj = userDAO.getById(userId); 22 | return obj; 23 | } 24 | 25 | @Override 26 | public List getAll(SearchDTO dto){ 27 | return userDAO.getAllWithFilter(dto); 28 | } 29 | 30 | @Override 31 | public synchronized boolean add(User user){ 32 | if ( user.getName() == null || user.getRole() == null || 33 | userDAO.userExists(user.getName(), user.getRole())) { 34 | return false; 35 | } else { 36 | userDAO.add(user); 37 | return true; 38 | } 39 | } 40 | 41 | @Override 42 | public User update(User user) { 43 | return userDAO.update(user); 44 | } 45 | 46 | @Override 47 | public boolean delete(long userId) { 48 | return userDAO.delete(userId); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring.liveBeansView.mbeanDomain: default 2 | spring: 3 | profiles.active: default 4 | --- 5 | spring: 6 | profiles: default 7 | 8 | spring.datasource.driver-class-name: com.mysql.jdbc.Driver 9 | spring.datasource.url: jdbc:mysql://localhost:3306/userCrud 10 | spring.datasource.username: root 11 | spring.datasource.password: 12 | spring.datasource.platform: mysql 13 | spring.datasource.initialize: false 14 | spring.datasource.tomcat.max-wait: 20000 15 | spring.datasource.tomcat.max-active: 50 16 | spring.datasource.tomcat.max-idle: 20 17 | spring.datasource.tomcat.min-idle: 15 18 | spring.jpa.show-sql: true 19 | spring.jpa.hibernate.ddl-auto: update 20 | spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect 21 | spring.jpa.properties.hibernate.id.new_generator_mappings: false 22 | spring.jpa.properties.hibernate.format_sql: true 23 | logging.level.org.hibernate.SQL: ERROR 24 | logging.level.org.hibernate.type.descriptor.sql.BasicBinder: TRACE 25 | elasticsearch.url: http://localhost:9200/_bulk 26 | 27 | --- 28 | spring: 29 | profiles: test 30 | 31 | spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.H2Dialect 32 | spring.datasource.url: jdbc:h2:~/test;AUTO_SERVER=TRUE 33 | spring.jpa.hibernate.ddl-auto: create 34 | spring.jpa.show-sql: false 35 | spring.jpa.properties.hibernate.id.new_generator_mappings: false 36 | spring.jpa.properties.hibernate.format_sql: true 37 | elasticsearch.url: http://localhost:9200/_bulk 38 | 39 | --- 40 | spring: 41 | profiles: container 42 | 43 | spring.datasource.driver-class-name: com.mysql.jdbc.Driver 44 | spring.datasource.url: jdbc:mysql://${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME} 45 | spring.datasource.username: ${DATABASE_USER} 46 | spring.datasource.password: ${DATABASE_PASSWORD} 47 | spring.datasource.platform: mysql 48 | spring.datasource.initialize: true 49 | spring.datasource.tomcat.max-wait: 20000 50 | spring.datasource.tomcat.max-active: 50 51 | spring.datasource.tomcat.max-idle: 20 52 | spring.datasource.tomcat.min-idle: 15 53 | spring.jpa.show-sql: true 54 | spring.jpa.hibernate.ddl-auto: create 55 | spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect 56 | spring.jpa.properties.hibernate.id.new_generator_mappings: false 57 | spring.jpa.properties.hibernate.format_sql: true 58 | logging.level.org.hibernate.SQL: ERROR 59 | logging.level.org.hibernate.type.descriptor.sql.BasicBinder: TRACE 60 | elasticsearch.url: ${ELASTIC_SEARCH_URL} 61 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ${ELASTIC_SEARCH_URL} 6 | logs-%date{yyyy-MM-dd} 7 | runtime 8 | 9 | 10 | host 11 | ${HOSTNAME} 12 | false 13 | 14 | 15 | severity 16 | %level 17 | 18 | 19 | thread 20 | %thread 21 | 22 | 23 | stacktrace 24 | %ex 25 | 26 | 27 | logger 28 | %logger 29 | 30 | 31 | 32 |
33 | Content-Type 34 | text/plain 35 |
36 |
37 |
38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | %msg 52 | 53 | 54 | 55 | 56 |
-------------------------------------------------------------------------------- /src/main/resources/schema-mysql.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS `users` ( 2 | `id` bigint(20) NOT NULL AUTO_INCREMENT, 3 | `activated` bit(1) DEFAULT NULL, 4 | `created_at` datetime DEFAULT NULL, 5 | `updated_at` datetime DEFAULT NULL, 6 | `name` varchar(255) NOT NULL, 7 | `role` varchar(255) NOT NULL, 8 | PRIMARY KEY (`id`) 9 | ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; 10 | -------------------------------------------------------------------------------- /src/test/java/com/userCrud/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.userCrud; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; 5 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 6 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 7 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 8 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 9 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 10 | 11 | import java.nio.charset.Charset; 12 | 13 | import org.junit.FixMethodOrder; 14 | import org.junit.Test; 15 | import org.junit.runner.RunWith; 16 | import org.junit.runners.MethodSorters; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 19 | import org.springframework.boot.test.context.SpringBootTest; 20 | import org.springframework.http.MediaType; 21 | import org.springframework.test.context.ActiveProfiles; 22 | import org.springframework.test.context.junit4.SpringRunner; 23 | import org.springframework.test.web.servlet.MockMvc; 24 | import org.springframework.test.web.servlet.MvcResult; 25 | 26 | import com.fasterxml.jackson.databind.ObjectMapper; 27 | import com.fasterxml.jackson.databind.ObjectWriter; 28 | import com.fasterxml.jackson.databind.SerializationFeature; 29 | import com.userCrud.model.User; 30 | 31 | /* 32 | * Running User CRUD Tests 33 | * By default, JUNIT cannot assure the order of the execution unless using the annotation 34 | * @FixMethodOrder(MethodSorters.NAME_ASCENDING) to order through NAME Ascending 35 | */ 36 | @RunWith(SpringRunner.class) 37 | @SpringBootTest 38 | @AutoConfigureMockMvc 39 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 40 | @ActiveProfiles("test") 41 | public class ApplicationTest { 42 | 43 | @Autowired 44 | private MockMvc mockMvc; 45 | 46 | public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); 47 | 48 | private String userJson(String name, String role) throws Exception { 49 | User anObject = new User(); 50 | anObject.setName(name); 51 | anObject.setRole(role); 52 | 53 | ObjectMapper mapper = new ObjectMapper(); 54 | mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); 55 | ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); 56 | return ow.writeValueAsString(anObject ); 57 | } 58 | 59 | private User[] getUsersFromJson(String json) throws Exception { 60 | return (User[])(new ObjectMapper()).readValue(json, User[].class); 61 | } 62 | 63 | @Test 64 | public void insertUser1() throws Exception { 65 | mockMvc.perform(post("/users").contentType(APPLICATION_JSON_UTF8) 66 | .content(userJson("user1", "admin"))) 67 | .andExpect(status().isCreated()); 68 | } 69 | 70 | @Test 71 | public void insertUser1AgainShouldFail() throws Exception { 72 | mockMvc.perform(post("/users").contentType(APPLICATION_JSON_UTF8) 73 | .content(userJson("user1", "admin"))) 74 | .andExpect(status().is4xxClientError()); 75 | } 76 | 77 | @Test 78 | public void insertUser2() throws Exception { 79 | mockMvc.perform(post("/users").contentType(APPLICATION_JSON_UTF8) 80 | .content(userJson("user2", "marketing"))) 81 | .andExpect(status().isCreated()); 82 | } 83 | 84 | @Test 85 | public void insertUser3() throws Exception { 86 | mockMvc.perform(post("/users").contentType(APPLICATION_JSON_UTF8) 87 | .content(userJson("user3", "marketing"))) 88 | .andExpect(status().isCreated()); 89 | } 90 | 91 | @Test 92 | public void insertUser4() throws Exception { 93 | mockMvc.perform(post("/users").contentType(APPLICATION_JSON_UTF8) 94 | .content(userJson("user4", "admin"))) 95 | .andExpect(status().isCreated()); 96 | } 97 | 98 | @Test 99 | public void insertUser5WithNullPropertiesShouldFail() throws Exception { 100 | mockMvc.perform(post("/users").contentType(APPLICATION_JSON_UTF8) 101 | .content(userJson(null, null))) 102 | .andExpect(status().is4xxClientError()); 103 | } 104 | 105 | @Test 106 | public void shouldAReturnAllUsersSortedByUpdatedAtField() throws Exception { 107 | MvcResult result = this.mockMvc.perform(get("/users")) 108 | .andDo(print()) 109 | .andExpect(status().isOk()) 110 | .andReturn(); 111 | 112 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 113 | assertThat(users[0].getName()).isEqualTo("user4"); 114 | assertThat(users.length).isEqualTo(4); 115 | } 116 | 117 | @Test 118 | public void shouldBReturnOnlyUserWithAdminRole() throws Exception { 119 | MvcResult result = this.mockMvc.perform(get("/users?role=admin")) 120 | .andDo(print()) 121 | .andExpect(status().isOk()) 122 | .andReturn(); 123 | 124 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 125 | 126 | assertThat(users.length).isEqualTo(2); 127 | } 128 | 129 | @Test 130 | public void shouldCReturnOnlyUserWithMarketingRole() throws Exception { 131 | MvcResult result = this.mockMvc.perform(get("/users?role=marketing")) 132 | .andDo(print()) 133 | .andExpect(status().isOk()) 134 | .andReturn(); 135 | 136 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 137 | 138 | assertThat(users.length).isEqualTo(2); 139 | } 140 | 141 | @Test 142 | public void shouldDReturnNoneUserWithNonExistingRoleFilter() throws Exception { 143 | MvcResult result = this.mockMvc.perform(get("/users?role=NONEXISTINGROLE")) 144 | .andDo(print()) 145 | .andExpect(status().isOk()) 146 | .andReturn(); 147 | 148 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 149 | 150 | assertThat(users.length).isEqualTo(0); 151 | } 152 | 153 | @Test 154 | public void shouldEReturnUsersWithMultipleNamesOnFilter() throws Exception { 155 | MvcResult result = this.mockMvc.perform(get("/users?name=user1,user2")) 156 | .andDo(print()) 157 | .andExpect(status().isOk()) 158 | .andReturn(); 159 | 160 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 161 | 162 | assertThat(users.length).isEqualTo(2); 163 | } 164 | 165 | @Test 166 | public void shouldFReturnNoneUserWithMultipleNamesButNonExistinroleOnFilter() throws Exception { 167 | MvcResult result = this.mockMvc.perform(get("/users?name=user1,user2&role=NONEXISTING")) 168 | .andDo(print()) 169 | .andExpect(status().isOk()) 170 | .andReturn(); 171 | 172 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 173 | 174 | assertThat(users.length).isEqualTo(0); 175 | } 176 | 177 | @Test 178 | public void shouldGReturnUsersWithMultipleNamesAndMatchingRolesOnFilter() throws Exception { 179 | MvcResult result = this.mockMvc.perform(get("/users?name=user1,user4&role=admin")) 180 | .andDo(print()) 181 | .andExpect(status().isOk()) 182 | .andReturn(); 183 | 184 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 185 | System.out.println("Auhsahusahus: "+users[0]); 186 | assertThat(users.length).isEqualTo(2); 187 | } 188 | 189 | @Test 190 | public void shouldHGetUserByIdChangePropertyAndCheckIfPropertyChanged() throws Exception { 191 | MvcResult result = this.mockMvc.perform(get("/users")) 192 | .andDo(print()) 193 | .andExpect(status().isOk()) 194 | .andReturn(); 195 | 196 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 197 | 198 | assertThat(users.length).isGreaterThan(0); 199 | 200 | mockMvc.perform(put("/users/"+users[0].getId()) 201 | .contentType(APPLICATION_JSON_UTF8) 202 | .content(userJson("userNew", null))) 203 | .andExpect(status().isOk()); 204 | 205 | MvcResult resultFindById = mockMvc.perform(get("/users/"+users[0].getId())) 206 | .andExpect(status().isOk()) 207 | .andReturn(); 208 | User user = (new ObjectMapper()).readValue(resultFindById .getResponse().getContentAsString(), User.class); 209 | assertThat(user.getName()).isEqualTo("userNew"); 210 | assertThat(user.getId()).isEqualTo(users[0].getId()); 211 | assertThat(user.getUpdatedAt()).isAfter(users[0].getUpdatedAt()); 212 | } 213 | 214 | @Test 215 | public void shouldITryToDeleteUnexistentUserButFail() throws Exception { 216 | mockMvc.perform(delete("/users/UnexistentID")) 217 | .andExpect(status().is4xxClientError()); 218 | } 219 | 220 | @Test 221 | public void shouldJGetUserByIdAndDelete() throws Exception { 222 | MvcResult result = this.mockMvc.perform(get("/users")) 223 | .andDo(print()) 224 | .andExpect(status().isOk()) 225 | .andReturn(); 226 | 227 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 228 | 229 | assertThat(users.length).isGreaterThan(0); 230 | 231 | User userToDelete = users[0]; 232 | 233 | mockMvc.perform(delete("/users/"+userToDelete.getId())) 234 | .andExpect(status().is2xxSuccessful()); 235 | } 236 | 237 | @Test 238 | public void shouldKReturnAllUsersNotConsideringTheRemovedOne() throws Exception { 239 | MvcResult result = this.mockMvc.perform(get("/users")) 240 | .andDo(print()) 241 | .andExpect(status().isOk()) 242 | .andReturn(); 243 | 244 | User[] users = getUsersFromJson(result.getResponse().getContentAsString()); 245 | 246 | assertThat(users.length).isEqualTo(3); 247 | } 248 | 249 | @Test 250 | public void shouldLTryToEditUnexistingUser() throws Exception { 251 | mockMvc.perform(put("/users/UnexistentID") 252 | .contentType(APPLICATION_JSON_UTF8) 253 | .content(userJson("userNew", null))) 254 | .andExpect(status().is4xxClientError()); 255 | 256 | } 257 | 258 | } 259 | 260 | -------------------------------------------------------------------------------- /src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n 9 | 10 | 11 | 12 | 13 | 31 | 32 | 33 | 34 | 35 | 36 | --------------------------------------------------------------------------------