├── .circleci └── config.yml ├── .github └── workflows │ └── maven.yml ├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .travis.yml ├── LICENSE ├── README.md ├── friendly-id-jackson-datatype ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── devskiller │ │ │ └── friendly_id │ │ │ └── jackson │ │ │ ├── FriendlyIdAnnotationIntrospector.java │ │ │ ├── FriendlyIdDeserializer.java │ │ │ ├── FriendlyIdFormat.java │ │ │ ├── FriendlyIdModule.java │ │ │ ├── FriendlyIdSerializer.java │ │ │ └── IdFormat.java │ └── resources │ │ └── META-INF │ │ └── services │ │ └── com.fasterxml.jackson.databind.Module │ └── test │ └── java │ └── com │ └── devskiller │ └── friendly_id │ └── spring │ ├── Bar.java │ ├── FieldWithoutFriendlyIdTest.java │ ├── Foo.java │ ├── FriendlyIdDeserializerTest.java │ └── ObjectMapperConfiguration.java ├── friendly-id-samples ├── friendly-id-contracts │ ├── pom.xml │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── devskiller │ │ │ └── friendly_id │ │ │ └── sample │ │ │ └── contracts │ │ │ ├── Application.java │ │ │ ├── BarController.java │ │ │ ├── BarResource.java │ │ │ ├── BarResourceAssembler.java │ │ │ ├── FooController.java │ │ │ ├── FooResource.java │ │ │ ├── FooResourceAssembler.java │ │ │ ├── JsonConfiguration.java │ │ │ └── domain │ │ │ ├── Bar.java │ │ │ └── Foo.java │ │ └── test │ │ ├── java │ │ └── com │ │ │ └── devskiller │ │ │ └── friendly_id │ │ │ └── sample │ │ │ └── contracts │ │ │ ├── BarControllerTest.java │ │ │ ├── ContractVerifierBase.java │ │ │ ├── FooControllerTest.java │ │ │ └── MvcTest.java │ │ └── resources │ │ └── contracts │ │ └── GetFoo.groovy ├── friendly-id-spring-boot-customized │ ├── pom.xml │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── devskiller │ │ │ └── friendly_id │ │ │ └── sample │ │ │ └── customized │ │ │ ├── Application.java │ │ │ ├── Bar.java │ │ │ ├── BarController.java │ │ │ └── FooService.java │ │ └── test │ │ └── java │ │ └── com │ │ └── devskiller │ │ └── friendly_id │ │ └── sample │ │ └── customized │ │ └── ApplicationTest.java ├── friendly-id-spring-boot-hateos │ ├── pom.xml │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── devskiller │ │ │ └── friendly_id │ │ │ └── sample │ │ │ └── hateos │ │ │ ├── Application.java │ │ │ ├── BarController.java │ │ │ ├── BarResource.java │ │ │ ├── BarResourceAssembler.java │ │ │ ├── FooController.java │ │ │ ├── FooResource.java │ │ │ ├── FooResourceAssembler.java │ │ │ ├── JsonConfiguration.java │ │ │ └── domain │ │ │ ├── Bar.java │ │ │ └── Foo.java │ │ └── test │ │ └── java │ │ └── com │ │ └── devskiller │ │ └── friendly_id │ │ └── sample │ │ └── hateos │ │ ├── BarControllerTest.java │ │ └── FooControllerTest.java ├── friendly-id-spring-boot-simple │ ├── pom.xml │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── devskiller │ │ │ └── friendly_id │ │ │ └── sample │ │ │ └── simple │ │ │ ├── Application.java │ │ │ └── Bar.java │ │ └── test │ │ └── java │ │ └── com │ │ └── devskiller │ │ └── friendly_id │ │ └── sample │ │ └── simple │ │ └── ApplicationTest.java └── pom.xml ├── friendly-id-spring-boot-starter ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── devskiller │ │ └── friendly_id │ │ └── boot │ │ └── FriendlyIdAutoConfiguration.java │ └── resources │ └── META-INF │ ├── spring.factories │ └── spring │ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports ├── friendly-id-spring-boot ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── devskiller │ └── friendly_id │ └── spring │ ├── EnableFriendlyId.java │ └── FriendlyIdConfiguration.java ├── friendly-id ├── pom.xml └── src │ ├── jmh │ ├── java │ │ └── com │ │ │ └── devskiller │ │ │ └── friendly_id │ │ │ ├── FriendlyIdBenchmark.java │ │ │ └── UuidConverterBenchmark.java │ └── resources │ │ └── logback-test.xml │ ├── main │ └── java │ │ └── com │ │ └── devskiller │ │ └── friendly_id │ │ ├── Base62.java │ │ ├── BigIntegerPairing.java │ │ ├── FriendlyId.java │ │ ├── Url62.java │ │ └── UuidConverter.java │ └── test │ └── java │ └── com │ └── devskiller │ └── friendly_id │ ├── AnalyzeGeneratedIdsTest.java │ ├── Base62Test.java │ ├── BigIntegerPairingTest.java │ ├── DataProvider.java │ ├── FriendlyIdTest.java │ ├── IdUtil.java │ └── Url62Test.java ├── mvnw ├── mvnw.cmd └── pom.xml /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | 5 | working_directory: ~/friendly_id 6 | 7 | docker: 8 | - image: circleci/openjdk:8u171-jdk 9 | 10 | steps: 11 | 12 | - checkout 13 | 14 | - restore_cache: 15 | key: friendly_id-{{ checksum "pom.xml" }} 16 | 17 | - run: mvn de.qaware.maven:go-offline-maven-plugin:1.1.0:resolve-dependencies 18 | 19 | - save_cache: 20 | paths: 21 | - ~/.m2 22 | key: friendly_id-{{ checksum "pom.xml" }} 23 | 24 | - run: mvn install 25 | 26 | - store_test_results: 27 | path: target/surefire-reports 28 | 29 | -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Set up JDK 1.8 13 | uses: actions/setup-java@v1 14 | with: 15 | java-version: 1.8 16 | - name: Build with Maven 17 | run: mvn -B package --file pom.xml 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | target 4 | pom.xml.versionsBackup -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.5"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Devskiller/friendly-id/bc63e0a8f95981482771958a530e44000470d2bc/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | dist: trusty 3 | group: edge 4 | 5 | language: java 6 | 7 | jdk: 8 | - oraclejdk8 9 | - oraclejdk11 10 | 11 | script: ./mvnw package 12 | 13 | after_success: 14 | - ./mvnw clean test jacoco:report coveralls:report 15 | 16 | cache: 17 | directories: 18 | - ~/.m2/repository 19 | - ~/.m2/wrapper -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/Devskiller/friendly-id.svg?branch=master)](https://travis-ci.org/Devskiller/friendly-id) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.devskiller.friendly-id/friendly-id/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.devskiller.friendly-id/friendly-id) [![Coverage Status](https://coveralls.io/repos/github/Devskiller/friendly-id/badge.svg?branch=master)](https://coveralls.io/github/Devskiller/friendly-id?branch=master) 2 | 3 | FriendlyID (Java, [Swift](https://github.com/kdubb/SwiftFriendlyId), [Rust](https://github.com/mariuszs/friendly_id), [Go](https://github.com/mariuszs/friendlyid-go)) 4 | == 5 | 6 | 7 | What is the FriendlyID library? 8 | -- 9 | The FriendlyID library converts a given UUID (with 36 characters) to a URL-friendly ID (a "FriendlyID") which is based on Base62 (with a maximum of 22 characters), as in the example below: 10 | 11 | 12 | UUID Friendly ID 13 | 14 | c3587ec5-0976-497f-8374-61e0c2ea3da5 -> 5wbwf6yUxVBcr48AMbz9cb 15 | | | 16 | 36 characters 22 characters or less 17 | 18 | In addition, this library allows to: 19 | 20 | 21 | * convert from a FriendlyID back to the original UUID; and 22 | * create a new, random FriendlyID 23 | 24 | Why use a FriendlyID? 25 | -- 26 | Universal Unique IDs (UUIDs) provide a non-sequential and unique identifier that can be generated separately from the source database. As a result, it is not possible to guess either the previous or next identifier. That's great, but, to achieve this level of security, a UUID is long (128 bits long) and looks ugly (36 alphanumeric characters including four hyphens which are added to make it easier to read the UUID), as in this example: `123e4567-e89b-12d3-a456-426655440000`. 27 | 28 | Such a format is: 29 | 30 | * difficult to read (especially if it is part of a URL) 31 | * difficult to remember 32 | * cannot be copied with just two mouse-clicks (you have to select manually the start and end positions) 33 | * can easily become broken across lines when it is copied, pasted, edited, or sent. 34 | 35 | 36 | Our FriendlyID Java library solves these problems by converting a given UUID using Base62 with alphanumeric characters in the range [0-9A-Za-z] into a FriendlyId which consists of a maximum of 22 characters (but in fact often contains fewer characters). 37 | 38 | Supported languages 39 | -- 40 | 41 | Curently FriendlyId supports Java (this project) and 42 | * [Swift](https://github.com/kdubb/SwiftFriendlyId) language (thanks to [Kevin Wooten](https://github.com/kdubb)) 43 | * [Rust](https://github.com/mariuszs/friendly_id) [![Version](https://img.shields.io/crates/v/friendly_id.svg?style=social&logo=appveyor)](https://crates.io/crates/friendly_id) 44 | * [Go](https://github.com/mariuszs/friendlyid-go) 45 | 46 | Tools 47 | -- 48 | 49 | There are available CLI converters for many platforms. 50 | 51 | * https://github.com/mariuszs/rust-friendlyid (also available in RPM and DEB format) 52 | * https://github.com/kdubb/SwiftFriendlyId#command-line 53 | 54 | ## Use cases 55 | 56 | ### Basic (returning a user in a database) 57 | 58 | 59 | Let us assume that a method in the controller for returning users requires the relevant UUID in order to find a given user in a database, as in this example: 60 | 61 | ```java 62 | @GetMapping("/users/{userId}") 63 | public User getUser(@PathVariable UUID userId) { 64 | [implementation deleted] 65 | } 66 | ``` 67 | 68 | Without using the Friendly ID library, you could access a given user as follows: 69 | 70 | ```bash 71 | curl http://localhost:8080/users/c3587ec5-0976-497f-8374-61e0c2ea3da5 72 | ``` 73 | 74 | 75 | After adding the FriendlyID library, the controller method itself does not change, but you would be able to access a given user using the relevant FriendlyID as follows: 76 | 77 | ```bash 78 | curl http://localhost:8080/users/5wbwf6yUxVBcr48AMbz9cb 79 | ``` 80 | 81 | 82 | 83 | In addition, if a given document returned by such a method contains objects of type UUID, those IDs will also be shortened into FriendlyID format. 84 | 85 | 86 | ### Advanced (Optimizing testing) 87 | 88 | 89 | The FriendlyID library makes it possible to define for UUIDs values which are easy to read. By using names instead of hard-to-remember UUIDs, you can write much simpler tests for your code, for example: 90 | 91 | ```java 92 | @Test 93 | public void shouldGetUser() { 94 | mockMvc.perform(get("/users/{userId}", "John")) 95 | .andExpect(status().isOk()) 96 | .andExpect(content().contentType("application/json")) 97 | .andExpect(jsonPath("$.uuid", is("John"))); 98 | } 99 | ``` 100 | 101 | In the above example, the variable "John" is decoded by the library to the correct UUID, in this case, `00000000-0000-0000-0000-000000a69efb`. In this way, you can give a variable in a test class a truly meaningful value and, as a result, an assertion which refers to that variable becomes exceptionally easy to understand in your test program. 102 | 103 | 104 | FriendlyID library 105 | -- 106 | 107 | Dependencies 108 | --- 109 | 110 | ```xml 111 | 112 | com.devskiller.friendly-id 113 | friendly-id 114 | 1.1.0 115 | 116 | ``` 117 | 118 | Usage 119 | --- 120 | 121 | ```java 122 | FriendlyId.createFriendlyId(); 123 | ``` 124 | 125 | This creates a new, random FriendlyID, for example: `5wbwf6yUxVBcr48AMbz9cb` 126 | 127 | ```java 128 | FriendlyId.toFriendlyId(UUID.fromString("c3587ec5-0976-497f-8374-61e0c2ea3da5")); 129 | ``` 130 | 131 | This converts a UUID in the form of a string to a FriendlyID, for example: `5wbwf6yUxVBcr48AMbz9cb` 132 | 133 | 134 | ```java 135 | FriendlyId.toUuid("5wbwf6yUxVBcr48AMbz9cb"); 136 | ``` 137 | 138 | This converts a FriendlyID to its UUID, for example: `c3587ec5-0976-497f-8374-61e0c2ea3da5` 139 | 140 | 141 | Notes 142 | -- 143 | 144 | * As every *UUID* is a 128-bit number, a *FriendlyID* can also store only a 128-bit number. 145 | * If a FriendlyID has any leading zeros, those leading zeros are ignored - for example, `00cafe` is treated as `cafe`. 146 | 147 | 148 | ## Integrations 149 | 150 | 151 | - [Spring Boot integration](#Spring-Boot-integration) 152 | - [Jackson integration ](#Jackson-integration) 153 | 154 | ### Spring Boot integration 155 | 156 | The FriendlyID library includes a Spring configuration to make it easy to add shorter IDs to an application. With a typical application based on Spring Boot, for your controllers to be able to use FriendlyIDs when communicating with the outside world, just add one new starter dependency as follows: 157 | 158 | ```xml 159 | 160 | com.devskiller.friendly-id 161 | friendly-id-spring-boot-starter 162 | 1.1.0 163 | 164 | ``` 165 | 166 | Let us assume that you'll use this sample application: 167 | 168 | ```java 169 | @SpringBootApplication 170 | @RestController 171 | public class Application { 172 | 173 | public static void main(String[] args) { 174 | SpringApplication.run(Application.class, args); 175 | } 176 | 177 | @GetMapping("/bars/{bar}") 178 | public Bar getBar(@PathVariable UUID bar) { 179 | return new Bar(UUID.randomUUID()); 180 | } 181 | 182 | @Value 183 | class Bar { 184 | private final UUID id; 185 | } 186 | } 187 | ``` 188 | 189 | This command: `curl http://localhost:8080/bars/5fD1KwsxRcGhBqWNju0jzt` 190 | 191 | will result in the following output: 192 | ```json 193 | {"id":"52OMXhWiAqUWwII0c97Svl"} 194 | ``` 195 | 196 | In this case, `Bar` is a POJO class which is converted by Spring MVC to a JSON document. This `Bar` object has one field of type UUID, and this field is output to the JSON document as a FriendlyID instead of a UUID. Although the application uses the relevant UUID internally, from an external point of view, only the FriendlyID is visible. 197 | 198 | ### Jackson integration 199 | 200 | 201 | First, add the following Jackson module dependency: 202 | ```xml 203 | 204 | com.devskiller.friendly-id 205 | friendly-id-jackson-datatype 206 | 1.1.0 207 | 208 | ``` 209 | Then register the `FriendlyIdModule` module as follows: 210 | 211 | ```java 212 | ObjectMapper mapper = new ObjectMapper() 213 | .registerModule(new FriendlyIdModule()); 214 | ``` 215 | 216 | Contributing 217 | ---------- 218 | 219 | Thinking of helping us out? We invite you to take a look at: 220 | 221 | - Source Code: [github.com/Devskiller/friendly-id/](https://github.com/Devskiller/friendly-id) 222 | - Issue Tracker: [github.com/Devskiller/friendly-id/issues](https://github.com/Devskiller/friendly-id/issues) 223 | 224 | 225 | License 226 | ------- 227 | 228 | The project is licensed under the Apache 2.0 license. 229 | For further details, please see the [License](/LICENSE/) page. 230 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | friendly-id-project 7 | com.devskiller.friendly-id 8 | 1.1.1-SNAPSHOT 9 | .. 10 | 11 | 12 | friendly-id-jackson-datatype 13 | 14 | 15 | 16 | com.devskiller.friendly-id 17 | friendly-id 18 | ${project.version} 19 | 20 | 21 | com.fasterxml.jackson.core 22 | jackson-annotations 23 | 24 | 25 | com.fasterxml.jackson.core 26 | jackson-core 27 | 28 | 29 | com.fasterxml.jackson.core 30 | jackson-databind 31 | 32 | 33 | com.fasterxml.jackson.module 34 | jackson-module-parameter-names 35 | 36 | 37 | 38 | junit 39 | junit 40 | test 41 | 42 | 43 | org.assertj 44 | assertj-core 45 | test 46 | 47 | 48 | 49 | 50 | 51 | 52 | maven-compiler-plugin 53 | 3.8.1 54 | 55 | true 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/main/java/com/devskiller/friendly_id/jackson/FriendlyIdAnnotationIntrospector.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.jackson; 2 | 3 | import java.util.UUID; 4 | 5 | import com.fasterxml.jackson.databind.deser.std.UUIDDeserializer; 6 | import com.fasterxml.jackson.databind.introspect.Annotated; 7 | import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; 8 | import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; 9 | import com.fasterxml.jackson.databind.ser.std.UUIDSerializer; 10 | 11 | public class FriendlyIdAnnotationIntrospector extends JacksonAnnotationIntrospector { 12 | 13 | private static final long serialVersionUID = 1L; 14 | 15 | @Override 16 | public Object findSerializer(Annotated annotatedMethod) { 17 | IdFormat annotation = _findAnnotation(annotatedMethod, IdFormat.class); 18 | if (annotatedMethod.getRawType() == UUID.class) { 19 | if (annotation != null) { 20 | switch (annotation.value()) { 21 | case RAW: 22 | return UUIDSerializer.class; 23 | case URL62: 24 | return FriendlyIdSerializer.class; 25 | } 26 | } 27 | return FriendlyIdSerializer.class; 28 | } else { 29 | return null; 30 | } 31 | } 32 | 33 | @Override 34 | public Object findDeserializer(Annotated annotatedMethod) { 35 | IdFormat annotation = _findAnnotation(annotatedMethod, IdFormat.class); 36 | if (rawDeserializationType(annotatedMethod) == UUID.class) { 37 | if (annotation != null) { 38 | switch (annotation.value()) { 39 | case RAW: 40 | return UUIDDeserializer.class; 41 | case URL62: 42 | return FriendlyIdDeserializer.class; 43 | } 44 | } 45 | return FriendlyIdDeserializer.class; 46 | } else { 47 | return null; 48 | } 49 | } 50 | 51 | private Class rawDeserializationType(Annotated a) { 52 | if (a instanceof AnnotatedMethod) { 53 | AnnotatedMethod am = (AnnotatedMethod) a; 54 | if (am.getParameterCount() == 1) { 55 | return am.getRawParameterType(0); 56 | } 57 | } 58 | return a.getRawType(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/main/java/com/devskiller/friendly_id/jackson/FriendlyIdDeserializer.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.jackson; 2 | 3 | import java.io.IOException; 4 | import java.util.UUID; 5 | 6 | import com.fasterxml.jackson.core.JsonParser; 7 | import com.fasterxml.jackson.core.JsonToken; 8 | import com.fasterxml.jackson.databind.DeserializationContext; 9 | import com.fasterxml.jackson.databind.deser.std.UUIDDeserializer; 10 | 11 | import com.devskiller.friendly_id.FriendlyId; 12 | 13 | public class FriendlyIdDeserializer extends UUIDDeserializer { 14 | 15 | @Override 16 | public UUID deserialize(JsonParser parser, DeserializationContext deserializationContext) throws IOException { 17 | 18 | JsonToken token = parser.getCurrentToken(); 19 | if (token == JsonToken.VALUE_STRING) { 20 | String string = parser.getValueAsString().trim(); 21 | if (looksLikeUuid(string)) { 22 | return super.deserialize(parser, deserializationContext); 23 | } else { 24 | return FriendlyId.toUuid(string); 25 | } 26 | } 27 | throw new IllegalStateException("This is not friendly id"); 28 | } 29 | 30 | private boolean looksLikeUuid(String value) { 31 | return value.contains("-"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/main/java/com/devskiller/friendly_id/jackson/FriendlyIdFormat.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.jackson; 2 | 3 | /** 4 | * Friendly ID format 5 | */ 6 | public enum FriendlyIdFormat { 7 | 8 | /** 9 | * Url62 encoded ID 10 | */ 11 | URL62, 12 | 13 | /** 14 | * Leave this ID as is (without conversion) 15 | */ 16 | RAW 17 | } 18 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/main/java/com/devskiller/friendly_id/jackson/FriendlyIdModule.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.jackson; 2 | 3 | import java.util.UUID; 4 | 5 | import com.fasterxml.jackson.databind.module.SimpleModule; 6 | 7 | public class FriendlyIdModule extends SimpleModule { 8 | 9 | private FriendlyIdAnnotationIntrospector introspector; 10 | 11 | public FriendlyIdModule() { 12 | introspector = new FriendlyIdAnnotationIntrospector(); 13 | addDeserializer(UUID.class, new FriendlyIdDeserializer()); 14 | addSerializer(UUID.class, new FriendlyIdSerializer()); 15 | } 16 | 17 | @Override 18 | public void setupModule(SetupContext context) { 19 | context.insertAnnotationIntrospector(introspector); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/main/java/com/devskiller/friendly_id/jackson/FriendlyIdSerializer.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.jackson; 2 | 3 | import java.io.IOException; 4 | import java.util.UUID; 5 | 6 | import com.fasterxml.jackson.core.JsonGenerator; 7 | import com.fasterxml.jackson.databind.SerializerProvider; 8 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 9 | 10 | import com.devskiller.friendly_id.FriendlyId; 11 | 12 | public class FriendlyIdSerializer extends StdSerializer { 13 | 14 | public FriendlyIdSerializer() { 15 | super(UUID.class); 16 | } 17 | 18 | @Override 19 | public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { 20 | jsonGenerator.writeString(FriendlyId.toFriendlyId(uuid)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/main/java/com/devskiller/friendly_id/jackson/IdFormat.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.jackson; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | /** 7 | * Declares that a field should be formatted as a friendly ID. 8 | */ 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface IdFormat { 11 | 12 | FriendlyIdFormat value() default FriendlyIdFormat.URL62; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/main/resources/META-INF/services/com.fasterxml.jackson.databind.Module: -------------------------------------------------------------------------------- 1 | com.devskiller.friendly_id.jackson.FriendlyIdModule -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/test/java/com/devskiller/friendly_id/spring/Bar.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.spring; 2 | 3 | import java.util.UUID; 4 | 5 | import com.devskiller.friendly_id.jackson.FriendlyIdFormat; 6 | import com.devskiller.friendly_id.jackson.IdFormat; 7 | 8 | public class Bar { 9 | 10 | @IdFormat(FriendlyIdFormat.RAW) 11 | private final UUID rawUuid; 12 | 13 | private final UUID friendlyId; 14 | 15 | public Bar(UUID rawUuid, UUID friendlyId) { 16 | this.rawUuid = rawUuid; 17 | this.friendlyId = friendlyId; 18 | } 19 | 20 | public UUID getRawUuid() { 21 | return rawUuid; 22 | } 23 | 24 | public UUID getFriendlyId() { 25 | return friendlyId; 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/test/java/com/devskiller/friendly_id/spring/FieldWithoutFriendlyIdTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.spring; 2 | 3 | import java.util.UUID; 4 | 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; 7 | import org.junit.Test; 8 | 9 | import com.devskiller.friendly_id.FriendlyId; 10 | 11 | import static com.devskiller.friendly_id.spring.ObjectMapperConfiguration.mapper; 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | 14 | public class FieldWithoutFriendlyIdTest { 15 | 16 | private UUID uuid = UUID.fromString("f088ce5b-9279-4cc3-946a-c15ad740dd6d"); 17 | private ObjectMapper mapper = mapper(); 18 | 19 | @Test 20 | public void shouldAllowToDoNotCodeUuidInDataObject() throws Exception { 21 | Foo foo = new Foo(); 22 | foo.setRawUuid(uuid); 23 | foo.setFriendlyId(uuid); 24 | 25 | String json = mapper.writeValueAsString(foo); 26 | 27 | assertThat(json).isEqualToIgnoringWhitespace( 28 | "{\"rawUuid\":\"f088ce5b-9279-4cc3-946a-c15ad740dd6d\",\"friendlyId\":\"7Jsg6CPDscHawyJfE70b9x\"}" 29 | ); 30 | 31 | Foo cloned = mapper.readValue(json, Foo.class); 32 | assertThat(cloned.getRawUuid()).isEqualTo(foo.getFriendlyId()); 33 | } 34 | 35 | @Test 36 | public void shouldDeserializeUuidsInDataObject() throws Exception { 37 | String json = "{\"rawUuid\":\"f088ce5b-9279-4cc3-946a-c15ad740dd6d\",\"friendlyId\":\"7Jsg6CPDscHawyJfE70b9x\"}"; 38 | 39 | Foo cloned = mapper.readValue(json, Foo.class); 40 | assertThat(cloned.getRawUuid()).isEqualTo(uuid); 41 | assertThat(cloned.getFriendlyId()).isEqualTo(uuid); 42 | } 43 | 44 | 45 | @Test 46 | public void shouldSerializeUuidsInValueObject() throws Exception { 47 | mapper = mapper(new ParameterNamesModule()); 48 | 49 | Bar bar = new Bar(uuid, uuid); 50 | 51 | String json = mapper.writeValueAsString(bar); 52 | 53 | assertThat(json).isEqualToIgnoringWhitespace( 54 | "{\"rawUuid\":\"f088ce5b-9279-4cc3-946a-c15ad740dd6d\",\"friendlyId\":\"7Jsg6CPDscHawyJfE70b9x\"}" 55 | ); 56 | } 57 | 58 | @Test 59 | public void shouldDeserializeUuuidsValueObject() throws Exception { 60 | mapper = mapper(new ParameterNamesModule()); 61 | 62 | String json = "{\"rawUuid\":\"f088ce5b-9279-4cc3-946a-c15ad740dd6d\",\"friendlyId\":\"7Jsg6CPDscHawyJfE70b9x\"}"; 63 | 64 | Bar deserialized = mapper.readValue(json, Bar.class); 65 | 66 | assertThat(deserialized.getRawUuid()).isEqualTo(uuid); 67 | assertThat(deserialized.getFriendlyId()).isEqualTo(uuid); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/test/java/com/devskiller/friendly_id/spring/Foo.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.spring; 2 | 3 | import java.util.UUID; 4 | 5 | import com.devskiller.friendly_id.jackson.FriendlyIdFormat; 6 | import com.devskiller.friendly_id.jackson.IdFormat; 7 | 8 | public class Foo { 9 | 10 | @IdFormat(FriendlyIdFormat.RAW) 11 | private UUID rawUuid; 12 | 13 | private UUID friendlyId; 14 | 15 | public UUID getRawUuid() { 16 | return rawUuid; 17 | } 18 | 19 | public void setRawUuid(UUID rawUuid) { 20 | this.rawUuid = rawUuid; 21 | } 22 | 23 | public UUID getFriendlyId() { 24 | return friendlyId; 25 | } 26 | 27 | public void setFriendlyId(UUID friendlyId) { 28 | this.friendlyId = friendlyId; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/test/java/com/devskiller/friendly_id/spring/FriendlyIdDeserializerTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.spring; 2 | 3 | import java.util.UUID; 4 | 5 | import org.junit.Test; 6 | 7 | import com.devskiller.friendly_id.FriendlyId; 8 | 9 | import static com.devskiller.friendly_id.spring.ObjectMapperConfiguration.mapper; 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | 12 | public class FriendlyIdDeserializerTest { 13 | 14 | @Test 15 | public void shouldSerializeFriendlyId() throws Exception { 16 | UUID uuid = UUID.randomUUID(); 17 | String json = mapper().writeValueAsString(uuid); 18 | System.out.println(json); 19 | assertThat(json).contains(FriendlyId.toFriendlyId(uuid)); 20 | } 21 | 22 | @Test 23 | public void shouldDeserializeFriendlyId() throws Exception { 24 | String friendlyId = "2YSfgVHnEYbYgfFKhEX3Sz"; 25 | UUID uuid = mapper().readValue("\"" + friendlyId + "\"", UUID.class); 26 | assertThat(uuid).isEqualByComparingTo(FriendlyId.toUuid(friendlyId)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /friendly-id-jackson-datatype/src/test/java/com/devskiller/friendly_id/spring/ObjectMapperConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.spring; 2 | 3 | import com.fasterxml.jackson.databind.Module; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import com.devskiller.friendly_id.jackson.FriendlyIdModule; 7 | 8 | public class ObjectMapperConfiguration { 9 | 10 | protected static ObjectMapper mapper(Module... modules) { 11 | ObjectMapper mapper = new ObjectMapper(); 12 | mapper.registerModule(new FriendlyIdModule()); 13 | mapper.registerModules(modules); 14 | return mapper; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | 6 | com.devskiller.friendly-id 7 | spring-boot-contracts 8 | 1.1.1-SNAPSHOT 9 | 10 | 11 | org.springframework.boot 12 | spring-boot-starter-parent 13 | 2.2.2.RELEASE 14 | 15 | 16 | 17 | 18 | UTF-8 19 | UTF-8 20 | 1.8 21 | 2.2.1.RELEASE 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | org.springframework.cloud 31 | spring-cloud-starter-contract-verifier 32 | test 33 | 34 | 35 | com.devskiller.friendly-id 36 | friendly-id-spring-boot-starter 37 | ${project.version} 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-hateoas 42 | 43 | 44 | org.atteo 45 | evo-inflector 46 | 1.2.2 47 | 48 | 49 | com.fasterxml.jackson.module 50 | jackson-module-parameter-names 51 | 52 | 53 | com.fasterxml.jackson.datatype 54 | jackson-datatype-jdk8 55 | 56 | 57 | com.fasterxml.jackson.datatype 58 | jackson-datatype-jsr310 59 | 60 | 61 | 62 | org.projectlombok 63 | lombok 64 | provided 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-starter-test 70 | test 71 | 72 | 73 | 74 | 75 | 76 | 77 | org.springframework.cloud 78 | spring-cloud-contract-dependencies 79 | ${spring-cloud-contract.version} 80 | pom 81 | import 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | org.springframework.boot 90 | spring-boot-maven-plugin 91 | 92 | 93 | maven-compiler-plugin 94 | 3.8.0 95 | 96 | true 97 | 98 | 99 | 100 | org.apache.maven.plugins 101 | maven-deploy-plugin 102 | 103 | true 104 | 105 | 106 | 107 | org.apache.maven.plugins 108 | maven-surefire-plugin 109 | 2.22.1 110 | 111 | 112 | org.springframework.cloud 113 | spring-cloud-contract-maven-plugin 114 | ${spring-cloud-contract.version} 115 | true 116 | 117 | com.devskiller.friendly_id.sample.contracts 118 | com.devskiller.friendly_id.sample.contracts.ContractVerifierBase 119 | 120 | 121 | 122 | org.jacoco 123 | jacoco-maven-plugin 124 | 0.8.3 125 | 126 | true 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/Application.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/BarController.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import com.devskiller.friendly_id.sample.contracts.domain.Bar; 4 | import com.devskiller.friendly_id.sample.contracts.domain.Foo; 5 | import org.springframework.hateoas.server.ExposesResourceFor; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.util.UUID; 12 | 13 | @RestController 14 | @ExposesResourceFor(BarResource.class) 15 | @RequestMapping("/foos/{fooId}/bars") 16 | public class BarController { 17 | 18 | private final BarResourceAssembler assembler; 19 | 20 | public BarController(BarResourceAssembler assembler) { 21 | this.assembler = assembler; 22 | } 23 | 24 | @GetMapping("/{id}") 25 | public BarResource getBar(@PathVariable UUID fooId, @PathVariable UUID id) { 26 | return assembler.toModel(new Bar(id, "Bar", new Foo(fooId, "Root Foo"))); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/BarResource.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import lombok.Value; 4 | import org.springframework.hateoas.RepresentationModel; 5 | import org.springframework.hateoas.server.core.Relation; 6 | 7 | @Relation(value = "bar", collectionRelation = "bars") 8 | @Value 9 | class BarResource extends RepresentationModel { 10 | 11 | private String name; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/BarResourceAssembler.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import com.devskiller.friendly_id.FriendlyId; 4 | import com.devskiller.friendly_id.sample.contracts.domain.Bar; 5 | import com.devskiller.friendly_id.sample.contracts.domain.Foo; 6 | import org.springframework.hateoas.server.LinkRelationProvider; 7 | import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; 8 | import org.springframework.hateoas.server.mvc.WebMvcLinkBuilderFactory; 9 | 10 | public class BarResourceAssembler extends RepresentationModelAssemblerSupport { 11 | 12 | LinkRelationProvider relProvider; 13 | 14 | public BarResourceAssembler() { 15 | super(BarController.class, BarResource.class); 16 | } 17 | 18 | public BarResourceAssembler(LinkRelationProvider relProvider) { 19 | super(BarController.class, BarResource.class); 20 | this.relProvider = relProvider; 21 | } 22 | 23 | @Override 24 | public BarResource toModel(Bar entity) { 25 | BarResource resource = new BarResource(entity.getName()); 26 | WebMvcLinkBuilderFactory factory = new WebMvcLinkBuilderFactory(); 27 | resource.add(factory.linkTo(FooController.class, FriendlyId.toFriendlyId(entity.getFoo().getId())) 28 | .withRel(relProvider.getCollectionResourceRelFor(Foo.class))); 29 | resource.add(factory.linkTo(BarController.class, FriendlyId.toFriendlyId(entity.getFoo().getId())).slash(FriendlyId.toFriendlyId(entity.getId())).withSelfRel()); 30 | return resource; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/FooController.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import com.devskiller.friendly_id.FriendlyId; 4 | import com.devskiller.friendly_id.sample.contracts.domain.Foo; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.hateoas.server.EntityLinks; 8 | import org.springframework.hateoas.server.ExposesResourceFor; 9 | import org.springframework.http.HttpEntity; 10 | import org.springframework.http.HttpHeaders; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.web.bind.annotation.*; 14 | 15 | import java.lang.invoke.MethodHandles; 16 | import java.util.UUID; 17 | 18 | 19 | @RestController 20 | @ExposesResourceFor(FooResource.class) 21 | @RequestMapping("/foos") 22 | public class FooController { 23 | 24 | private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); 25 | 26 | private final EntityLinks entityLinks; 27 | private final FooResourceAssembler assembler; 28 | 29 | public FooController(EntityLinks entityLinks) { 30 | this.entityLinks = entityLinks; 31 | this.assembler = new FooResourceAssembler(); 32 | } 33 | 34 | @GetMapping("/{id}") 35 | public FooResource get(@PathVariable UUID id) { 36 | log.info("Get {}", id); 37 | Foo foo = new Foo(id, "Foo"); 38 | return assembler.toModel(foo); 39 | } 40 | 41 | @PutMapping("/{id}") 42 | public HttpEntity update(@PathVariable UUID id, @RequestBody FooResource fooResource) { 43 | log.info("Update {} : {}", id, fooResource); 44 | Foo entity = new Foo(fooResource.getUuid(), fooResource.getName()); 45 | return ResponseEntity.ok(assembler.toModel(entity)); 46 | } 47 | 48 | @PostMapping 49 | public HttpEntity create(@RequestBody FooResource fooResource) { 50 | HttpHeaders headers = new HttpHeaders(); 51 | Foo entity = new Foo(fooResource.getUuid(), "Foo"); 52 | 53 | // ... 54 | 55 | headers.setLocation(entityLinks.linkToItemResource(FooResource.class, FriendlyId.toFriendlyId(entity.getId())).toUri()); 56 | return new ResponseEntity<>(headers, HttpStatus.CREATED); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/FooResource.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import lombok.Value; 4 | import org.springframework.hateoas.RepresentationModel; 5 | import org.springframework.hateoas.server.core.Relation; 6 | 7 | import java.util.UUID; 8 | 9 | @Relation(value = "foos") 10 | @Value 11 | public class FooResource extends RepresentationModel { 12 | 13 | private final UUID uuid; 14 | private final String name; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/FooResourceAssembler.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import com.devskiller.friendly_id.FriendlyId; 4 | import com.devskiller.friendly_id.sample.contracts.domain.Foo; 5 | import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; 6 | import org.springframework.hateoas.server.mvc.WebMvcLinkBuilderFactory; 7 | 8 | public class FooResourceAssembler extends RepresentationModelAssemblerSupport { 9 | 10 | public FooResourceAssembler() { 11 | super(FooController.class, FooResource.class); 12 | } 13 | 14 | @Override 15 | public FooResource toModel(Foo entity) { 16 | WebMvcLinkBuilderFactory factory = new WebMvcLinkBuilderFactory(); 17 | FooResource resource = new FooResource(entity.getId(), entity.getName()); 18 | resource.add(factory.linkTo(FooController.class).slash(FriendlyId.toFriendlyId(entity.getId())).withSelfRel()); 19 | return resource; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/JsonConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.hateoas.server.LinkRelationProvider; 6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 7 | 8 | @Configuration 9 | public class JsonConfiguration implements WebMvcConfigurer { 10 | 11 | // This is declared as part of WebMVC slice, used in testing 12 | @Bean 13 | public FooResourceAssembler fooResourceAssembler() { 14 | return new FooResourceAssembler(); 15 | } 16 | 17 | // This is declared as part of WebMVC slice, used in testing 18 | @Bean 19 | public BarResourceAssembler barResourceAssembler(LinkRelationProvider relProvider) { 20 | return new BarResourceAssembler(relProvider); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Bar.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | import java.util.UUID; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | public class Bar { 11 | 12 | private UUID id; 13 | private String name; 14 | 15 | private Foo foo; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Foo.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | import java.util.UUID; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | public class Foo { 11 | 12 | private UUID id; 13 | private String name; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/test/java/com/devskiller/friendly_id/sample/contracts/BarControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.web.servlet.MockMvc; 10 | 11 | import com.devskiller.friendly_id.spring.EnableFriendlyId; 12 | 13 | import static org.hamcrest.CoreMatchers.is; 14 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 15 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 16 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 19 | 20 | @RunWith(SpringRunner.class) 21 | @WebMvcTest(BarController.class) 22 | @EnableFriendlyId 23 | public class BarControllerTest { 24 | 25 | @Autowired 26 | MockMvc mockMvc; 27 | 28 | @Test 29 | public void shouldGet() throws Exception { 30 | mockMvc.perform(get("/foos/{fooId}/bars/{barId}", "foo", "bar")) 31 | .andDo(print()) 32 | .andExpect(status().isOk()) 33 | .andExpect(content().contentType("application/hal+json")) 34 | .andExpect(jsonPath("$.name", is("Bar"))) 35 | .andExpect(jsonPath("$._links.self.href", is("http://localhost/foos/foo/bars/bar"))) 36 | .andExpect(jsonPath("$._links.foos.href", is("http://localhost/foos"))); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/test/java/com/devskiller/friendly_id/sample/contracts/ContractVerifierBase.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import io.restassured.module.mockmvc.RestAssuredMockMvc; 4 | import org.junit.Before; 5 | import org.junit.runner.RunWith; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | import org.springframework.web.context.WebApplicationContext; 11 | 12 | import com.devskiller.friendly_id.spring.EnableFriendlyId; 13 | 14 | @RunWith(SpringRunner.class) 15 | @WebMvcTest 16 | @EnableFriendlyId 17 | public abstract class ContractVerifierBase { 18 | 19 | @Autowired 20 | private WebApplicationContext context; 21 | 22 | @Before 23 | public void setUp() { 24 | RestAssuredMockMvc.webAppContextSetup(context); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/test/java/com/devskiller/friendly_id/sample/contracts/FooControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.web.servlet.MockMvc; 10 | 11 | import com.devskiller.friendly_id.spring.EnableFriendlyId; 12 | 13 | import static org.hamcrest.CoreMatchers.is; 14 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 15 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 16 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 19 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; 20 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 21 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 22 | 23 | @RunWith(SpringRunner.class) 24 | @WebMvcTest(FooController.class) 25 | @EnableFriendlyId 26 | public class FooControllerTest { 27 | 28 | @Autowired 29 | MockMvc mockMvc; 30 | 31 | @Test 32 | public void shouldGet() throws Exception { 33 | mockMvc.perform(get("/foos/{id}", "cafe")) 34 | .andDo(print()) 35 | .andExpect(status().isOk()) 36 | .andExpect(content().contentType("application/hal+json")) 37 | .andExpect(jsonPath("$.uuid", is("cafe"))) 38 | .andExpect(jsonPath("$._links.self.href", is("http://localhost/foos/cafe"))); 39 | } 40 | 41 | @Test 42 | public void shouldCreate() throws Exception { 43 | mockMvc.perform(post("/foos/") 44 | .content("{\"uuid\":\"newFoo\",\"name\":\"Very New Foo\"}") 45 | .contentType("application/hal+json")) 46 | .andDo(print()) 47 | .andExpect(header().string("Location", "http://localhost/foos/newFoo")) 48 | .andExpect(status().isCreated()); 49 | } 50 | 51 | @Test 52 | public void update() throws Exception { 53 | mockMvc.perform(put("/foos/{id}", "foo") 54 | .content("{\"uuid\":\"foo\",\"name\":\"Sample Foo\"}") 55 | .contentType("application/hal+json;charset=UTF-8")) 56 | .andDo(print()) 57 | .andExpect(status().isOk()); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/test/java/com/devskiller/friendly_id/sample/contracts/MvcTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.contracts; 2 | 3 | import com.devskiller.friendly_id.FriendlyId; 4 | import com.devskiller.friendly_id.jackson.FriendlyIdModule; 5 | import com.fasterxml.jackson.annotation.JsonCreator; 6 | import com.fasterxml.jackson.databind.SerializationFeature; 7 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; 8 | import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; 9 | import io.restassured.module.mockmvc.RestAssuredMockMvc; 10 | import org.junit.Before; 11 | import org.springframework.core.convert.converter.Converter; 12 | import org.springframework.format.support.DefaultFormattingConversionService; 13 | import org.springframework.hateoas.server.EntityLinks; 14 | import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; 15 | import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 16 | import org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder; 17 | 18 | import java.util.UUID; 19 | 20 | import static org.mockito.Mockito.mock; 21 | import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; 22 | 23 | public class MvcTest { 24 | 25 | protected StandaloneMockMvcBuilder mockMvcBuilder; 26 | 27 | @Before 28 | public void setup() { 29 | mockMvcBuilder = standaloneSetup(new FooController(mock(EntityLinks.class))); 30 | DefaultFormattingConversionService service = new DefaultFormattingConversionService(); 31 | service.addConverter(new StringToUuidConverter()); 32 | mockMvcBuilder.setMessageConverters(jackson2HttpMessageConverter()).setConversionService(service); 33 | RestAssuredMockMvc.standaloneSetup(mockMvcBuilder); 34 | } 35 | 36 | public static class StringToUuidConverter implements Converter { 37 | 38 | @Override 39 | public UUID convert(String id) { 40 | return FriendlyId.toUuid(id); 41 | } 42 | } 43 | 44 | private MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { 45 | MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); 46 | Jackson2ObjectMapperBuilder builder = this.jacksonBuilder(); 47 | converter.setObjectMapper(builder.build()); 48 | return converter; 49 | } 50 | 51 | protected Jackson2ObjectMapperBuilder jacksonBuilder() { 52 | Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); 53 | builder.modules(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES), new JavaTimeModule(), new FriendlyIdModule()); 54 | builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); 55 | builder.simpleDateFormat("yyyy-MM-dd"); 56 | builder.indentOutput(true); 57 | return builder; 58 | } 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-contracts/src/test/resources/contracts/GetFoo.groovy: -------------------------------------------------------------------------------- 1 | org.springframework.cloud.contract.spec.Contract.make { 2 | request { 3 | method 'GET' 4 | url '/foos/caffe' 5 | headers { 6 | applicationJsonUtf8() 7 | } 8 | } 9 | response { 10 | status 200 11 | body( 12 | uuid: 'caffe', 13 | name: 'Foo', 14 | _links: [ 15 | self: [ 16 | href: 'http://localhost/foos/caffe' 17 | ] 18 | 19 | ] 20 | ) 21 | headers { 22 | applicationJsonUtf8() 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-customized/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | 6 | com.devskiller.friendly-id 7 | spring-boot-customized 8 | 1.1.1-SNAPSHOT 9 | 10 | 11 | org.springframework.boot 12 | spring-boot-starter-parent 13 | 2.2.2.RELEASE 14 | 15 | 16 | 17 | 18 | UTF-8 19 | UTF-8 20 | 1.8 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | com.devskiller.friendly-id 30 | friendly-id-spring-boot-starter 31 | ${project.version} 32 | 33 | 34 | 35 | com.fasterxml.jackson.module 36 | jackson-module-parameter-names 37 | 38 | 39 | 40 | org.projectlombok 41 | lombok 42 | provided 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | maven-compiler-plugin 60 | 3.8.1 61 | 62 | true 63 | 64 | 65 | 66 | org.apache.maven.plugins 67 | maven-deploy-plugin 68 | 69 | true 70 | 71 | 72 | 73 | org.jacoco 74 | jacoco-maven-plugin 75 | 0.8.5 76 | 77 | true 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-customized/src/main/java/com/devskiller/friendly_id/sample/customized/Application.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.customized; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-customized/src/main/java/com/devskiller/friendly_id/sample/customized/Bar.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.customized; 2 | 3 | import java.util.UUID; 4 | 5 | import lombok.Value; 6 | 7 | import com.devskiller.friendly_id.jackson.IdFormat; 8 | 9 | import static com.devskiller.friendly_id.jackson.FriendlyIdFormat.RAW; 10 | 11 | @Value 12 | class Bar { 13 | 14 | private final UUID friendlyId; 15 | 16 | @IdFormat(RAW) 17 | private final UUID uuid; 18 | 19 | public Bar(UUID friendlyId, @IdFormat(RAW) UUID uuid) { 20 | this.friendlyId = friendlyId; 21 | this.uuid = uuid; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-customized/src/main/java/com/devskiller/friendly_id/sample/customized/BarController.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.customized; 2 | 3 | import java.lang.invoke.MethodHandles; 4 | import java.util.UUID; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.PutMapping; 12 | import org.springframework.web.bind.annotation.RequestBody; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | @RestController 17 | @RequestMapping("/bars") 18 | public class BarController { 19 | 20 | private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); 21 | 22 | private final FooService fooService; 23 | 24 | public BarController(FooService fooService) { 25 | this.fooService = fooService; 26 | } 27 | 28 | @GetMapping("/{id}") 29 | public Bar get(@PathVariable UUID id) { 30 | log.info("get {}", id); 31 | return fooService.find(id); 32 | } 33 | 34 | @PutMapping("/{id}") 35 | public void getBar(@PathVariable UUID id, @RequestBody Bar body) { 36 | fooService.update(id, body); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-customized/src/main/java/com/devskiller/friendly_id/sample/customized/FooService.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.customized; 2 | 3 | import java.util.UUID; 4 | 5 | import org.springframework.stereotype.Service; 6 | 7 | @Service 8 | class FooService { 9 | 10 | Bar find(UUID uuid) { 11 | System.out.println("find: " + uuid); 12 | return new Bar(uuid, uuid); 13 | } 14 | 15 | void update(UUID id, Bar bar) { 16 | System.out.println("update: " + id + ":" + bar); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-customized/src/test/java/com/devskiller/friendly_id/sample/customized/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.customized; 2 | 3 | import com.devskiller.friendly_id.FriendlyId; 4 | import com.devskiller.friendly_id.spring.EnableFriendlyId; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 9 | import org.springframework.boot.test.mock.mockito.MockBean; 10 | import org.springframework.http.MediaType; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | import org.springframework.test.web.servlet.MockMvc; 13 | 14 | import java.util.UUID; 15 | 16 | import static com.devskiller.friendly_id.FriendlyId.toUuid; 17 | import static org.hamcrest.CoreMatchers.is; 18 | import static org.mockito.BDDMockito.given; 19 | import static org.mockito.BDDMockito.then; 20 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 24 | 25 | @RunWith(SpringRunner.class) 26 | @WebMvcTest(BarController.class) 27 | @EnableFriendlyId 28 | public class ApplicationTest { 29 | 30 | @Autowired 31 | MockMvc mockMvc; 32 | 33 | @MockBean 34 | FooService fooService; 35 | 36 | @Test 37 | public void shouldSerialize() throws Exception { 38 | 39 | // given 40 | UUID uuid = UUID.randomUUID(); 41 | given(fooService.find(uuid)).willReturn(new Bar(uuid, uuid)); 42 | 43 | // expect 44 | mockMvc.perform(get("/bars/{id}", FriendlyId.toFriendlyId(uuid))) 45 | .andDo(print()) 46 | .andExpect(status().isOk()) 47 | .andExpect(content().contentType(MediaType.APPLICATION_JSON)) 48 | .andExpect(jsonPath("$.friendlyId", is(FriendlyId.toFriendlyId(uuid)))) 49 | .andExpect(jsonPath("$.uuid", is(uuid.toString()))); 50 | } 51 | 52 | @Test 53 | public void shouldDeserialize() throws Exception { 54 | 55 | // given 56 | UUID uuid = UUID.randomUUID(); 57 | String json = "{\"friendlyId\":\"" + FriendlyId.toFriendlyId(uuid) + "\",\"uuid\":\"" + uuid + "\"}"; 58 | 59 | // when 60 | mockMvc.perform(put("/bars/{id}", FriendlyId.toFriendlyId(uuid)) 61 | .content(json) 62 | .contentType(MediaType.APPLICATION_JSON)) 63 | .andDo(print()) 64 | .andExpect(status().isOk()); 65 | 66 | // then 67 | then(fooService) 68 | .should().update(uuid, new Bar(uuid, uuid)); 69 | } 70 | 71 | @Test 72 | public void sampleTestUsingPseudoUuid() throws Exception { 73 | 74 | // given 75 | UUID barId = toUuid("barId"); 76 | given(fooService.find(barId)).willReturn(new Bar(barId, barId)); 77 | 78 | // expect 79 | mockMvc.perform(get("/bars/{id}", "barId")) 80 | .andDo(print()) 81 | .andExpect(status().isOk()) 82 | .andExpect(content().contentType(MediaType.APPLICATION_JSON)) 83 | .andExpect(jsonPath("$.friendlyId", is("barId"))) 84 | .andExpect(jsonPath("$.uuid", is(barId.toString()))); 85 | 86 | System.out.println(barId); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | 6 | com.devskiller.friendly-id 7 | spring-boot-hateos 8 | 1.1.1-SNAPSHOT 9 | 10 | 11 | org.springframework.boot 12 | spring-boot-starter-parent 13 | 2.2.2.RELEASE 14 | 15 | 16 | 17 | 18 | UTF-8 19 | UTF-8 20 | 1.8 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | com.devskiller.friendly-id 30 | friendly-id-spring-boot-starter 31 | ${project.version} 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-hateoas 36 | 37 | 38 | org.atteo 39 | evo-inflector 40 | 1.2.2 41 | 42 | 43 | com.fasterxml.jackson.module 44 | jackson-module-parameter-names 45 | 46 | 47 | com.fasterxml.jackson.datatype 48 | jackson-datatype-jdk8 49 | 50 | 51 | com.fasterxml.jackson.datatype 52 | jackson-datatype-jsr310 53 | 54 | 55 | 56 | org.projectlombok 57 | lombok 58 | provided 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-test 64 | test 65 | 66 | 67 | 68 | 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-maven-plugin 73 | 74 | 75 | maven-compiler-plugin 76 | 3.8.0 77 | 78 | 79 | org.apache.maven.plugins 80 | maven-deploy-plugin 81 | 82 | true 83 | 84 | 85 | 86 | org.jacoco 87 | jacoco-maven-plugin 88 | 0.8.3 89 | 90 | true 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/Application.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/BarController.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import com.devskiller.friendly_id.sample.hateos.domain.Bar; 4 | import com.devskiller.friendly_id.sample.hateos.domain.Foo; 5 | import org.springframework.hateoas.server.ExposesResourceFor; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.util.UUID; 12 | 13 | @RestController 14 | @ExposesResourceFor(BarResource.class) 15 | @RequestMapping("/foos/{fooId}/bars") 16 | public class BarController { 17 | 18 | private final BarResourceAssembler assembler; 19 | 20 | public BarController(BarResourceAssembler assembler) { 21 | this.assembler = assembler; 22 | } 23 | 24 | @GetMapping("/{id}") 25 | public BarResource getBar(@PathVariable UUID fooId, @PathVariable UUID id) { 26 | return assembler.toModel(new Bar(id, "Bar", new Foo(fooId, "Root Foo"))); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/BarResource.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import lombok.Value; 4 | import org.springframework.hateoas.RepresentationModel; 5 | import org.springframework.hateoas.server.core.Relation; 6 | 7 | @Relation(value = "bar", collectionRelation = "bars") 8 | @Value 9 | class BarResource extends RepresentationModel { 10 | 11 | private String name; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/BarResourceAssembler.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import com.devskiller.friendly_id.sample.hateos.domain.Bar; 4 | import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; 5 | import org.springframework.hateoas.server.mvc.WebMvcLinkBuilderFactory; 6 | 7 | import static com.devskiller.friendly_id.FriendlyId.toFriendlyId; 8 | 9 | public class BarResourceAssembler extends RepresentationModelAssemblerSupport { 10 | 11 | public BarResourceAssembler() { 12 | super(BarController.class, BarResource.class); 13 | } 14 | 15 | @Override 16 | public BarResource toModel(Bar entity) { 17 | BarResource resource = new BarResource(entity.getName()); 18 | WebMvcLinkBuilderFactory factory = new WebMvcLinkBuilderFactory(); 19 | resource.add(factory.linkTo(FooController.class).withRel("foos")); 20 | resource.add(factory.linkTo(BarController.class, toFriendlyId(entity.getFoo().getId())).slash(toFriendlyId(entity.getId())).withSelfRel()); 21 | return resource; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/FooController.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import com.devskiller.friendly_id.sample.hateos.domain.Foo; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.hateoas.server.ExposesResourceFor; 7 | import org.springframework.http.HttpEntity; 8 | import org.springframework.http.HttpHeaders; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.*; 12 | import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; 13 | 14 | import java.lang.invoke.MethodHandles; 15 | import java.net.URI; 16 | import java.util.UUID; 17 | 18 | import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on; 19 | 20 | @RestController 21 | @ExposesResourceFor(FooResource.class) 22 | @RequestMapping("/foos") 23 | public class FooController { 24 | 25 | private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); 26 | 27 | private final FooResourceAssembler assembler; 28 | 29 | public FooController(FooResourceAssembler assembler) { 30 | this.assembler = assembler; 31 | } 32 | 33 | @GetMapping("/{id}") 34 | public HttpEntity get(@PathVariable UUID id) { 35 | log.info("Get {}", id); 36 | Foo foo = new Foo(id, "Foo"); 37 | 38 | FooResource fooResource = assembler.toModel(foo); 39 | return ResponseEntity.ok(fooResource); 40 | } 41 | 42 | @PutMapping("/{id}") 43 | public HttpEntity update(@PathVariable UUID id, @RequestBody FooResource fooResource) { 44 | log.info("Update {} : {}", id, fooResource); 45 | Foo entity = new Foo(fooResource.getUuid(), fooResource.getName()); 46 | return ResponseEntity.ok(assembler.toModel(entity)); 47 | } 48 | 49 | @PostMapping 50 | public HttpEntity create(@RequestBody FooResource fooResource) { 51 | HttpHeaders headers = new HttpHeaders(); 52 | Foo entity = new Foo(fooResource.getUuid(), "Foo"); 53 | 54 | // ... 55 | URI location = MvcUriComponentsBuilder.fromMethodCall(on(getClass()) 56 | .get(fooResource.getUuid())) 57 | .buildAndExpand() 58 | .toUri(); 59 | 60 | headers.setLocation(location); 61 | 62 | return new ResponseEntity<>(headers, HttpStatus.CREATED); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/FooResource.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 4 | import lombok.Value; 5 | import org.springframework.hateoas.CollectionModel; 6 | import org.springframework.hateoas.RepresentationModel; 7 | import org.springframework.hateoas.server.core.Relation; 8 | 9 | import java.util.UUID; 10 | 11 | @Relation(value = "foos") 12 | @Value 13 | public class FooResource extends RepresentationModel { 14 | 15 | private final UUID uuid; 16 | private final String name; 17 | @JsonUnwrapped 18 | private final CollectionModel embeddeds; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/FooResourceAssembler.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import com.devskiller.friendly_id.sample.hateos.domain.Bar; 4 | import com.devskiller.friendly_id.sample.hateos.domain.Foo; 5 | import org.springframework.hateoas.CollectionModel; 6 | import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; 7 | import org.springframework.hateoas.server.mvc.WebMvcLinkBuilderFactory; 8 | 9 | import java.util.Arrays; 10 | import java.util.List; 11 | import java.util.UUID; 12 | 13 | import static com.devskiller.friendly_id.FriendlyId.toFriendlyId; 14 | 15 | public class FooResourceAssembler extends RepresentationModelAssemblerSupport { 16 | 17 | public FooResourceAssembler() { 18 | super(FooController.class, FooResource.class); 19 | } 20 | 21 | @Override 22 | public FooResource toModel(Foo entity) { 23 | BarResourceAssembler barResourceAssembler = new BarResourceAssembler(); 24 | List bars = Arrays.asList(new Bar(UUID.randomUUID(), "bar one", entity), 25 | new Bar(UUID.randomUUID(), "bar two", entity)); 26 | CollectionModel barResources = barResourceAssembler.toCollectionModel(bars); 27 | WebMvcLinkBuilderFactory factory = new WebMvcLinkBuilderFactory(); 28 | FooResource resource = new FooResource(entity.getId(), entity.getName(), barResources); 29 | 30 | resource.add(factory.linkTo(FooController.class).slash(toFriendlyId(entity.getId())).withSelfRel()); 31 | return resource; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/JsonConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | 7 | @Configuration 8 | public class JsonConfiguration implements WebMvcConfigurer { 9 | 10 | // This is declared as part of WebMVC slice, used in testing 11 | @Bean 12 | public FooResourceAssembler fooResourceAssembler() { 13 | return new FooResourceAssembler(); 14 | } 15 | 16 | // This is declared as part of WebMVC slice, used in testing 17 | @Bean 18 | public BarResourceAssembler barResourceAssembler() { 19 | return new BarResourceAssembler(); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/domain/Bar.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | import java.util.UUID; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | public class Bar { 11 | 12 | private UUID id; 13 | private String name; 14 | 15 | private Foo foo; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/domain/Foo.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | import java.util.UUID; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | public class Foo { 11 | 12 | private UUID id; 13 | private String name; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/test/java/com/devskiller/friendly_id/sample/hateos/BarControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.web.servlet.MockMvc; 10 | 11 | import com.devskiller.friendly_id.spring.EnableFriendlyId; 12 | 13 | import static org.hamcrest.CoreMatchers.is; 14 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 15 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 16 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 19 | 20 | @RunWith(SpringRunner.class) 21 | @WebMvcTest(BarController.class) 22 | @EnableFriendlyId 23 | public class BarControllerTest { 24 | 25 | @Autowired 26 | MockMvc mockMvc; 27 | 28 | @Test 29 | public void shouldGet() throws Exception { 30 | mockMvc.perform(get("/foos/{fooId}/bars/{barId}", "foo", "bar")) 31 | .andDo(print()) 32 | .andExpect(status().isOk()) 33 | .andExpect(content().contentType("application/hal+json")) 34 | .andExpect(jsonPath("$.name", is("Bar"))) 35 | .andExpect(jsonPath("$._links.self.href", is("http://localhost/foos/foo/bars/bar"))) 36 | .andExpect(jsonPath("$._links.foos.href", is("http://localhost/foos"))); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-hateos/src/test/java/com/devskiller/friendly_id/sample/hateos/FooControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.hateos; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.web.servlet.MockMvc; 10 | 11 | import com.devskiller.friendly_id.spring.EnableFriendlyId; 12 | 13 | import static org.hamcrest.CoreMatchers.is; 14 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 15 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 16 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 19 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; 20 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 21 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 22 | 23 | @RunWith(SpringRunner.class) 24 | @WebMvcTest 25 | @EnableFriendlyId // STRANGE: Why this is required? 26 | public class FooControllerTest { 27 | 28 | @Autowired 29 | MockMvc mockMvc; 30 | 31 | @Test 32 | public void shouldGet() throws Exception { 33 | mockMvc.perform(get("/foos/{id}", "cafe")) 34 | .andDo(print()) 35 | .andExpect(status().isOk()) 36 | .andExpect(content().contentType("application/hal+json")) 37 | .andExpect(jsonPath("$.uuid", is("cafe"))) 38 | .andExpect(jsonPath("$._links.self.href", is("http://localhost/foos/cafe"))); 39 | } 40 | 41 | @Test 42 | public void shouldCreate() throws Exception { 43 | mockMvc.perform(post("/foos/") 44 | .content("{\"uuid\":\"newFoo\",\"name\":\"Very New Foo\"}") 45 | .contentType("application/hal+json")) 46 | .andDo(print()) 47 | .andExpect(header().string("Location", "http://localhost/foos/newFoo")) 48 | .andExpect(status().isCreated()); 49 | } 50 | 51 | @Test 52 | public void update() throws Exception { 53 | mockMvc.perform(put("/foos/{id}", "foo") 54 | .content("{\"uuid\":\"foo\",\"name\":\"Sample Foo\"}") 55 | .contentType("application/hal+json")) 56 | .andDo(print()) 57 | .andExpect(status().isOk()); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-simple/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | 6 | com.devskiller.friendly-id 7 | spring-boot-simple 8 | 1.1.1-SNAPSHOT 9 | 10 | 11 | org.springframework.boot 12 | spring-boot-starter-parent 13 | 2.2.2.RELEASE 14 | 15 | 16 | 17 | 18 | UTF-8 19 | UTF-8 20 | 1.8 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | com.devskiller.friendly-id 30 | friendly-id-spring-boot-starter 31 | ${project.version} 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-test 37 | test 38 | 39 | 40 | 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-maven-plugin 46 | 47 | 48 | maven-compiler-plugin 49 | 3.8.0 50 | 51 | 52 | org.apache.maven.plugins 53 | maven-deploy-plugin 54 | 55 | true 56 | 57 | 58 | 59 | org.jacoco 60 | jacoco-maven-plugin 61 | 0.8.3 62 | 63 | true 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-simple/src/main/java/com/devskiller/friendly_id/sample/simple/Application.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.simple; 2 | 3 | import java.util.UUID; 4 | 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @SpringBootApplication 13 | public class Application { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(Application.class, args); 17 | } 18 | 19 | @GetMapping("/bars/{id}") 20 | Bar getBar(@PathVariable UUID id) { 21 | Bar bar = new Bar(); 22 | bar.setId(id); 23 | return bar; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-simple/src/main/java/com/devskiller/friendly_id/sample/simple/Bar.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.simple; 2 | 3 | import java.util.UUID; 4 | 5 | public class Bar { 6 | 7 | private UUID id; 8 | 9 | public UUID getId() { 10 | return id; 11 | } 12 | 13 | public void setId(UUID id) { 14 | this.id = id; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /friendly-id-samples/friendly-id-spring-boot-simple/src/test/java/com/devskiller/friendly_id/sample/simple/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.sample.simple; 2 | 3 | import java.util.UUID; 4 | 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.boot.test.web.client.TestRestTemplate; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import static org.assertj.core.api.BDDAssertions.then; 14 | 15 | @RunWith(SpringRunner.class) 16 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 17 | public class ApplicationTest { 18 | 19 | @Autowired 20 | private TestRestTemplate restTemplate; 21 | 22 | 23 | @Test 24 | public void shouldSerialize() { 25 | 26 | // given 27 | UUID uuid = UUID.randomUUID(); 28 | 29 | // expect 30 | Bar entity = restTemplate.getForEntity("/bars/{id}", Bar.class, uuid).getBody(); 31 | 32 | then(entity.getId()).isEqualTo(uuid); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /friendly-id-samples/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | friendly-id-samples 6 | pom 7 | 8 | 9 | com.devskiller.friendly-id 10 | friendly-id-project 11 | 1.1.1-SNAPSHOT 12 | .. 13 | 14 | 15 | 16 | friendly-id-spring-boot-simple 17 | friendly-id-spring-boot-customized 18 | friendly-id-spring-boot-hateos 19 | friendly-id-contracts 20 | 21 | 22 | 23 | 24 | 25 | maven-install-plugin 26 | 27 | true 28 | 29 | 30 | 31 | 32 | 33 | 34 | org.jacoco 35 | jacoco-maven-plugin 36 | 37 | true 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /friendly-id-spring-boot-starter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | com.devskiller.friendly-id 5 | friendly-id-project 6 | 1.1.1-SNAPSHOT 7 | .. 8 | 9 | 4.0.0 10 | 11 | friendly-id-spring-boot-starter 12 | 13 | 14 | 15 | com.devskiller.friendly-id 16 | friendly-id-spring-boot 17 | ${project.version} 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter 22 | provided 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-autoconfigure-processor 27 | true 28 | 29 | 30 | -------------------------------------------------------------------------------- /friendly-id-spring-boot-starter/src/main/java/com/devskiller/friendly_id/boot/FriendlyIdAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.boot; 2 | 3 | import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.devskiller.friendly_id.spring.EnableFriendlyId; 7 | 8 | @Configuration 9 | @ConditionalOnExpression("${com.devskiller.friendly_id.auto:true}") 10 | @EnableFriendlyId 11 | public class FriendlyIdAutoConfiguration { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /friendly-id-spring-boot-starter/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration = com.devskiller.friendly_id.boot.FriendlyIdAutoConfiguration -------------------------------------------------------------------------------- /friendly-id-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports: -------------------------------------------------------------------------------- 1 | com.devskiller.friendly_id.boot.FriendlyIdAutoConfiguration 2 | -------------------------------------------------------------------------------- /friendly-id-spring-boot/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | com.devskiller.friendly-id 5 | friendly-id-project 6 | 1.1.1-SNAPSHOT 7 | .. 8 | 9 | 4.0.0 10 | 11 | friendly-id-spring-boot 12 | 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter 17 | provided 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | com.devskiller.friendly-id 25 | friendly-id-jackson-datatype 26 | ${project.version} 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /friendly-id-spring-boot/src/main/java/com/devskiller/friendly_id/spring/EnableFriendlyId.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.spring; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import org.springframework.context.annotation.Import; 9 | 10 | @Target(ElementType.TYPE) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Import(FriendlyIdConfiguration.class) 13 | public @interface EnableFriendlyId { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /friendly-id-spring-boot/src/main/java/com/devskiller/friendly_id/spring/FriendlyIdConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id.spring; 2 | 3 | import java.util.UUID; 4 | 5 | import com.fasterxml.jackson.databind.Module; 6 | 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.core.convert.converter.Converter; 10 | import org.springframework.format.FormatterRegistry; 11 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 12 | 13 | import com.devskiller.friendly_id.FriendlyId; 14 | import com.devskiller.friendly_id.jackson.FriendlyIdModule; 15 | 16 | @Configuration 17 | public class FriendlyIdConfiguration implements WebMvcConfigurer { 18 | 19 | @Override 20 | public void addFormatters(FormatterRegistry registry) { 21 | registry.addConverter(new StringToUuidConverter()); 22 | registry.addConverter(new UuidToStringConverter()); 23 | } 24 | 25 | @Bean 26 | public Module friendlyIdModule() { 27 | return new FriendlyIdModule(); 28 | } 29 | 30 | //FIXME: make this public 31 | public static class StringToUuidConverter implements Converter { 32 | 33 | @Override 34 | public UUID convert(String id) { 35 | return FriendlyId.toUuid(id); 36 | } 37 | } 38 | 39 | 40 | public static class UuidToStringConverter implements Converter { 41 | 42 | @Override 43 | public String convert(UUID id) { 44 | return FriendlyId.toFriendlyId(id); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /friendly-id/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | 7 | com.devskiller.friendly-id 8 | friendly-id-project 9 | 1.1.1-SNAPSHOT 10 | .. 11 | 12 | 13 | friendly-id 14 | 15 | 16 | 17 | junit 18 | junit 19 | test 20 | 21 | 22 | org.assertj 23 | assertj-core 24 | test 25 | 26 | 27 | io.vavr 28 | vavr-test 29 | test 30 | 31 | 32 | 33 | 34 | 35 | jmh 36 | 37 | 38 | 39 | org.codehaus.mojo 40 | build-helper-maven-plugin 41 | 3.0.0 42 | 43 | 44 | 45 | add-test-source 46 | add-test-resource 47 | 48 | 49 | 50 | src/jmh/java 51 | 52 | 53 | 54 | src/jmh/resources 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | org.apache.maven.plugins 63 | maven-compiler-plugin 64 | 65 | 66 | 67 | testCompile 68 | 69 | 70 | 71 | 72 | org.openjdk.jmh 73 | jmh-generator-annprocess 74 | ${jmh.version} 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | org.codehaus.mojo 83 | exec-maven-plugin 84 | 1.6.0 85 | 86 | 87 | run-benchmarks 88 | integration-test 89 | 90 | exec 91 | 92 | 93 | test 94 | java 95 | 96 | -classpath 97 | 98 | org.openjdk.jmh.Main 99 | .* 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | org.openjdk.jmh 110 | jmh-core 111 | 1.22 112 | test 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /friendly-id/src/jmh/java/com/devskiller/friendly_id/FriendlyIdBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.util.UUID; 4 | 5 | import org.openjdk.jmh.annotations.Benchmark; 6 | import org.openjdk.jmh.annotations.Fork; 7 | import org.openjdk.jmh.annotations.Measurement; 8 | import org.openjdk.jmh.annotations.OperationsPerInvocation; 9 | import org.openjdk.jmh.annotations.Scope; 10 | import org.openjdk.jmh.annotations.Setup; 11 | import org.openjdk.jmh.annotations.State; 12 | import org.openjdk.jmh.annotations.Warmup; 13 | import org.openjdk.jmh.infra.Blackhole; 14 | import org.openjdk.jmh.runner.Runner; 15 | import org.openjdk.jmh.runner.RunnerException; 16 | import org.openjdk.jmh.runner.options.Options; 17 | import org.openjdk.jmh.runner.options.OptionsBuilder; 18 | 19 | @State(Scope.Benchmark) 20 | @Warmup(iterations = 3) 21 | @Measurement(iterations = 10) 22 | @Fork(2) 23 | public class FriendlyIdBenchmark { 24 | 25 | static final int SIZE = 1_000_000; 26 | 27 | UUID[] uuids; 28 | String[] ids; 29 | 30 | public static void main(String[] args) throws RunnerException { 31 | Options opt = new OptionsBuilder() 32 | .include(FriendlyIdBenchmark.class.getSimpleName()) 33 | .build(); 34 | 35 | new Runner(opt).run(); 36 | } 37 | 38 | @Setup 39 | public void setup() { 40 | uuids = new UUID[SIZE]; 41 | ids = new String[SIZE]; 42 | for (int i = 0; i < SIZE; i++) { 43 | uuids[i] = UUID.randomUUID(); 44 | ids[i] = FriendlyId.toFriendlyId(uuids[i]); 45 | } 46 | } 47 | 48 | @Benchmark 49 | @OperationsPerInvocation(SIZE) 50 | public void serializeUuid(Blackhole blackhole) { 51 | for (int i = 0; i < SIZE; i++) { 52 | blackhole.consume(FriendlyId.toFriendlyId(uuids[i])); 53 | } 54 | } 55 | 56 | @Benchmark 57 | @OperationsPerInvocation(SIZE) 58 | public void deserializeId(Blackhole blackhole) { 59 | for (int i = 0; i < SIZE; i++) { 60 | blackhole.consume(FriendlyId.toUuid(ids[i])); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /friendly-id/src/jmh/java/com/devskiller/friendly_id/UuidConverterBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Random; 5 | import java.util.UUID; 6 | 7 | import org.openjdk.jmh.annotations.Benchmark; 8 | import org.openjdk.jmh.annotations.Fork; 9 | import org.openjdk.jmh.annotations.Measurement; 10 | import org.openjdk.jmh.annotations.OperationsPerInvocation; 11 | import org.openjdk.jmh.annotations.Scope; 12 | import org.openjdk.jmh.annotations.Setup; 13 | import org.openjdk.jmh.annotations.State; 14 | import org.openjdk.jmh.annotations.Warmup; 15 | import org.openjdk.jmh.infra.Blackhole; 16 | import org.openjdk.jmh.runner.Runner; 17 | import org.openjdk.jmh.runner.RunnerException; 18 | import org.openjdk.jmh.runner.options.Options; 19 | import org.openjdk.jmh.runner.options.OptionsBuilder; 20 | 21 | @State(Scope.Benchmark) 22 | @Warmup(iterations = 3) 23 | @Measurement(iterations = 10) 24 | @Fork(2) 25 | public class UuidConverterBenchmark { 26 | 27 | static final int SIZE = 1_000_000; 28 | 29 | UUID[] uuids; 30 | BigInteger[] ids; 31 | 32 | public static void main(String[] args) throws RunnerException { 33 | Options opt = new OptionsBuilder() 34 | .include(UuidConverterBenchmark.class.getSimpleName()) 35 | .build(); 36 | new Runner(opt).run(); 37 | } 38 | 39 | @Setup 40 | public void setup() { 41 | uuids = new UUID[SIZE]; 42 | ids = new BigInteger[SIZE]; 43 | for (int i = 0; i < SIZE; i++) { 44 | uuids[i] = UUID.randomUUID(); 45 | ids[i] = new BigInteger(127, new Random()); 46 | } 47 | } 48 | 49 | @Benchmark 50 | @OperationsPerInvocation(SIZE) 51 | public void convertToBigInteger(Blackhole blackhole) { 52 | for (int i = 0; i < SIZE; i++) { 53 | blackhole.consume(UuidConverter.toBigInteger(uuids[i])); 54 | } 55 | } 56 | 57 | @Benchmark 58 | @OperationsPerInvocation(SIZE) 59 | public void convertFromBigInteger(Blackhole blackhole) { 60 | for (int i = 0; i < SIZE; i++) { 61 | blackhole.consume(UuidConverter.toUuid(ids[i])); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /friendly-id/src/jmh/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %d{HH:mm:ss.SSS} ${LEVEL:-%6p} [%-9t] %-42logger{39} : %m%n 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /friendly-id/src/main/java/com/devskiller/friendly_id/Base62.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.math.BigInteger; 4 | import java.util.function.BiFunction; 5 | import java.util.regex.Pattern; 6 | import java.util.stream.IntStream; 7 | 8 | import static java.util.Objects.requireNonNull; 9 | 10 | /** 11 | * Base62 encoder/decoder. 12 | *

13 | * This is free and unencumbered public domain software 14 | *

15 | * Source: https://github.com/opencoinage/opencoinage/blob/master/src/java/org/opencoinage/util/Base62.java 16 | */ 17 | class Base62 { 18 | 19 | private static final BigInteger BASE = BigInteger.valueOf(62); 20 | private static final String DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; 21 | 22 | /** 23 | * Encodes a number using Base62 encoding. 24 | * 25 | * @param number a positive integer 26 | * @return a Base62 string 27 | * 28 | * @throws IllegalArgumentException if number is a negative integer 29 | */ 30 | static String encode(BigInteger number) { 31 | if (number.compareTo(BigInteger.ZERO) < 0) { 32 | throwIllegalArgumentException("number must not be negative"); 33 | } 34 | StringBuilder result = new StringBuilder(); 35 | while (number.compareTo(BigInteger.ZERO) > 0) { 36 | BigInteger[] divmod = number.divideAndRemainder(BASE); 37 | number = divmod[0]; 38 | int digit = divmod[1].intValue(); 39 | result.insert(0, DIGITS.charAt(digit)); 40 | } 41 | return (result.length() == 0) ? DIGITS.substring(0, 1) : result.toString(); 42 | } 43 | 44 | private static BigInteger throwIllegalArgumentException(String format, Object... args) { 45 | throw new IllegalArgumentException(String.format(format, args)); 46 | } 47 | 48 | /** 49 | * Decodes a string using Base62 encoding. 50 | * 51 | * @param string a Base62 string 52 | * @return a positive integer 53 | * 54 | * @throws IllegalArgumentException if string is empty 55 | */ 56 | static BigInteger decode(final String string) { 57 | return decode(string, 128); 58 | } 59 | 60 | static BigInteger decode(final String string, int bitLimit) { 61 | requireNonNull(string, "Decoded string must not be null"); 62 | if (string.length() == 0) { 63 | return throwIllegalArgumentException("String '%s' must not be empty", string); 64 | } 65 | 66 | if (!Pattern.matches("[" + DIGITS + "]*", string)) { 67 | throwIllegalArgumentException("String '%s' contains illegal characters, only '%s' are allowed", string, DIGITS); 68 | } 69 | 70 | return IntStream.range(0, string.length()) 71 | .mapToObj(index -> BigInteger.valueOf(charAt.apply(string, index)).multiply(BASE.pow(index))) 72 | .reduce(BigInteger.ZERO, (acc, value) -> { 73 | BigInteger sum = acc.add(value); 74 | if (bitLimit > 0 && sum.bitLength() > bitLimit) { 75 | throwIllegalArgumentException("String '%s' contains more than 128bit information", string); 76 | } 77 | return sum; 78 | }); 79 | 80 | } 81 | 82 | private static BiFunction charAt = (string, index) -> 83 | DIGITS.indexOf(string.charAt(string.length() - index - 1)); 84 | 85 | } -------------------------------------------------------------------------------- /friendly-id/src/main/java/com/devskiller/friendly_id/BigIntegerPairing.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.math.BigInteger; 4 | import java.util.function.Function; 5 | 6 | /** 7 | * Basing on snippet published by drmalex07 8 | *

9 | * https://gist.github.com/drmalex07/9008c611ffde6cb2ef3a2db8668bc251 10 | */ 11 | class BigIntegerPairing { 12 | 13 | private static final BigInteger HALF = BigInteger.ONE.shiftLeft(64); // 2^64 14 | private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); 15 | 16 | private static Function toUnsigned = value 17 | -> value.signum() < 0 ? value.add(HALF) : value; 18 | private static Function toSigned = 19 | value -> MAX_LONG.compareTo(value) < 0 ? value.subtract(HALF) : value; 20 | 21 | static BigInteger pair(BigInteger hi, BigInteger lo) { 22 | BigInteger unsignedLo = toUnsigned.apply(lo); 23 | BigInteger unsignedHi = toUnsigned.apply(hi); 24 | return unsignedLo.add(unsignedHi.multiply(HALF)); 25 | } 26 | 27 | static BigInteger[] unpair(BigInteger value) { 28 | BigInteger[] parts = value.divideAndRemainder(HALF); 29 | BigInteger signedHi = toSigned.apply(parts[0]); 30 | BigInteger signedLo = toSigned.apply(parts[1]); 31 | return new BigInteger[]{signedHi, signedLo}; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.util.UUID; 4 | 5 | /** 6 | * Class to convert UUID to url Friendly IDs basing on Url62 7 | */ 8 | public class FriendlyId { 9 | 10 | /** 11 | * Create FriendlyId id 12 | * 13 | * @return Friendly Id encoded UUID 14 | */ 15 | public static String createFriendlyId() { 16 | return Url62.encode(UUID.randomUUID()); 17 | } 18 | 19 | /** 20 | * Encode UUID to FriendlyId id 21 | * 22 | * @param uuid UUID to be encoded 23 | * @return Friendly Id encoded UUID 24 | */ 25 | public static String toFriendlyId(UUID uuid) { 26 | return Url62.encode(uuid); 27 | } 28 | 29 | /** 30 | * Decode Friendly Id to UUID 31 | * 32 | * @param friendlyId encoded UUID 33 | * @return decoded UUID 34 | */ 35 | public static UUID toUuid(String friendlyId) { 36 | return Url62.decode(friendlyId); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /friendly-id/src/main/java/com/devskiller/friendly_id/Url62.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.math.BigInteger; 4 | import java.util.UUID; 5 | 6 | /** 7 | * Class to convert UUID to Url62 IDs 8 | */ 9 | class Url62 { 10 | 11 | /** 12 | * Encode UUID to Url62 id 13 | * 14 | * @param uuid UUID to be encoded 15 | * @return url62 encoded UUID 16 | */ 17 | static String encode(UUID uuid) { 18 | BigInteger pair = UuidConverter.toBigInteger(uuid); 19 | return Base62.encode(pair); 20 | } 21 | 22 | /** 23 | * Decode url62 id to UUID 24 | * 25 | * @param id url62 encoded id 26 | * @return decoded UUID 27 | */ 28 | static UUID decode(String id) { 29 | BigInteger decoded = Base62.decode(id); 30 | return UuidConverter.toUuid(decoded); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /friendly-id/src/main/java/com/devskiller/friendly_id/UuidConverter.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.math.BigInteger; 4 | import java.util.UUID; 5 | 6 | class UuidConverter { 7 | 8 | static BigInteger toBigInteger(UUID uuid) { 9 | return BigIntegerPairing.pair( 10 | BigInteger.valueOf(uuid.getMostSignificantBits()), 11 | BigInteger.valueOf(uuid.getLeastSignificantBits()) 12 | ); 13 | } 14 | 15 | static UUID toUuid(BigInteger value) { 16 | BigInteger[] unpaired = BigIntegerPairing.unpair(value); 17 | return new UUID(unpaired[0].longValueExact(), unpaired[1].longValueExact()); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /friendly-id/src/test/java/com/devskiller/friendly_id/AnalyzeGeneratedIdsTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.util.ArrayList; 4 | import java.util.IntSummaryStatistics; 5 | import java.util.List; 6 | import java.util.UUID; 7 | import java.util.stream.Collectors; 8 | 9 | import org.junit.Test; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | 13 | public class AnalyzeGeneratedIdsTest { 14 | 15 | private List ids = new ArrayList<>(); 16 | 17 | @Test 18 | public void analyzeGeneratedValueStatistics() { 19 | for (int i = 0; i < 100_000; i++) { 20 | this.ids.add(Base62.encode(UuidConverter.toBigInteger(UUID.randomUUID()))); 21 | } 22 | IntSummaryStatistics stats = ids.stream().map(String::length).mapToInt(Integer::intValue).summaryStatistics(); 23 | 24 | System.out.println("\nResults:"); 25 | System.out.println("Min: " + stats.getMin()); 26 | System.out.println("Max: " + stats.getMax()); 27 | System.out.println("Avg: " + stats.getAverage()); 28 | System.out.println("Count: " + stats.getCount()); 29 | System.out.println("Sample: \n" + ids.stream().limit(100).collect(Collectors.joining("\n"))); 30 | 31 | assertThat(stats.getMax()).isEqualTo(22); 32 | assertThat(stats.getMin()).isGreaterThanOrEqualTo(17); 33 | assertThat(stats.getAverage()).isLessThanOrEqualTo(22); 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /friendly-id/src/test/java/com/devskiller/friendly_id/Base62Test.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import org.junit.Test; 4 | 5 | import static com.devskiller.friendly_id.IdUtil.areEqualIgnoringLeadingZeros; 6 | import static io.vavr.test.Property.def; 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 9 | import static org.assertj.core.util.Objects.areEqual; 10 | 11 | public class Base62Test { 12 | 13 | @Test 14 | public void decodingValuePrefixedWithZeros() { 15 | assertThat(Base62.encode(Base62.decode("00001"))).isEqualTo("1"); 16 | assertThat(Base62.encode(Base62.decode("01001"))).isEqualTo("1001"); 17 | assertThat(Base62.encode(Base62.decode("00abcd"))).isEqualTo("abcd"); 18 | } 19 | 20 | @Test 21 | public void shouldCheck128BitLimits() { 22 | assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> 23 | Base62.decode("1Vkp6axDWu5pI3q1xQO3oO0")); 24 | } 25 | 26 | @Test 27 | public void decodingIdShouldBeReversible() { 28 | def("areEqualIgnoringLeadingZeros(Base62.toFriendlyId(Base62.toUuid(id)), id)") 29 | .forAll(DataProvider.FRIENDLY_IDS) 30 | .suchThat(id -> areEqualIgnoringLeadingZeros(Base62.encode(Base62.decode(id)), id)) 31 | .check(24, 100_000) 32 | .assertIsSatisfied(); 33 | } 34 | 35 | @Test 36 | public void encodingNumberShouldBeReversible() { 37 | def("areEqualIgnoringLeadingZeros(Base62.toFriendlyId(Base62.toUuid(id)), id)") 38 | .forAll(DataProvider.POSITIVE_BIG_INTEGERS) 39 | .suchThat(bigInteger -> areEqual(Base62.decode(Base62.encode(bigInteger)), bigInteger) 40 | ) 41 | .check(-1, 100_000) 42 | .assertIsSatisfied(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /friendly-id/src/test/java/com/devskiller/friendly_id/BigIntegerPairingTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Arrays; 5 | 6 | import io.vavr.Tuple2; 7 | import org.junit.Test; 8 | 9 | import static com.devskiller.friendly_id.BigIntegerPairing.pair; 10 | import static com.devskiller.friendly_id.BigIntegerPairing.unpair; 11 | import static io.vavr.test.Property.def; 12 | import static java.math.BigInteger.valueOf; 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | 15 | public class BigIntegerPairingTest { 16 | 17 | @Test 18 | public void shouldPairTwoLongs() { 19 | long x = 1; 20 | long y = 2; 21 | 22 | BigInteger z = pair(valueOf(1), valueOf(2)); 23 | 24 | assertThat(unpair(z)).contains(valueOf(x), valueOf(y)); 25 | } 26 | 27 | @Test 28 | public void resultOfPairingShouldBePositive() { 29 | def("pair(longs).signum() > 0") 30 | .forAll(DataProvider.LONG_PAIRS) 31 | .suchThat(longs -> makePair(longs).signum() > 0) 32 | .check(-1, 100_000) 33 | .assertIsSatisfied(); 34 | } 35 | 36 | private BigInteger makePair(Tuple2 longs) { 37 | return longs.apply((x, y) -> pair(valueOf(x), valueOf(y))); 38 | } 39 | 40 | @Test 41 | public void pairingLongsShouldBeReversible() { 42 | def("Arrays.equals(unpair(pair(longs)), asArray(longs))") 43 | .forAll(DataProvider.LONG_PAIRS) 44 | .suchThat(longs -> Arrays.equals(unpair(makePair(longs)), asArray(longs))) 45 | .check(-1, 100_000) 46 | .assertIsSatisfied(); 47 | } 48 | 49 | private BigInteger[] asArray(Tuple2 longsPair) { 50 | return longsPair.apply((x, y) -> new BigInteger[]{valueOf(x), valueOf(y)}); 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /friendly-id/src/test/java/com/devskiller/friendly_id/DataProvider.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Random; 5 | import java.util.UUID; 6 | 7 | import io.vavr.Tuple; 8 | import io.vavr.Tuple2; 9 | import io.vavr.test.Arbitrary; 10 | import io.vavr.test.Gen; 11 | import org.assertj.core.util.Strings; 12 | 13 | public class DataProvider { 14 | 15 | public static Arbitrary> LONG_PAIRS = ignored -> { 16 | Gen longs = Gen.choose(Long.MIN_VALUE, Long.MAX_VALUE); 17 | return random -> Tuple.of(longs.apply(random), longs.apply(random)); 18 | }; 19 | static Arbitrary UUIDS = ignored -> random -> UUID.randomUUID(); 20 | static Arbitrary POSITIVE_BIG_INTEGERS = ignored -> random -> 21 | new BigInteger(128, new Random()); 22 | static Arbitrary FRIENDLY_IDS = Arbitrary.string( 23 | Gen.frequency( 24 | Tuple.of(1, Gen.choose('A', 'Z')), 25 | Tuple.of(1, Gen.choose('a', 'z')), 26 | Tuple.of(1, Gen.choose('0', '9')))) 27 | .filter(code -> !Strings.isNullOrEmpty(code)) 28 | .filter(code -> Base62.decode(code, -1).bitLength() <= 128); 29 | 30 | } 31 | 32 | -------------------------------------------------------------------------------- /friendly-id/src/test/java/com/devskiller/friendly_id/FriendlyIdTest.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import io.vavr.test.Arbitrary; 4 | import org.junit.Test; 5 | 6 | import static com.devskiller.friendly_id.FriendlyId.toFriendlyId; 7 | import static com.devskiller.friendly_id.FriendlyId.toUuid; 8 | import static com.devskiller.friendly_id.IdUtil.areEqualIgnoringLeadingZeros; 9 | import static io.vavr.test.Property.def; 10 | import static org.assertj.core.util.Objects.areEqual; 11 | 12 | public class FriendlyIdTest { 13 | 14 | @Test 15 | public void shouldCreateValidIdsThatConformToUuidType4() { 16 | def("areEqual(FriendlyId.toUuid(FriendlyId.toFriendlyId(uuid))), uuid)") 17 | .forAll(Arbitrary.integer()) 18 | .suchThat(ignored -> toUuid(FriendlyId.createFriendlyId()).version() == 4) 19 | .check(-1, 100_000) 20 | .assertIsSatisfied(); 21 | } 22 | 23 | @Test 24 | public void encodingUuidShouldBeReversible() { 25 | def("areEqual(FriendlyId.toUuid(FriendlyId.toFriendlyId(uuid))), uuid)") 26 | .forAll(DataProvider.UUIDS) 27 | .suchThat(uuid -> areEqual(toUuid(toFriendlyId(uuid)), uuid)) 28 | .check(-1, 100_000) 29 | .assertIsSatisfied(); 30 | } 31 | 32 | @Test 33 | public void decodingIdShouldBeReversible() { 34 | def("areEqualIgnoringLeadingZeros(Url62.toFriendlyId(Url62.toUuid(id)), id)") 35 | .forAll(DataProvider.FRIENDLY_IDS) 36 | .suchThat(id -> areEqualIgnoringLeadingZeros(toFriendlyId(toUuid(id)), id)) 37 | .check(100, 100_000) 38 | .assertIsSatisfied(); 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /friendly-id/src/test/java/com/devskiller/friendly_id/IdUtil.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import static org.assertj.core.util.Objects.areEqual; 4 | 5 | public class IdUtil { 6 | 7 | static boolean areEqualIgnoringLeadingZeros(String code1, String code2) { 8 | return areEqual(removeLeadingZeros(code1), removeLeadingZeros(code2)); 9 | } 10 | 11 | private static String removeLeadingZeros(String string) { 12 | return string.replaceFirst("^0+(?!$)", ""); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /friendly-id/src/test/java/com/devskiller/friendly_id/Url62Test.java: -------------------------------------------------------------------------------- 1 | package com.devskiller.friendly_id; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 6 | 7 | public class Url62Test { 8 | 9 | @Test 10 | public void shouldExplodeWhenContainsIllegalCharacters() { 11 | assertThatThrownBy(() -> Url62.decode("Foo Bar")) 12 | .isInstanceOf(IllegalArgumentException.class) 13 | .hasMessageContaining("contains illegal characters"); 14 | } 15 | 16 | @Test 17 | public void shouldFaildOnEmptyString() { 18 | assertThatThrownBy(() -> Url62.decode("")) 19 | .isInstanceOf(IllegalArgumentException.class) 20 | .hasMessageContaining("must not be empty"); 21 | } 22 | 23 | @Test 24 | public void shouldFailsOnNullString() { 25 | assertThatThrownBy(() -> Url62.decode(null)) 26 | .isInstanceOf(NullPointerException.class) 27 | .hasMessageContaining("must not be null"); 28 | } 29 | 30 | @Test 31 | public void shouldFailsWhenStringContainsMoreThan128bitInformation() { 32 | assertThatThrownBy(() -> Url62.decode("7NLCAyd6sKR7kDHxgAWFPas")) 33 | .isInstanceOf(IllegalArgumentException.class) 34 | .hasMessageContaining("contains more than 128bit information"); 35 | } 36 | } -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.devskiller.friendly-id 7 | friendly-id-project 8 | pom 9 | 1.1.1-SNAPSHOT 10 | 11 | friendly id 12 | Library to convert uuid to url friendly IDs basing on base62 13 | https://github.com/Devskiller/friendly-id 14 | 15 | 16 | friendly-id 17 | friendly-id-jackson-datatype 18 | friendly-id-spring-boot 19 | friendly-id-spring-boot-starter 20 | friendly-id-samples 21 | 22 | 23 | 24 | UTF-8 25 | UTF-8 26 | 1.8 27 | 1.8 28 | 2.2.2.RELEASE 29 | 30 | 31 | 32 | 33 | Apache 2 34 | http://www.apache.org/licenses/LICENSE-2.0.txt 35 | repo 36 | A business-friendly OSS license 37 | 38 | 39 | 40 | 41 | 42 | Mariusz Smykula 43 | mariuszs@gmail.com 44 | Devskiller 45 | 46 | 47 | 48 | 49 | scm:git:https://github.com/Devskiller/friendly-id.git 50 | scm:git:git@github.com:Devskiller/friendly-id.git 51 | https://github.com/Devskiller/friendly-id 52 | HEAD 53 | 54 | 55 | 56 | 57 | oss 58 | Sonatype Nexus Snapshots 59 | http://oss.sonatype.org/content/repositories/snapshots 60 | 61 | 62 | oss 63 | Nexus Release Repository 64 | http://oss.sonatype.org/service/local/staging/deploy/maven2/ 65 | 66 | 67 | 68 | 69 | GitHub Issues 70 | https://github.com/Devskiller/friendly-id/issues 71 | 72 | 73 | 74 | Travis 75 | https://travis-ci.org/Devskiller/friendly-id 76 | 77 | 78 | 79 | 80 | 81 | org.springframework.boot 82 | spring-boot-dependencies 83 | ${spring-boot.version} 84 | pom 85 | import 86 | 87 | 88 | org.assertj 89 | assertj-core 90 | 3.12.0 91 | test 92 | 93 | 94 | io.vavr 95 | vavr-test 96 | 0.10.0 97 | test 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | org.apache.maven.plugins 107 | maven-compiler-plugin 108 | 3.8.1 109 | 110 | 111 | maven-surefire-plugin 112 | 2.22.2 113 | 114 | 115 | maven-install-plugin 116 | 2.5.2 117 | 118 | 119 | org.apache.maven.plugins 120 | maven-release-plugin 121 | 2.5.3 122 | 123 | true 124 | false 125 | true 126 | release 127 | @{project.version} 128 | 129 | 130 | 131 | org.codehaus.mojo 132 | flatten-maven-plugin 133 | 1.1.0 134 | 135 | ${project.build.directory} 136 | true 137 | oss 138 | 139 | 140 | 141 | flatten 142 | prepare-package 143 | 144 | flatten 145 | 146 | 147 | 148 | flatten-clean 149 | clean 150 | 151 | clean 152 | 153 | 154 | 155 | 156 | 157 | org.jacoco 158 | jacoco-maven-plugin 159 | 0.8.5 160 | 161 | 162 | org.eluder.coveralls 163 | coveralls-maven-plugin 164 | 4.3.0 165 | 166 | 167 | 168 | 169 | 170 | org.jacoco 171 | jacoco-maven-plugin 172 | 173 | 174 | 175 | prepare-agent 176 | 177 | 178 | 179 | report 180 | 181 | report 182 | 183 | 184 | 185 | 186 | 187 | org.codehaus.mojo 188 | flatten-maven-plugin 189 | 190 | 191 | 192 | 193 | 194 | 195 | release 196 | 197 | 198 | 199 | org.apache.maven.plugins 200 | maven-gpg-plugin 201 | 1.6 202 | 203 | 204 | sign-artifacts 205 | verify 206 | 207 | sign 208 | 209 | 210 | 211 | 212 | 213 | org.apache.maven.plugins 214 | maven-source-plugin 215 | 3.2.1 216 | 217 | 218 | attach-sources 219 | 220 | jar-no-fork 221 | 222 | 223 | 224 | 225 | 226 | org.apache.maven.plugins 227 | maven-javadoc-plugin 228 | 3.1.1 229 | 230 | 231 | attach-javadocs 232 | 233 | jar 234 | 235 | 236 | 237 | 238 | 239 | org.sonatype.plugins 240 | nexus-staging-maven-plugin 241 | 1.6.8 242 | true 243 | 244 | sonatype-nexus-staging 245 | https://oss.sonatype.org/ 246 | true 247 | 248 | 249 | 250 | com.google.code.maven-replacer-plugin 251 | replacer 252 | 1.5.3 253 | 254 | 255 | process-sources 256 | 257 | replace 258 | 259 | 260 | 261 | 262 | README.md 263 | 264 | 265 | (\d+\.\d+\.\d+(\-SNAPSHOT)?) 266 | ${project.version} 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | --------------------------------------------------------------------------------