├── .classpath ├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .project ├── .settings ├── org.eclipse.core.resources.prefs ├── org.eclipse.jdt.core.prefs └── org.eclipse.m2e.core.prefs ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── br │ │ └── com │ │ └── safeguard │ │ ├── SafeguardApplication.java │ │ ├── check │ │ └── SafeguardCheck.java │ │ ├── constraint │ │ ├── annotations │ │ │ └── Verify.java │ │ └── validators │ │ │ └── VerifyValidator.java │ │ ├── exceptions │ │ └── SafeguardException.java │ │ ├── interfaces │ │ ├── BaseParam.java │ │ ├── BasePattern.java │ │ └── Check.java │ │ ├── messages │ │ └── ErrorMessage.java │ │ ├── params │ │ └── Param.java │ │ ├── patterns │ │ └── Patterns.java │ │ ├── types │ │ └── ParametroTipo.java │ │ ├── validators │ │ └── PatternValidator.java │ │ └── verifies │ │ └── ParamVerify.java └── resources │ └── application.properties └── test └── java └── com └── gilmarcarlos └── developer └── safeguard ├── TesteDeObjetosAnotados.java └── TesteDeParametros.java /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gilmardeveloper/java-validator-safeguard/63d6a2aa8452400f56622511b4cf220894cd8889/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | safeguard 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding//src/test/java=UTF-8 5 | encoding/=UTF-8 6 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 3 | org.eclipse.jdt.core.compiler.compliance=1.8 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.8 6 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 7 | 8 | ## Our Standards 9 | 10 | Examples of behavior that contributes to creating a positive environment include: 11 | 12 | * Using welcoming and inclusive language 13 | * Being respectful of differing viewpoints and experiences 14 | * Gracefully accepting constructive criticism 15 | * Focusing on what is best for the community 16 | * Showing empathy towards other community members 17 | 18 | Examples of unacceptable behavior by participants include: 19 | 20 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 21 | * Trolling, insulting/derogatory comments, and personal or political attacks 22 | * Public or private harassment 23 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 24 | * Other conduct which could reasonably be considered inappropriate in a professional setting 25 | 26 | ## Our Responsibilities 27 | 28 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 29 | 30 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 31 | 32 | ## Scope 33 | 34 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 35 | 36 | ## Enforcement 37 | 38 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at gilmarcarlos.developer@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 39 | 40 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 41 | 42 | ## Attribution 43 | 44 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 45 | 46 | [homepage]: http://contributor-covenant.org 47 | [version]: http://contributor-covenant.org/version/1/4/ 48 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "{}" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright {yyyy} {name of copyright owner} 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Safeguard 2 | 3 | ### Biblioteca java para validação de CPF, CNPJ, Inscrição Estadual, Telefone, CEP, placas de veículos, telefone e outros campos de texto. Integrado com provedores de validação e persistência. 4 | 5 | ## Downloads 6 | 7 | * [Clone GitHub](https://github.com/gilmardeveloper/java-validator-safeguard.git) 8 | * [Download JAR](https://oss.sonatype.org/content/groups/public/com/github/gilmardeveloper/safeguard/0.0.1-RELEASE/safeguard-0.0.1-RELEASE.jar) 9 | 10 | ## Maven 11 | 12 | ### Faça o [Clone](https://github.com/gilmardeveloper/java-validator-safeguard.git) ou use o maven adicionando a dependência no seu arquivo pom.xml. 13 | ``` 14 | 15 | 16 | com.github.gilmardeveloper 17 | safeguard 18 | 0.0.1-RELEASE 19 | 20 | 21 | 22 | ``` 23 | ## Como usar 24 | 25 | 1. Validando um elemento 26 | 27 | ```java 28 | String texto = "digite apenas letras ou números"; 29 | 30 | Check check = new SafeguardCheck(); 31 | 32 | boolean hasError = check 33 | .elementOf(texto,ParametroTipo.DEFAULT_SEM_CARACTERES_ESPECIAIS) 34 | .validate() 35 | .hasError(); 36 | ``` 37 | 2. Validando mais de um elemento 38 | ```java 39 | String texto = "digite apenas letras ou números"; 40 | String numeros = "1234567890"; 41 | String cpf= "96205663279"; 42 | 43 | Check check = new SafeguardCheck(); 44 | 45 | boolean hasError = check 46 | .elementOf(texto,ParametroTipo.DEFAULT_SEM_CARACTERES_ESPECIAIS) 47 | .elementOf(numeros,ParametroTipo.NUMERO) 48 | .elementOf(cpf,ParametroTipo.CPF) 49 | .validate() 50 | .hasError(); 51 | ``` 52 | 3. Validando o mesmo elemento 53 | 54 | **Obs.: Apenas opções do tipo DEFAULT devem ser usadas em um mesmo elemento, sendo distintas entre si.** 55 | 56 | ```java 57 | String texto = "Você pode digita apenas letras ou números"; 58 | 59 | Check check = new SafeguardCheck(); 60 | 61 | boolean hasError = check 62 | .elementOf(texto,ParametroTipo.DEFAULT_SEM_CARACTERES_ESPECIAIS) 63 | .elementOf(texto,ParametroTipo.DEFAULT_SEM_NUMEROS) 64 | .validate() 65 | .hasError(); 66 | ``` 67 | 4. Validando atributos de classe 68 | 69 | 4.1. Anotando atributos com @Verify 70 | 71 | ```java 72 | public class Empresa { 73 | 74 | @Verify(ParametroTipo.TEXTO_SEM_CARACTERES_ESPECIAIS) 75 | private String nome; 76 | @Verify(ParametroTipo.CNPJ) 77 | private String cnpj; 78 | @Verify(ParametroTipo.IE_SAO_PAULO_SP) 79 | private String ie; 80 | 81 | } 82 | ``` 83 | 4.2. Validando a instância da classe de forma manual 84 | 85 | ```java 86 | Empresa empresa = new Empresa(nome, cnpj, ie); 87 | 88 | Check check = new SafeguardCheck(); 89 | 90 | boolean hasError = check.elementOf(empresa).Validate().hasError(); 91 | ``` 92 | 93 | 4.3. Usando um provedor de validação 94 | 95 | 4.3.1 Usando a validação do Spring MVC 96 | 97 | public void validar(@Valid Empresa empresa, BindingResult result, HttpServletResponse response) { 98 | 99 | if(!result.hasErrors()) { 100 | //do anything 101 | response.setStatus(200); 102 | }else { 103 | 104 | response.setStatus(400); 105 | } 106 | 107 | } 108 | 109 | 4.3.2 Usando a validação do JPA 110 | 111 | EntityManager manager = entityManagerFactory.createEntityManager(); 112 | 113 | manager.persist(empresa); 114 | 115 | manager.close(); 116 | 117 | ## Métodos da interface Check 118 | 119 | - elementOf(Object object) 120 | - Método que recebe um objeto que tenha atributos da classe anotados com (@Verify) para ser adicionado em um (List) de elementos 121 | 122 | - elementOf(String value, BaseParam tipo) 123 | - Método que recebe um (String) e um (BaseParam) para ser adicionado em um (Map) de elementos 124 | 125 | - elementOf(String value, ParametroTipo tipo) 126 | - Método que recebe um (String) e um (BaseParam) para ser adicionado em um (Map) de elementos 127 | 128 | - getInvalidElements() 129 | - Método que retorna uma lista de elementos inválidos 130 | 131 | - getValidElements() 132 | - Método que retorna uma lista de elementos válidos 133 | 134 | - hasError() 135 | - Método que retorna true caso os elementos verificados sejam inválidos, false caso contrário 136 | 137 | - validate() 138 | - O método que faz a validação dos valores passados anteriormente no método elementOf(), e retorna a própria classe 139 | 140 | ## Lista de Validações 141 | 142 | /**Cadeia de caracteres que representa um documento de CPF*/ 143 | CPF 144 | 145 | /**Cadeia de caracteres que representa um documento de CPF formatado*/ 146 | CPF_FORMATADO 147 | 148 | /**Cadeia de caracteres que representa um documento de Titulo de Eleitor*/ 149 | TITULO_DE_ELEITOR 150 | 151 | /**Cadeia de caracteres que representa um documento de Titulo de Eleitor formatado*/ 152 | TITULO_DE_ELEITOR_FORMATADO 153 | 154 | /**Cadeia de caracteres que representa um documento de Número de Indentificação do Trabalhador*/ 155 | NIT 156 | 157 | /**Cadeia de caracteres que representa um documento de Número de Indentificação do Trabalhador formatado*/ 158 | NIT_FORMATADO 159 | 160 | /**Cadeia de caracteres que representa um CNPJ*/ 161 | CNPJ 162 | 163 | /**Cadeia de caracteres que representa um CNPJ formatado*/ 164 | CNPJ_FORMATADO 165 | 166 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 167 | IE_ACRE_AC 168 | 169 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 170 | IE_ACRE_AC_FORMATADO 171 | 172 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 173 | IE_ALAGOAS_AL 174 | 175 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 176 | IE_ALAGOAS_AL_FORMATADO 177 | 178 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 179 | IE_AMAPA_AP 180 | 181 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 182 | IE_AMAPA_AP_FORMATADO 183 | 184 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 185 | IE_AMAZONAS_AM 186 | 187 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 188 | IE_AMAZONAS_AM_FORMATADO 189 | 190 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 191 | IE_BAHIA_BA 192 | 193 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 194 | IE_BAHIA_BA_FORMATADO 195 | 196 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 197 | IE_CEARA_CE 198 | 199 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 200 | IE_CEARA_CE_FORMATADO 201 | 202 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 203 | IE_DISTRITO_FEDERAL_DF 204 | 205 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 206 | IE_DISTRITO_FEDERAL_DF_FORMATADO 207 | 208 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 209 | IE_ESPIRITO_SANTO_ES 210 | 211 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 212 | IE_ESPIRITO_SANTO_ES_FORMATADO 213 | 214 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 215 | IE_GOIAIS_GO 216 | 217 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 218 | IE_GOIAIS_GO_FORMATADO 219 | 220 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 221 | IE_MARANHAO_MA 222 | 223 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 224 | IE_MARANHAO_MA_FORMATADO 225 | 226 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 227 | IE_MATO_GROSSO_MT 228 | 229 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 230 | IE_MATO_GROSSO_MT_FORMATADO 231 | 232 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 233 | IE_MATO_GROSSO_DO_SUL_MS 234 | 235 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 236 | IE_MATO_GROSSO_DO_SUL_MS_FORMATADO 237 | 238 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 239 | IE_MINAS_GERAIS_MG 240 | 241 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 242 | IE_MINAS_GERAIS_MG_FORMATADO 243 | 244 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 245 | IE_PARA_PA 246 | 247 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 248 | IE_PARA_PA_FORMATADO 249 | 250 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 251 | IE_PARAIBA_PB 252 | 253 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 254 | IE_PARAIBA_PB_FORMATADO 255 | 256 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 257 | IE_PARARA_PR 258 | 259 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 260 | IE_PARARA_PR_FORMATADO 261 | 262 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 263 | IE_PERNAMBUCO_PE 264 | 265 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 266 | IE_PERNAMBUCO_PE_FORMATADO 267 | 268 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 269 | IE_PIAUI_PI 270 | 271 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 272 | IE_PIAUI_PI_FORMATADO 273 | 274 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 275 | IE_RIO_DE_JANEIRO_RJ 276 | 277 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 278 | IE_RIO_DE_JANEIRO_RJ_FORMATADO 279 | 280 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 281 | IE_RIO_GRANDE_DO_NORTE_RN 282 | 283 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 284 | IE_RIO_GRANDE_DO_NORTE_RN_FORMATADO 285 | 286 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 287 | IE_RIO_GRANDE_DO_SUL_RS 288 | 289 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 290 | IE_RIO_GRANDE_DO_SUL_RS_FORMATADO 291 | 292 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 293 | IE_RONDONIA_RO 294 | 295 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 296 | IE_RONDONIA_RO_FORMATADO 297 | 298 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 299 | IE_RORAIMA_RR 300 | 301 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 302 | IE_RORAIMA_RR_FORMATADO 303 | 304 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 305 | IE_SANTA_CATARINA_SC 306 | 307 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 308 | IE_SANTA_CATARINA_SC_FORMATADO 309 | 310 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 311 | IE_SAO_PAULO_SP 312 | 313 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 314 | IE_SAO_PAULO_SP_FORMATADO 315 | 316 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 317 | IE_SERGIPE_SE 318 | 319 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 320 | IE_SERGIPE_SE_FORMATADO 321 | 322 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 323 | IE_TOCANTINS_TO 324 | 325 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 326 | IE_TOCANTINS_TO_FORMATADO 327 | 328 | /** 329 | * Cadeia de caracteres de texto padrão, contendo caracters da tabela unicode 330 | * iniciando em \u0020 e terminando em \u00FC 331 | */ 332 | DEFAULT 333 | 334 | /**Cadeia de caracteres de texto padrão sem o sinal de maior */ 335 | DEFAULT_SEM_SIMBOLO_DE_MAIOR 336 | 337 | /**Cadeia de caracteres de texto padrão sem o sinal de menor */ 338 | DEFAULT_SEM_SIMBOLO_DE_MENOR 339 | 340 | /**Cadeia de caracteres de texto padrão sem o sinal de menor e maior*/ 341 | DEFAULT_SEM_SIMBOLO_DE_MENOR_E_MAIOR 342 | 343 | /**Cadeia de caracteres de texto padrão sem o sinal de chaves */ 344 | DEFAULT_SEM_SIMBOLO_DE_CHAVES 345 | 346 | /**Cadeia de caracteres de texto padrão sem o sinal de colchetes */ 347 | DEFAULT_SEM_SIMBOLO_DE_COLCHETES 348 | 349 | /**Cadeia de caracteres de texto padrão sem o sinal de parneteses */ 350 | DEFAULT_SEM_SIMBOLO_DE_PARENTESES 351 | 352 | /**Cadeia de caracteres de texto padrão sem o sinal de asterisco */ 353 | DEFAULT_SEM_SIMBOLO_DE_ASTERISCO 354 | 355 | /**Cadeia de caracteres de texto padrão sem o sinal de arroba */ 356 | DEFAULT_SEM_SIMBOLO_DE_ARROBA 357 | 358 | /**Cadeia de caracteres de texto padrão sem o sinal de hashtag */ 359 | DEFAULT_SEM_SIMBOLO_DE_HASHTAG 360 | 361 | /**Cadeia de caracteres de texto padrão sem o sinal de sifrão */ 362 | DEFAULT_SEM_SIMBOLO_DE_SIFRAO 363 | 364 | /**Cadeia de caracteres de texto padrão sem o sinal de porcentagem */ 365 | DEFAULT_SEM_SIMBOLO_DE_PORCENTAGEM 366 | 367 | /**Cadeia de caracteres de texto padrão sem o sinal de trema */ 368 | DEFAULT_SEM_SIMBOLO_DE_TREMA 369 | 370 | /**Cadeia de caracteres de texto padrão sem o sinal de e comercial */ 371 | DEFAULT_SEM_SIMBOLO_DE_E_COMERCIAL 372 | 373 | /**Cadeia de caracteres de texto padrão sem o sinal de underline */ 374 | DEFAULT_SEM_SIMBOLO_DE_UNDERLINE 375 | 376 | /**Cadeia de caracteres de texto padrão sem o sinal de hífem */ 377 | DEFAULT_SEM_SIMBOLO_DE_HIFEM 378 | 379 | /**Cadeia de caracteres de texto padrão sem o sinal de mais */ 380 | DEFAULT_SEM_SIMBOLO_DE_MAIS 381 | 382 | /**Cadeia de caracteres de texto padrão sem o sinal de aspas simples */ 383 | DEFAULT_SEM_SIMBOLO_DE_ASPAS_SIMPLES 384 | 385 | /**Cadeia de caracteres de texto padrão sem o sinal de aspas duplas */ 386 | DEFAULT_SEM_SIMBOLO_DE_ASPAS_DUPLA 387 | 388 | /**Cadeia de caracteres de texto padrão sem o sinal de ponto */ 389 | DEFAULT_SEM_SIMBOLO_DE_PONTO 390 | 391 | /**Cadeia de caracteres de texto padrão sem o sinal de virgula */ 392 | DEFAULT_SEM_SIMBOLO_DE_VIRGULA 393 | 394 | /**Cadeia de caracteres de texto padrão sem o sinal de dois pontos */ 395 | DEFAULT_SEM_SIMBOLO_DE_DOIS_PONTOS 396 | 397 | /**Cadeia de caracteres de texto padrão sem o sinal de ponto e virgula */ 398 | DEFAULT_SEM_SIMBOLO_DE_PONTO_E_VIRGULA 399 | 400 | /**Cadeia de caracteres de texto padrão sem o sinal de exclamação */ 401 | DEFAULT_SEM_SIMBOLO_DE_PONTO_DE_EXCLAMACAO 402 | 403 | /**Cadeia de caracteres de texto padrão sem o sinal de interrogação */ 404 | DEFAULT_SEM_SIMBOLO_DE_PONTO_DE_INTERROGACAO 405 | 406 | /**Cadeia de caracteres de texto padrão sem pontuação */ 407 | DEFAULT_SEM_PONTUACAO 408 | 409 | /**Cadeia de caracteres de texto padrão sem números */ 410 | DEFAULT_SEM_NUMEROS 411 | 412 | /**Cadeia de caracteres de texto padrão sem sinais matemáticos */ 413 | DEFAULT_SEM_SINAIS_MATEMATICOS 414 | 415 | /**Cadeia de caracteres de texto padrão sem caracteres especiais */ 416 | DEFAULT_SEM_CARACTERES_ESPECIAIS 417 | 418 | /**Cadeia de caracteres apenas com texto, sem númeors ou caracteres especiais*/ 419 | TEXTO_SEM_CARACTERES_ESPECIAIS 420 | 421 | /**Cadeia de caracteres apenas com texto e hífem, sem númeors ou caracteres especiais*/ 422 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_HIFEM 423 | 424 | /**Cadeia de caracteres apenas com texto e underline, sem númeors ou caracteres especiais*/ 425 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_UNDERLINE 426 | 427 | /**Cadeia de caracteres apenas com texto e virgula, sem númeors ou caracteres especiais*/ 428 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_VIRGULA 429 | 430 | /**Cadeia de caracteres apenas com texto e pontuação, sem númeors ou caracteres especiais*/ 431 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO 432 | 433 | /**Cadeia de caracteres apenas com texto, pontuação, hífem e underline, sem númeors ou caracteres especiais*/ 434 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE 435 | 436 | /**Cadeia de caracteres com texto e número, sem caracteres especiais*/ 437 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS 438 | 439 | /**Cadeia de caracteres com texto, números e hífem, sem caracteres especiais*/ 440 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_HIFEM 441 | 442 | /**Cadeia de caracteres com texto, números e underline, sem caracteres especiais*/ 443 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_UNDERLINE 444 | 445 | /**Cadeia de caracteres com texto, números e virgula, sem caracteres especiais*/ 446 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_VIRGULA 447 | 448 | /**Cadeia de caracteres com texto, números e pontuação, sem caracteres especiais*/ 449 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO 450 | 451 | /**Cadeia de caracteres com texto, números, pontuação, hífem e underline, sem caracteres especiais*/ 452 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE 453 | 454 | /**Cadeia de caracteres com texto, números, virgula, hífem e underline, sem caracteres especiais*/ 455 | TEXTO_NUMERO_VIRGULA_HIFEM_UNDERLINE_SEM_PONTUACAO 456 | 457 | /**Cadeia de caracteres contendo apenas números*/ 458 | NUMERO 459 | 460 | /**Cadeia de caracteres que representa um email*/ 461 | EMAIL 462 | 463 | /**Cadeia de caracteres que representa um CEP*/ 464 | CEP 465 | 466 | /**Cadeia de caracteres que representa um CEP formatado*/ 467 | CEP_FORMATADO 468 | /**Cadeia de caracteres que representa uma placa de veículo*/ 469 | PLACA_DE_VEICULO_BRASIL 470 | 471 | /**Cadeia de caracteres que representa uma placa de veículo formatado*/ 472 | PLACA_DE_VEICULO_FORMATADO_BRASIL 473 | 474 | /** 475 | * Cadeia de caracteres que representa um telefone fixo ou móvel com ou sem número da operadora, DD + NÚMERO 476 | * 477 | * Exemplos: 478 | * Com número da operadora 01211988774455, obs.: O dígito 9 pode ser omitido para telefones fixos 1133445566 479 | * Sem o número da operadora 11988774455 480 | */ 481 | TELEFONE 482 | 483 | /** 484 | * Cadeia de caracteres que representa um telefone fixo ou móvel com ou sem número da operadora, DD + NÚMERO formatado 485 | * 486 | * Exemplos: 487 | * Com número da operadora 012(11)98877-4455, obs.: O dígito 9 pode ser omitido para telefones fixos (11)3344-5566 488 | * Sem o número da operadora (11)98877-4455 489 | */ 490 | TELEFONE_FORMATADO_BRASIL 491 | 492 | /** 493 | * Cadeia de caracteres que representa um telefone fixo ou móvel com o número do país, DD + NÚMERO formatado 494 | * 495 | * Exemplos: 496 | * Formato internacional: +55 11 98877-4455, obs.: O dígito 9 pode ser omitido para telefones fixos +55 11 3344-5566 497 | */ 498 | TELEFONE_FORMATADO_INTERNACIONAL 499 | 500 | 501 | © 2017 Gilmar Carlos All rights reserved. 502 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | # 2 | #!/bin/sh 3 | # ---------------------------------------------------------------------------- 4 | # Licensed to the Apache Software Foundation (ASF) under one 5 | # or more contributor license agreements. See the NOTICE file 6 | # distributed with this work for additional information 7 | # regarding copyright ownership. The ASF licenses this file 8 | # to you under the Apache License, Version 2.0 (the 9 | # "License"); you may not use this file except in compliance 10 | # with the License. You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, 15 | # software distributed under the License is distributed on an 16 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | # KIND, either express or implied. See the License for the 18 | # specific language governing permissions and limitations 19 | # under the License. 20 | # ---------------------------------------------------------------------------- 21 | 22 | # ---------------------------------------------------------------------------- 23 | # Maven2 Start Up Batch script 24 | # 25 | # Required ENV vars: 26 | # ------------------ 27 | # JAVA_HOME - location of a JDK home dir 28 | # 29 | # Optional ENV vars 30 | # ----------------- 31 | # M2_HOME - location of maven2's installed home dir 32 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 33 | # e.g. to debug Maven itself, use 34 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 35 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 36 | # ---------------------------------------------------------------------------- 37 | 38 | if [ -z "$MAVEN_SKIP_RC" ] ; then 39 | 40 | if [ -f /etc/mavenrc ] ; then 41 | . /etc/mavenrc 42 | fi 43 | 44 | if [ -f "$HOME/.mavenrc" ] ; then 45 | . "$HOME/.mavenrc" 46 | fi 47 | 48 | fi 49 | 50 | # OS specific support. $var _must_ be set to either true or false. 51 | cygwin=false; 52 | darwin=false; 53 | mingw=false 54 | case "`uname`" in 55 | CYGWIN*) cygwin=true ;; 56 | MINGW*) mingw=true;; 57 | Darwin*) darwin=true 58 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 59 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 60 | if [ -z "$JAVA_HOME" ]; then 61 | if [ -x "/usr/libexec/java_home" ]; then 62 | export JAVA_HOME="`/usr/libexec/java_home`" 63 | else 64 | export JAVA_HOME="/Library/Java/Home" 65 | fi 66 | fi 67 | ;; 68 | esac 69 | 70 | if [ -z "$JAVA_HOME" ] ; then 71 | if [ -r /etc/gentoo-release ] ; then 72 | JAVA_HOME=`java-config --jre-home` 73 | fi 74 | fi 75 | 76 | if [ -z "$M2_HOME" ] ; then 77 | ## resolve links - $0 may be a link to maven's home 78 | PRG="$0" 79 | 80 | # need this for relative symlinks 81 | while [ -h "$PRG" ] ; do 82 | ls=`ls -ld "$PRG"` 83 | link=`expr "$ls" : '.*-> \(.*\)$'` 84 | if expr "$link" : '/.*' > /dev/null; then 85 | PRG="$link" 86 | else 87 | PRG="`dirname "$PRG"`/$link" 88 | fi 89 | done 90 | 91 | saveddir=`pwd` 92 | 93 | M2_HOME=`dirname "$PRG"`/.. 94 | 95 | # make it fully qualified 96 | M2_HOME=`cd "$M2_HOME" && pwd` 97 | 98 | cd "$saveddir" 99 | # echo Using m2 at $M2_HOME 100 | fi 101 | 102 | # For Cygwin, ensure paths are in UNIX format before anything is touched 103 | if $cygwin ; then 104 | [ -n "$M2_HOME" ] && 105 | M2_HOME=`cygpath --unix "$M2_HOME"` 106 | [ -n "$JAVA_HOME" ] && 107 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 108 | [ -n "$CLASSPATH" ] && 109 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 110 | fi 111 | 112 | # For Migwn, ensure paths are in UNIX format before anything is touched 113 | if $mingw ; then 114 | [ -n "$M2_HOME" ] && 115 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 116 | [ -n "$JAVA_HOME" ] && 117 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 118 | # TODO classpath? 119 | fi 120 | 121 | if [ -z "$JAVA_HOME" ]; then 122 | javaExecutable="`which javac`" 123 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 124 | # readlink(1) is not available as standard on Solaris 10. 125 | readLink=`which readlink` 126 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 127 | if $darwin ; then 128 | javaHome="`dirname \"$javaExecutable\"`" 129 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 130 | else 131 | javaExecutable="`readlink -f \"$javaExecutable\"`" 132 | fi 133 | javaHome="`dirname \"$javaExecutable\"`" 134 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 135 | JAVA_HOME="$javaHome" 136 | export JAVA_HOME 137 | fi 138 | fi 139 | fi 140 | 141 | if [ -z "$JAVACMD" ] ; then 142 | if [ -n "$JAVA_HOME" ] ; then 143 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 144 | # IBM's JDK on AIX uses strange locations for the executables 145 | JAVACMD="$JAVA_HOME/jre/sh/java" 146 | else 147 | JAVACMD="$JAVA_HOME/bin/java" 148 | fi 149 | else 150 | JAVACMD="`which java`" 151 | fi 152 | fi 153 | 154 | if [ ! -x "$JAVACMD" ] ; then 155 | echo "Error: JAVA_HOME is not defined correctly." >&2 156 | echo " We cannot execute $JAVACMD" >&2 157 | exit 1 158 | fi 159 | 160 | if [ -z "$JAVA_HOME" ] ; then 161 | echo "Warning: JAVA_HOME environment variable is not set." 162 | fi 163 | 164 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 165 | 166 | # traverses directory structure from process work directory to filesystem root 167 | # first directory with .mvn subdirectory is considered project base directory 168 | find_maven_basedir() { 169 | 170 | if [ -z "$1" ] 171 | then 172 | echo "Path not specified to find_maven_basedir" 173 | return 1 174 | fi 175 | 176 | basedir="$1" 177 | wdir="$1" 178 | while [ "$wdir" != '/' ] ; do 179 | if [ -d "$wdir"/.mvn ] ; then 180 | basedir=$wdir 181 | break 182 | fi 183 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 184 | if [ -d "${wdir}" ]; then 185 | wdir=`cd "$wdir/.."; pwd` 186 | fi 187 | # end of workaround 188 | done 189 | echo "${basedir}" 190 | } 191 | 192 | # concatenates all lines of a file 193 | concat_lines() { 194 | if [ -f "$1" ]; then 195 | echo "$(tr -s '\n' ' ' < "$1")" 196 | fi 197 | } 198 | 199 | BASE_DIR=`find_maven_basedir "$(pwd)"` 200 | if [ -z "$BASE_DIR" ]; then 201 | exit 1; 202 | fi 203 | 204 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 205 | echo $MAVEN_PROJECTBASEDIR 206 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 207 | 208 | # For Cygwin, switch paths to Windows format before running java 209 | if $cygwin; then 210 | [ -n "$M2_HOME" ] && 211 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 212 | [ -n "$JAVA_HOME" ] && 213 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 214 | [ -n "$CLASSPATH" ] && 215 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 216 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 217 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 218 | fi 219 | 220 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 221 | 222 | exec "$JAVACMD" \ 223 | $MAVEN_OPTS \ 224 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 225 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 226 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 227 | -------------------------------------------------------------------------------- /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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.github.gilmardeveloper 7 | safeguard 8 | 0.0.1-RELEASE 9 | jar 10 | 11 | safeguard 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 1.5.4.RELEASE 17 | 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | br.com.caelum.stella 35 | caelum-stella-core 36 | 2.1.2 37 | 38 | 39 | 40 | javax.validation 41 | validation-api 42 | 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-test 47 | test 48 | 49 | 50 | 51 | org.hibernate 52 | hibernate-validator 53 | 54 | 55 | 56 | javax.el 57 | javax.el-api 58 | 2.2.4 59 | 60 | 61 | 62 | org.glassfish.web 63 | javax.el 64 | 2.2.4 65 | 66 | 67 | 68 | 69 | 70 | 71 | ossrh 72 | https://oss.sonatype.org/content/repositories/snapshots 73 | 74 | 75 | ossrh 76 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | org.springframework.boot 86 | spring-boot-maven-plugin 87 | 88 | 89 | 90 | 91 | org.hibernate 92 | hibernate-validator 93 | 94 | 95 | org.glassfish.web 96 | javax.el 97 | 98 | 99 | javax.el 100 | javax.el-api 101 | 102 | 103 | org.springframework.boot 104 | spring-boot-starter-test 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | repackage 113 | 114 | 115 | exec 116 | 117 | 118 | 119 | 120 | 121 | 122 | org.sonatype.plugins 123 | nexus-staging-maven-plugin 124 | 1.6.7 125 | true 126 | 127 | ossrh 128 | https://oss.sonatype.org/ 129 | true 130 | 131 | 132 | 133 | 134 | org.apache.maven.plugins 135 | maven-source-plugin 136 | 2.2.1 137 | 138 | 139 | attach-sources 140 | 141 | jar-no-fork 142 | 143 | 144 | 145 | 146 | 147 | org.apache.maven.plugins 148 | maven-javadoc-plugin 149 | 2.9.1 150 | 151 | 152 | attach-javadocs 153 | 154 | jar 155 | 156 | 157 | 158 | 159 | 160 | 161 | org.apache.maven.plugins 162 | maven-gpg-plugin 163 | 1.5 164 | 165 | 166 | sign-artifacts 167 | verify 168 | 169 | sign 170 | 171 | 172 | 173 | 174 | 175 | 176 | org.sonatype.plugins 177 | nexus-staging-maven-plugin 178 | 1.6.7 179 | true 180 | 181 | ossrh 182 | https://oss.sonatype.org/ 183 | true 184 | 185 | 186 | 187 | 188 | 189 | 190 | Biblioteca java para validação de CPF, CNPJ, Inscrição Estadual, Telefone, CEP, placas de veículos, telefone e outros campos de texto. Integrado com provedores de validação e persistência. 191 | https://github.com/gilmardeveloper/java-validator-safeguard 192 | 193 | 194 | Gilmar Carlos 195 | https://github.com/gilmardeveloper 196 | 197 | 198 | 199 | scm:git:git://github.com/gilmardeveloper/java-validator-safeguard.git 200 | scm:git:ssh://github.com:gilmardeveloper/java-validator-safeguard.git 201 | https://github.com/gilmardeveloper/java-validator-safeguard 202 | 203 | 204 | 205 | 206 | The Apache License, Version 2.0 207 | http://www.apache.org/licenses/LICENSE-2.0.txt 208 | 209 | 210 | 211 | 212 | 213 | Gilmar Carlos 214 | gilmarcarlos.developer@gmail.com 215 | GilmarDeveloper 216 | https://github.com/gilmardeveloper 217 | 218 | 219 | 220 | 221 | 222 | 223 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/SafeguardApplication.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SafeguardApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SafeguardApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/check/SafeguardCheck.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.check; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import br.com.safeguard.exceptions.SafeguardException; 9 | import br.com.safeguard.interfaces.BaseParam; 10 | import br.com.safeguard.interfaces.Check; 11 | import br.com.safeguard.params.Param; 12 | import br.com.safeguard.types.ParametroTipo; 13 | import br.com.safeguard.verifies.ParamVerify; 14 | 15 | /** 16 | * Classe com os métodos funcionais para validação de cadeia de caracteres ou objetos com atributos 17 | * anotado com (@Verify), que implementa a interface (Check) 18 | * 19 | * @author Gilmar Carlos 20 | * 21 | */ 22 | public class SafeguardCheck implements Check { 23 | 24 | private Map stringElements; 25 | private List objectElements; 26 | private ParamVerify verify; 27 | private Integer key; 28 | 29 | /** 30 | * Construtor padrão 31 | */ 32 | public SafeguardCheck() { 33 | stringElements = new HashMap(); 34 | verify = new ParamVerify(); 35 | objectElements = new ArrayList<>(); 36 | key = 0; 37 | } 38 | 39 | /** 40 | * Método que recebe um (String) e um (ParametroTipo) para ser adicionado em um (Map) de elementos 41 | * 42 | * @param value Valor a ser validado 43 | * @param tipo Tipo usado na validação 44 | * @return this retorna a própria classe 45 | */ 46 | public SafeguardCheck elementOf(String value, ParametroTipo tipo) { 47 | stringElements.put(key++, new Param(tipo, value)); 48 | return this; 49 | } 50 | 51 | /** 52 | * Método que recebe um (String) e um (BaseParam) para ser adicionado em um (Map) de elementos 53 | * 54 | * @param value Valor a ser validado 55 | * @param tipo Tipo usado na validação 56 | * @return this retorna a própria classe 57 | */ 58 | public SafeguardCheck elementOf(String value, BaseParam tipo) { 59 | stringElements.put(key++, new Param(tipo, value)); 60 | return this; 61 | } 62 | 63 | /** 64 | * Método que recebe um objeto que tenha atributos da classe anotados com (@Verify) para ser adicionado 65 | * em um (List) de elementos 66 | * 67 | * @param object Instancia da classe anotada com (@Verify) 68 | * @return this retorna a própria classe 69 | */ 70 | public SafeguardCheck elementOf(Object object) { 71 | objectElements.add(object); 72 | return this; 73 | } 74 | 75 | /** 76 | * O método que faz a validação dos valores passados anteriormente no método {@code elementOf()}, 77 | * e retorna a própria classe 78 | * 79 | * 80 | * @return this retorna a própria classe 81 | */ 82 | public SafeguardCheck validate() { 83 | 84 | try { 85 | if (!stringElements.isEmpty()) { 86 | verify.validate(stringElements); 87 | } 88 | 89 | if (!objectElements.isEmpty()) { 90 | verify.validate(objectElements); 91 | } 92 | } catch (SafeguardException e) { 93 | e.printStackTrace(); 94 | } 95 | 96 | return this; 97 | } 98 | 99 | /** 100 | * Método que retorna true caso os elementos verificados sejam inválidos, 101 | * false caso contrário 102 | * 103 | * @return Boolean retorna true se houver erros 104 | */ 105 | public Boolean hasError() { 106 | return verify.hasError(); 107 | } 108 | 109 | /** 110 | *Método que retorna uma lista de elementos inválidos 111 | * 112 | * @return List retorna uma lista de elementos inválidos 113 | */ 114 | public List getInvalidElements() { 115 | return verify.getInvalidElements(); 116 | } 117 | 118 | 119 | /** 120 | *Método que retorna uma lista de elementos válidos 121 | * 122 | * @return List retorna uma lista de elementos válidos 123 | */ 124 | public List getValidElements() { 125 | return verify.getValidElements(); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/constraint/annotations/Verify.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.constraint.annotations; 2 | 3 | import static java.lang.annotation.ElementType.FIELD; 4 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 5 | 6 | import java.lang.annotation.Documented; 7 | import java.lang.annotation.ElementType; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.RetentionPolicy; 10 | import java.lang.annotation.Target; 11 | 12 | import javax.validation.Constraint; 13 | import javax.validation.Payload; 14 | 15 | import br.com.safeguard.constraint.validators.VerifyValidator; 16 | import br.com.safeguard.types.ParametroTipo; 17 | 18 | /** 19 | * Anotação para atributos de classes que devem ser validados seguindo o tipo específico 20 | * de validador registrado em um (Enum) que implemente a interface (BaseParam) 21 | * 22 | *

Pode ser usada junto a um provedor de validação compativel com (javax.validation.ConstraintValidator)

23 | * 24 | * 25 | * 26 | * Valor default: {@code ParametroTipo.DEFAULT} 27 | * Exemplo de uso: 28 | * 29 | * 30 | * {@code @verify}
31 | * {@code private String nome;}
32 | * {@code @verify(ParametroTipo.CPF_FORMATADO)}
33 | * {@code private String cpf;}
34 | * 35 | * 36 | * @author Gilmar Carlos 37 | * 38 | */ 39 | @Constraint(validatedBy = VerifyValidator.class) 40 | @Documented 41 | @Retention(RetentionPolicy.RUNTIME) 42 | @Target({ElementType.FIELD}) 43 | public @interface Verify { 44 | 45 | String message() default "O campo verificado contém caracteres inválidos"; 46 | Class[] groups() default {}; 47 | Class[] payload() default {}; 48 | 49 | ParametroTipo[] value() default ParametroTipo.DEFAULT; 50 | 51 | @Target({FIELD}) 52 | @Retention(RUNTIME) 53 | @Documented 54 | @interface List { 55 | 56 | Verify[] value(); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/constraint/validators/VerifyValidator.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.constraint.validators; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import javax.validation.ConstraintValidator; 7 | import javax.validation.ConstraintValidatorContext; 8 | 9 | import br.com.safeguard.check.SafeguardCheck; 10 | import br.com.safeguard.constraint.annotations.Verify; 11 | import br.com.safeguard.interfaces.Check; 12 | import br.com.safeguard.types.ParametroTipo; 13 | 14 | /** 15 | * 16 | * Classe usada para validar objetos anotados com (@Verify), é chamada por um 17 | * provedor de validação compatível com (javax.validation.ConstraintValidator) 18 | * 19 | * @author Gilmar Carlos 20 | * 21 | */ 22 | public class VerifyValidator implements ConstraintValidator{ 23 | 24 | private Check check; 25 | private List parametros; 26 | 27 | @Override 28 | public void initialize(Verify verify) { 29 | parametros = Arrays.asList(verify.value()); 30 | } 31 | 32 | @Override 33 | public boolean isValid(String value, ConstraintValidatorContext context) { 34 | if(value == null) { 35 | return false; 36 | } 37 | 38 | check = new SafeguardCheck(); 39 | parametros.forEach((parametro) -> check.elementOf(value, parametro).validate()); 40 | 41 | if(check.hasError()) { 42 | context.disableDefaultConstraintViolation(); 43 | context.buildConstraintViolationWithTemplate("(" + value + ") contém caracteres inválidos ") 44 | .addConstraintViolation(); 45 | } 46 | 47 | return !check.hasError(); 48 | } 49 | 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/exceptions/SafeguardException.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.exceptions; 2 | 3 | /** 4 | * Classe que especifica uma exceção do tipo checked para evitar erros de compilação 5 | * 6 | * @author Gilmar Carlos 7 | * 8 | */ 9 | public class SafeguardException extends Exception { 10 | 11 | private static final long serialVersionUID = 1L; 12 | 13 | /** 14 | * Contrutor padrão que lança uma exceção genérica 15 | */ 16 | public SafeguardException() { 17 | super(); 18 | } 19 | 20 | /** 21 | * 22 | * Construtor que recebe uma mensagem (String) com detalhes sobre a exceção 23 | * 24 | * @param message Mensagem de erro 25 | */ 26 | public SafeguardException(String message) { 27 | super(message); 28 | } 29 | 30 | /** 31 | * 32 | * Construtor que recebe um (Throwable) com detalhes sobre a causa da exceção 33 | * 34 | * @param cause Causa do erro 35 | */ 36 | public SafeguardException(Throwable cause) { 37 | super(cause); 38 | } 39 | 40 | /** 41 | * 42 | * Construtor que recebe uma mesnagem (String) e um (Throwable) com detalhes sobre a causa da exceção 43 | * 44 | * @param message Mensagem de erro 45 | * @param cause Causa do erro 46 | */ 47 | public SafeguardException(String message, Throwable cause) { 48 | super(message, cause); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/interfaces/BaseParam.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.interfaces; 2 | 3 | import br.com.caelum.stella.validation.Validator; 4 | 5 | /** 6 | * Interface que deve ser implementada por um (Enum) de validadores (ParametroTipo) 7 | * para ser usado como um (Enum) que retorna instacias da classe (br.com.caelum.stella.validation.Validator) 8 | * 9 | * 10 | * @see 11 | *
    12 | *
  • Exemplo de implementação
  • 13 | *
14 | *

15 | * {@code TIPO_DO_PADRAO(new Class)) }

16 | * {@code private Validator tipo; }

17 | * {@code private Patterns(Validator tipo) }
18 | * {@code this.tipo = tipo; }

19 | * {@code @Override }
20 | * {@code public String getType() }
21 | * {@code return tipo; }
22 | *

23 | * 24 | * @author Gilmar Carlos 25 | * 26 | */ 27 | public interface BaseParam { 28 | 29 | Validator getType(); 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/interfaces/BasePattern.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.interfaces; 2 | 3 | import br.com.caelum.stella.validation.InvalidValue; 4 | 5 | /** 6 | * Interface que extende de (br.com.caelum.stella.validation) que deve ser 7 | * implementada por um (Enum) de padrões (Pattern) para ser usado em um (Enum) que implementa a interface (BaseParam) 8 | * 9 | * 10 | * @see 11 | *
    12 | *
  • https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
  • 13 | *
  • Exemplo de implementação
  • 14 | *
15 | *

16 | * {@code TIPO_DO_PADRAO(new String("[pattern]")) }

17 | * {@code private String pattern; }

18 | * {@code private Patterns(String pattern) }
19 | * {@code this.pattern = pattern; }

20 | * {@code @Override }
21 | * {@code public String getPattern() }
22 | * {@code return pattern; }
23 | *

24 | * 25 | * @author Gilmar Carlos 26 | * 27 | */ 28 | public interface BasePattern extends InvalidValue { 29 | 30 | String getPattern(); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/interfaces/Check.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.interfaces; 2 | 3 | import java.util.List; 4 | 5 | import br.com.safeguard.check.SafeguardCheck; 6 | import br.com.safeguard.types.ParametroTipo; 7 | 8 | /** 9 | * Interface com os métodos funcionais para validação de cadeia de caracteres ou objetos com atributos 10 | * anotado com (@Verify), que deve ser implementado pela as classes funcionais 11 | * 12 | * @author Gilmar Carlos 13 | * 14 | */ 15 | public interface Check { 16 | 17 | /** 18 | * Método que recebe um (String) e um (ParametroTipo) para ser adicionado em um (Map) de elementos 19 | * 20 | * @param value Valor a ser validado 21 | * @param tipo Padrão usado na validação 22 | * @return this retorna a própria classe 23 | */ 24 | SafeguardCheck elementOf(String value, ParametroTipo tipo); 25 | 26 | 27 | /** 28 | * Método que recebe um (String) e um (BaseParam) para ser adicionado em um (Map) de elementos 29 | * 30 | * @param value Valor a ser validado 31 | * @param tipo Padrão usado na validação 32 | * @return this retorna a própria classe 33 | */ 34 | SafeguardCheck elementOf(String value, BaseParam tipo); 35 | 36 | /** 37 | * Método que recebe um objeto que tenha atributos da classe anotados com (@Verify) para ser adicionado 38 | * em um (List) de elementos 39 | * 40 | * @param object Instancia da classe anotada com (@Verify) 41 | * @return this retorna a própria classe 42 | */ 43 | SafeguardCheck elementOf(Object object); 44 | 45 | /** 46 | * O método que faz a validação dos valores passados anteriormente no método {@code elementOf()}, 47 | * e retorna a própria classe 48 | * 49 | * 50 | * 51 | * Para implementação do método 52 | * 53 | *

54 | * Deve passar um (List) de objects que tenha atributos anotados com (@Verify) e/ou um (Map) de elementos com 55 | * chave (String), que representa o valor a ser validado, e um valor do tipo (Enum) que implemente a interface 56 | * (BaseParam) 57 | *

58 | * 59 | *

60 | * As coleções devem ser passadas ao método {@code void validate(Map elements) throws SafeguardException} da 61 | * da classe (ParamVerify), a chamada do método lança uma exceção do tipo checked para garantir que a coleção 62 | * passada não esteja vazia 63 | *

64 | * 65 | * @return this retorna a própria classe 66 | */ 67 | SafeguardCheck validate(); 68 | 69 | /** 70 | * Deve retornar o resultado do método {@code Boolean hasError()} da classe (ParamVerify) 71 | * 72 | * @return Boolean retorna true se houver erros de validação 73 | */ 74 | Boolean hasError(); 75 | 76 | /** 77 | * Deve retornar uma lista de elementos inválidos chamando o método {@code List getInvalidElements()} da classe (ParamVerify) 78 | * 79 | * @return List Lista de lementos inválidos 80 | */ 81 | List getInvalidElements(); 82 | 83 | /** 84 | * Deve retornar uma lista de elementos válidos chamando o método {@code List getValidElements()} da classe (ParamVerify) 85 | * 86 | * @return List Lista de elementos válidos 87 | */ 88 | List getValidElements(); 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/messages/ErrorMessage.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.messages; 2 | 3 | import br.com.caelum.stella.MessageProducer; 4 | import br.com.caelum.stella.SimpleValidationMessage; 5 | import br.com.caelum.stella.ValidationMessage; 6 | import br.com.caelum.stella.validation.InvalidValue; 7 | 8 | /** 9 | * Faz a busca de mensagens de erros nas validações 10 | * 11 | * implementa a interface {@link br.com.caelum.stella.MessageProducer} 12 | * 13 | * @author Gilmar Carlos 14 | * 15 | */ 16 | public class ErrorMessage implements MessageProducer { 17 | 18 | @Override 19 | public ValidationMessage getMessage(InvalidValue invalidValue) { 20 | String simpleName = invalidValue.getClass().getSimpleName(); 21 | String errorName = invalidValue.name(); 22 | String key = simpleName + "." + " O VALOR NÃO CORRESPONDE AO PADRÃO DO TIPO " + errorName; 23 | String message; 24 | message = key.replaceFirst("[.]", " : ").replaceAll("_", " "); 25 | return new SimpleValidationMessage(message); 26 | } 27 | 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/params/Param.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.params; 2 | 3 | import java.io.Serializable; 4 | 5 | import br.com.safeguard.interfaces.BaseParam; 6 | 7 | /** 8 | * 9 | * Classe pojo usada para servir de bind para validação de paramentros 10 | * 11 | * @author Gilmar Carlos 12 | * 13 | */ 14 | public class Param implements Serializable{ 15 | 16 | private static final long serialVersionUID = 1L; 17 | 18 | private BaseParam type; 19 | private String value; 20 | 21 | public Param(BaseParam type, String value) { 22 | this.type = type; 23 | this.value = value; 24 | } 25 | public BaseParam getType() { 26 | return type; 27 | } 28 | public void setType(BaseParam type) { 29 | this.type = type; 30 | } 31 | public String getValue() { 32 | return value; 33 | } 34 | public void setValue(String value) { 35 | this.value = value; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/patterns/Patterns.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.patterns; 2 | 3 | import br.com.safeguard.interfaces.BasePattern; 4 | 5 | /** 6 | * Enum que determina o tipo dos padrões que vão ser utilizados pelos validadores. 7 | * 8 | * O Enum implementa a interface (BasePattern), e retorna o padrão correspondente ao validador registrado em (ParametroTipo) 9 | * 10 | * @author Gilmar Carlos 11 | * 12 | */ 13 | public enum Patterns implements BasePattern{ 14 | 15 | DEFAULT (new String("[\\u0020-\\u00FC]+")), 16 | DEFAULT_SEM_SIMBOLO_DE_MAIOR (new String("[\\u0020-\\u00FC&&[^>]]+")), 17 | DEFAULT_SEM_SIMBOLO_DE_MENOR (new String("[\\u0020-\\u00FC&&[^<]]+")), 18 | DEFAULT_SEM_SIMBOLO_DE_MENOR_E_MAIOR (new String("[\\u0020-\\u00FC&&[^<>]]+")), 19 | DEFAULT_SEM_SIMBOLO_DE_CHAVES (new String("[\\u0020-\\u00FC&&[^\\{\\}]]+")), 20 | DEFAULT_SEM_SIMBOLO_DE_COLCHETES (new String("[\\u0020-\\u00FC&&[^\\[\\]]]+")), 21 | DEFAULT_SEM_SIMBOLO_DE_PARENTESES (new String("[\\u0020-\\u00FC&&[^\\(\\)]]+")), 22 | DEFAULT_SEM_SIMBOLO_DE_ASTERISCO (new String("[\\u0020-\\u00FC&&[^*]]+")), 23 | DEFAULT_SEM_SIMBOLO_DE_ARROBA (new String("[\\u0020-\\u00FC&&[^@]]+")), 24 | DEFAULT_SEM_SIMBOLO_DE_HASHTAG (new String("[\\u0020-\\u00FC&&[^#]]+")), 25 | DEFAULT_SEM_SIMBOLO_DE_SIFRAO (new String("[\\u0020-\\u00FC&&[^$]]+")), 26 | DEFAULT_SEM_SIMBOLO_DE_PORCENTAGEM (new String("[\\u0020-\\u00FC&&[^%]]+")), 27 | DEFAULT_SEM_SIMBOLO_DE_TREMA (new String("[\\u0020-\\u00FC&&[^¨]]+")), 28 | DEFAULT_SEM_SIMBOLO_DE_E_COMERCIAL (new String("[\\u0020-\\u00FC&&[^&]]+")), 29 | DEFAULT_SEM_SIMBOLO_DE_UNDERLINE (new String("[\\u0020-\\u00FC&&[^_]]+")), 30 | DEFAULT_SEM_SIMBOLO_DE_HIFEM (new String("[\\u0020-\\u00FC&&[^\\-]]+")), 31 | DEFAULT_SEM_SIMBOLO_DE_MAIS (new String("[\\u0020-\\u00FC&&[^+]]+")), 32 | DEFAULT_SEM_SIMBOLO_DE_ASPAS_SIMPLES (new String("[\\u0020-\\u00FC&&[^\']]+")), 33 | DEFAULT_SEM_SIMBOLO_DE_ASPAS_DUPLA (new String("[\\u0020-\\u00FC&&[^\"]]+")), 34 | DEFAULT_SEM_SIMBOLO_DE_PONTO (new String("[\\u0020-\\u00FC&&[^.]]+")), 35 | DEFAULT_SEM_SIMBOLO_DE_VIRGULA (new String("[\\u0020-\\u00FC&&[^,]]+")), 36 | DEFAULT_SEM_SIMBOLO_DE_DOIS_PONTOS (new String("[\\u0020-\\u00FC&&[^:]]+")), 37 | DEFAULT_SEM_SIMBOLO_DE_PONTO_E_VIRGULA (new String("[\\u0020-\\u00FC&&[^;]]+")), 38 | DEFAULT_SEM_SIMBOLO_DE_PONTO_DE_EXCLAMACAO (new String("[\\u0020-\\u00FC&&[^!]]+")), 39 | DEFAULT_SEM_SIMBOLO_DE_PONTO_DE_INTERROGACAO (new String("[\\u0020-\\u00FC&&[^?]]+")), 40 | DEFAULT_SEM_PONTUACAO (new String("[\\u0020-\\u00FC&&[^!?.,:;]]+")), 41 | DEFAULT_SEM_NUMEROS (new String("[\\u0020-\\u00FC&&[^\\d]]+")), 42 | DEFAULT_SEM_SINAIS_MATEMATICOS (new String("[\\u0020-\\u00FC&&[^/*\\-+=]]+")), 43 | DEFAULT_SEM_CARACTERES_ESPECIAIS (new String("[\\u0020-\\u00FC&&[^\\p{Punct}]]+")), 44 | 45 | TEXTO_SEM_CARACTERES_ESPECIAIS (new String("[\\u0020-\\u00FC&&[^\\d\\p{Punct}\\u007F-\\u00BF]]+")), 46 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_HIFEM (new String("[\\u0020-\\u00FC&&[\\sa-zA-Z\\-\\u00C0-\\u00FC]]+")), 47 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_UNDERLINE (new String("[\\u0020-\\u00FC&&[\\sa-zA-Z_\\u00C0-\\u00FC]]+")), 48 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_VIRGULA (new String("[\\u0020-\\u00FC&&[\\sa-zA-Z,\\u00C0-\\u00FC]]+")), 49 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO (new String("[\\u0020-\\u00FC&&[\\sa-zA-Z!?.,:;\\u00C0-\\u00FC]]+")), 50 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE (new String("[\\u0020-\\u00FC&&[\\sa-zA-Z!?.,:;_\\-\\u00C0-\\u00FC]]+")), 51 | 52 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS (new String("[\\u0020-\\u00FC&&[^\\p{Punct}\\u007F-\\u00BF]]+")), 53 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_HIFEM (new String("[\\u0020-\\u00FC&&[\\d\\sa-zA-Z\\-\\u00C0-\\u00FC]]+")), 54 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_UNDERLINE (new String("[\\u0020-\\u00FC&&[\\d\\sa-zA-Z_\\u00C0-\\u00FC]]+")), 55 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_VIRGULA (new String("[\\u0020-\\u00FC&&[\\d\\sa-zA-Z,\\u00C0-\\u00FC]]+")), 56 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO (new String("[\\u0020-\\u00FC&&[\\d\\sa-zA-Z!?.,:;\\u00C0-\\u00FC]]+")), 57 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE (new String("[\\u0020-\\u00FC&&[\\d\\sa-zA-Z!?.,:;_\\-\\u00C0-\\u00FC]]+")), 58 | TEXTO_NUMERO_VIRGULA_HIFEM_UNDERLINE_SEM_PONTUACAO (new String("[^<>`´~^'¬¢£³²¹!?@#$%¨&*+=§/\\|\\^\\]\\[\\{\\}\\(\\)\"]+")), 59 | 60 | NUMERO (new String("[^\\D]+")), 61 | 62 | EMAIL (new String("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$")), 63 | 64 | CEP (new String("[^\\D]{8}")), 65 | CEP_FORMATADO (new String("\\d{5}-\\d{3}")), 66 | 67 | PLACA_DE_VEICULO_BRASIL (new String("[A-Z]{3}\\d{4}")), 68 | PLACA_DE_VEICULO_FORMATADO_BRASIL (new String("[A-Z]{3}\\-\\d{4}")), 69 | 70 | TELEFONE (new String("([0]{1}(12|15|21|31|41|43))?[1-9]{2}[9]?[\\d]{8}")), 71 | TELEFONE_FORMATADO_BRASIL (new String("([0]{1}(12|15|21|31|41|43))?\\([1-9]{2}\\)[9]?[\\d]{4}\\-[\\d]{4}")), 72 | TELEFONE_FORMATADO_INTERNACIONAL (new String("\\+[\\d]{1,3}\\s[1-9]{2}\\s[9]?[\\d]{4}\\-[\\d]{4}")); 73 | 74 | private String pattern; 75 | 76 | private Patterns(String pattern) { 77 | this.pattern = pattern; 78 | } 79 | 80 | @Override 81 | public String getPattern() { 82 | return pattern; 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/types/ParametroTipo.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.types; 2 | 3 | import br.com.caelum.stella.validation.CNPJValidator; 4 | import br.com.caelum.stella.validation.CPFValidator; 5 | import br.com.caelum.stella.validation.NITValidator; 6 | import br.com.caelum.stella.validation.TituloEleitoralValidator; 7 | import br.com.caelum.stella.validation.Validator; 8 | import br.com.caelum.stella.validation.ie.IEAcreValidator; 9 | import br.com.caelum.stella.validation.ie.IEAlagoasValidator; 10 | import br.com.caelum.stella.validation.ie.IEAmapaValidator; 11 | import br.com.caelum.stella.validation.ie.IEAmazonasValidator; 12 | import br.com.caelum.stella.validation.ie.IEBahiaValidator; 13 | import br.com.caelum.stella.validation.ie.IECearaValidator; 14 | import br.com.caelum.stella.validation.ie.IEDistritoFederalValidator; 15 | import br.com.caelum.stella.validation.ie.IEEspiritoSantoValidator; 16 | import br.com.caelum.stella.validation.ie.IEGoiasValidator; 17 | import br.com.caelum.stella.validation.ie.IEMaranhaoValidator; 18 | import br.com.caelum.stella.validation.ie.IEMatoGrossoDoSulValidator; 19 | import br.com.caelum.stella.validation.ie.IEMatoGrossoValidator; 20 | import br.com.caelum.stella.validation.ie.IEMinasGeraisValidator; 21 | import br.com.caelum.stella.validation.ie.IEParaValidator; 22 | import br.com.caelum.stella.validation.ie.IEParaibaValidator; 23 | import br.com.caelum.stella.validation.ie.IEParanaValidator; 24 | import br.com.caelum.stella.validation.ie.IEPernambucoValidator; 25 | import br.com.caelum.stella.validation.ie.IEPiauiValidator; 26 | import br.com.caelum.stella.validation.ie.IERioDeJaneiroValidator; 27 | import br.com.caelum.stella.validation.ie.IERioGrandeDoNorteValidator; 28 | import br.com.caelum.stella.validation.ie.IERioGrandeDoSulValidator; 29 | import br.com.caelum.stella.validation.ie.IERondoniaValidator; 30 | import br.com.caelum.stella.validation.ie.IERoraimaValidator; 31 | import br.com.caelum.stella.validation.ie.IESantaCatarinaValidator; 32 | import br.com.caelum.stella.validation.ie.IESaoPauloValidator; 33 | import br.com.caelum.stella.validation.ie.IESergipeValidator; 34 | import br.com.caelum.stella.validation.ie.IETocantinsValidator; 35 | import br.com.safeguard.interfaces.BaseParam; 36 | import br.com.safeguard.patterns.Patterns; 37 | import br.com.safeguard.validators.PatternValidator; 38 | 39 | /** 40 | * Enum que determina o tipo das validações e retornam o validador correspondente. 41 | * 42 | * O Enum implementa a interface (BaseParam), e faz uso dos padrões registrados em (Patterns) 43 | * 44 | *

45 | * Default é validação padrão registrada pelo validador 46 | *

47 | * 48 | * @author Gilmar Carlos 49 | * 50 | */ 51 | public enum ParametroTipo implements BaseParam{ 52 | 53 | /**Cadeia de caracteres que representa um documento de CPF*/ 54 | CPF (new CPFValidator()), 55 | /**Cadeia de caracteres que representa um documento de CPF formatado*/ 56 | CPF_FORMATADO (new CPFValidator(true)), 57 | /**Cadeia de caracteres que representa um documento de Titulo de Eleitor*/ 58 | TITULO_DE_ELEITOR (new TituloEleitoralValidator()), 59 | /**Cadeia de caracteres que representa um documento de Titulo de Eleitor formatado*/ 60 | TITULO_DE_ELEITOR_FORMATADO (new TituloEleitoralValidator(true)), 61 | /**Cadeia de caracteres que representa um documento de Número de Indentificação do Trabalhador*/ 62 | NIT (new NITValidator()), 63 | /**Cadeia de caracteres que representa um documento de Número de Indentificação do Trabalhador formatado*/ 64 | NIT_FORMATADO (new NITValidator(true)), 65 | 66 | /**Cadeia de caracteres que representa um CNPJ*/ 67 | CNPJ (new CNPJValidator()), 68 | /**Cadeia de caracteres que representa um CNPJ formatado*/ 69 | CNPJ_FORMATADO (new CNPJValidator(true)), 70 | 71 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 72 | IE_ACRE_AC (new IEAcreValidator()), 73 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 74 | IE_ACRE_AC_FORMATADO (new IEAcreValidator(true)), 75 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 76 | IE_ALAGOAS_AL (new IEAlagoasValidator()), 77 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 78 | IE_ALAGOAS_AL_FORMATADO (new IEAlagoasValidator(true)), 79 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 80 | IE_AMAPA_AP (new IEAmapaValidator()), 81 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 82 | IE_AMAPA_AP_FORMATADO (new IEAmapaValidator(true)), 83 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 84 | IE_AMAZONAS_AM (new IEAmazonasValidator()), 85 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 86 | IE_AMAZONAS_AM_FORMATADO (new IEAmazonasValidator(true)), 87 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 88 | IE_BAHIA_BA (new IEBahiaValidator()), 89 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 90 | IE_BAHIA_BA_FORMATADO (new IEBahiaValidator(true)), 91 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 92 | IE_CEARA_CE (new IECearaValidator()), 93 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 94 | IE_CEARA_CE_FORMATADO (new IECearaValidator(true)), 95 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 96 | IE_DISTRITO_FEDERAL_DF (new IEDistritoFederalValidator()), 97 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 98 | IE_DISTRITO_FEDERAL_DF_FORMATADO (new IEDistritoFederalValidator(true)), 99 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 100 | IE_ESPIRITO_SANTO_ES (new IEEspiritoSantoValidator()), 101 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 102 | IE_ESPIRITO_SANTO_ES_FORMATADO (new IEEspiritoSantoValidator(true)), 103 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 104 | IE_GOIAIS_GO (new IEGoiasValidator()), 105 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 106 | IE_GOIAIS_GO_FORMATADO (new IEGoiasValidator(true)), 107 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 108 | IE_MARANHAO_MA (new IEMaranhaoValidator()), 109 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 110 | IE_MARANHAO_MA_FORMATADO (new IEMaranhaoValidator(true)), 111 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 112 | IE_MATO_GROSSO_MT (new IEMatoGrossoValidator()), 113 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 114 | IE_MATO_GROSSO_MT_FORMATADO (new IEMatoGrossoValidator(true)), 115 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 116 | IE_MATO_GROSSO_DO_SUL_MS (new IEMatoGrossoDoSulValidator()), 117 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 118 | IE_MATO_GROSSO_DO_SUL_MS_FORMATADO (new IEMatoGrossoDoSulValidator(true)), 119 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 120 | IE_MINAS_GERAIS_MG (new IEMinasGeraisValidator()), 121 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 122 | IE_MINAS_GERAIS_MG_FORMATADO (new IEMinasGeraisValidator(true)), 123 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 124 | IE_PARA_PA (new IEParaValidator()), 125 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 126 | IE_PARA_PA_FORMATADO (new IEParaValidator(true)), 127 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 128 | IE_PARAIBA_PB (new IEParaibaValidator()), 129 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 130 | IE_PARAIBA_PB_FORMATADO (new IEParaibaValidator(true)), 131 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 132 | IE_PARARA_PR (new IEParanaValidator()), 133 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 134 | IE_PARARA_PR_FORMATADO (new IEParanaValidator(true)), 135 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 136 | IE_PERNAMBUCO_PE (new IEPernambucoValidator()), 137 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 138 | IE_PERNAMBUCO_PE_FORMATADO (new IEPernambucoValidator(true)), 139 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 140 | IE_PIAUI_PI (new IEPiauiValidator()), 141 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 142 | IE_PIAUI_PI_FORMATADO (new IEPiauiValidator(true)), 143 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 144 | IE_RIO_DE_JANEIRO_RJ (new IERioDeJaneiroValidator()), 145 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 146 | IE_RIO_DE_JANEIRO_RJ_FORMATADO (new IERioDeJaneiroValidator(true)), 147 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 148 | IE_RIO_GRANDE_DO_NORTE_RN (new IERioGrandeDoNorteValidator()), 149 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 150 | IE_RIO_GRANDE_DO_NORTE_RN_FORMATADO (new IERioGrandeDoNorteValidator(true)), 151 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 152 | IE_RIO_GRANDE_DO_SUL_RS (new IERioGrandeDoSulValidator()), 153 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 154 | IE_RIO_GRANDE_DO_SUL_RS_FORMATADO (new IERioGrandeDoSulValidator(true)), 155 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 156 | IE_RONDONIA_RO (new IERondoniaValidator()), 157 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 158 | IE_RONDONIA_RO_FORMATADO (new IERondoniaValidator(true)), 159 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 160 | IE_RORAIMA_RR (new IERoraimaValidator()), 161 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 162 | IE_RORAIMA_RR_FORMATADO (new IERoraimaValidator(true)), 163 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 164 | IE_SANTA_CATARINA_SC (new IESantaCatarinaValidator()), 165 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 166 | IE_SANTA_CATARINA_SC_FORMATADO (new IESantaCatarinaValidator(true)), 167 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 168 | IE_SAO_PAULO_SP (new IESaoPauloValidator()), 169 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 170 | IE_SAO_PAULO_SP_FORMATADO (new IESaoPauloValidator(true)), 171 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 172 | IE_SERGIPE_SE (new IESergipeValidator()), 173 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 174 | IE_SERGIPE_SE_FORMATADO (new IESergipeValidator(true)), 175 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 176 | IE_TOCANTINS_TO (new IETocantinsValidator()), 177 | /**Cadeia de caracteres que representa uma Inscrição estadual*/ 178 | IE_TOCANTINS_TO_FORMATADO (new IETocantinsValidator(true)), 179 | 180 | /** 181 | * Cadeia de caracteres de texto padrão, contendo caracters da tabela unicode 182 | * iniciando em \u0020 e terminando em \u00FC 183 | */ 184 | DEFAULT (new PatternValidator()), 185 | /**Cadeia de caracteres de texto padrão sem o sinal de maior */ 186 | DEFAULT_SEM_SIMBOLO_DE_MAIOR (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_MAIOR)), 187 | /**Cadeia de caracteres de texto padrão sem o sinal de menor */ 188 | DEFAULT_SEM_SIMBOLO_DE_MENOR (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_MENOR)), 189 | /**Cadeia de caracteres de texto padrão sem o sinal de menor e maior*/ 190 | DEFAULT_SEM_SIMBOLO_DE_MENOR_E_MAIOR (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_MENOR_E_MAIOR)), 191 | /**Cadeia de caracteres de texto padrão sem o sinal de chaves */ 192 | DEFAULT_SEM_SIMBOLO_DE_CHAVES (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_CHAVES)), 193 | /**Cadeia de caracteres de texto padrão sem o sinal de colchetes */ 194 | DEFAULT_SEM_SIMBOLO_DE_COLCHETES (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_COLCHETES)), 195 | /**Cadeia de caracteres de texto padrão sem o sinal de parneteses */ 196 | DEFAULT_SEM_SIMBOLO_DE_PARENTESES (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_PARENTESES)), 197 | /**Cadeia de caracteres de texto padrão sem o sinal de asterisco */ 198 | DEFAULT_SEM_SIMBOLO_DE_ASTERISCO (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_ASTERISCO)), 199 | /**Cadeia de caracteres de texto padrão sem o sinal de arroba */ 200 | DEFAULT_SEM_SIMBOLO_DE_ARROBA (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_ARROBA)), 201 | /**Cadeia de caracteres de texto padrão sem o sinal de hashtag */ 202 | DEFAULT_SEM_SIMBOLO_DE_HASHTAG (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_HASHTAG)), 203 | /**Cadeia de caracteres de texto padrão sem o sinal de sifrão */ 204 | DEFAULT_SEM_SIMBOLO_DE_SIFRAO (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_SIFRAO)), 205 | /**Cadeia de caracteres de texto padrão sem o sinal de porcentagem */ 206 | DEFAULT_SEM_SIMBOLO_DE_PORCENTAGEM (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_PORCENTAGEM)), 207 | /**Cadeia de caracteres de texto padrão sem o sinal de trema */ 208 | DEFAULT_SEM_SIMBOLO_DE_TREMA (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_TREMA)), 209 | /**Cadeia de caracteres de texto padrão sem o sinal de e comercial */ 210 | DEFAULT_SEM_SIMBOLO_DE_E_COMERCIAL (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_E_COMERCIAL)), 211 | /**Cadeia de caracteres de texto padrão sem o sinal de underline */ 212 | DEFAULT_SEM_SIMBOLO_DE_UNDERLINE (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_UNDERLINE)), 213 | /**Cadeia de caracteres de texto padrão sem o sinal de hífem */ 214 | DEFAULT_SEM_SIMBOLO_DE_HIFEM (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_HIFEM)), 215 | /**Cadeia de caracteres de texto padrão sem o sinal de mais */ 216 | DEFAULT_SEM_SIMBOLO_DE_MAIS (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_MAIS)), 217 | /**Cadeia de caracteres de texto padrão sem o sinal de aspas simples */ 218 | DEFAULT_SEM_SIMBOLO_DE_ASPAS_SIMPLES (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_ASPAS_SIMPLES)), 219 | /**Cadeia de caracteres de texto padrão sem o sinal de aspas duplas */ 220 | DEFAULT_SEM_SIMBOLO_DE_ASPAS_DUPLA (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_ASPAS_DUPLA)), 221 | /**Cadeia de caracteres de texto padrão sem o sinal de ponto */ 222 | DEFAULT_SEM_SIMBOLO_DE_PONTO (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_PONTO)), 223 | /**Cadeia de caracteres de texto padrão sem o sinal de virgula */ 224 | DEFAULT_SEM_SIMBOLO_DE_VIRGULA (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_VIRGULA)), 225 | /**Cadeia de caracteres de texto padrão sem o sinal de dois pontos */ 226 | DEFAULT_SEM_SIMBOLO_DE_DOIS_PONTOS (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_DOIS_PONTOS)), 227 | /**Cadeia de caracteres de texto padrão sem o sinal de ponto e virgula */ 228 | DEFAULT_SEM_SIMBOLO_DE_PONTO_E_VIRGULA (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_PONTO_E_VIRGULA)), 229 | /**Cadeia de caracteres de texto padrão sem o sinal de exclamação */ 230 | DEFAULT_SEM_SIMBOLO_DE_PONTO_DE_EXCLAMACAO (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_PONTO_DE_EXCLAMACAO)), 231 | /**Cadeia de caracteres de texto padrão sem o sinal de interrogação */ 232 | DEFAULT_SEM_SIMBOLO_DE_PONTO_DE_INTERROGACAO (new PatternValidator(Patterns.DEFAULT_SEM_SIMBOLO_DE_PONTO_DE_INTERROGACAO)), 233 | /**Cadeia de caracteres de texto padrão sem pontuação */ 234 | DEFAULT_SEM_PONTUACAO (new PatternValidator(Patterns.DEFAULT_SEM_PONTUACAO)), 235 | /**Cadeia de caracteres de texto padrão sem números */ 236 | DEFAULT_SEM_NUMEROS (new PatternValidator(Patterns.DEFAULT_SEM_NUMEROS)), 237 | /**Cadeia de caracteres de texto padrão sem sinais matemáticos */ 238 | DEFAULT_SEM_SINAIS_MATEMATICOS (new PatternValidator(Patterns.DEFAULT_SEM_SINAIS_MATEMATICOS)), 239 | /**Cadeia de caracteres de texto padrão sem caracteres especiais */ 240 | DEFAULT_SEM_CARACTERES_ESPECIAIS (new PatternValidator(Patterns.DEFAULT_SEM_CARACTERES_ESPECIAIS)), 241 | 242 | /**Cadeia de caracteres apenas com texto, sem númeors ou caracteres especiais*/ 243 | TEXTO_SEM_CARACTERES_ESPECIAIS (new PatternValidator(Patterns.TEXTO_SEM_CARACTERES_ESPECIAIS)), 244 | /**Cadeia de caracteres apenas com texto e hífem, sem númeors ou caracteres especiais*/ 245 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_HIFEM (new PatternValidator(Patterns.TEXTO_SEM_CARACTERES_ESPECIAIS_COM_HIFEM)), 246 | /**Cadeia de caracteres apenas com texto e underline, sem númeors ou caracteres especiais*/ 247 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_UNDERLINE (new PatternValidator(Patterns.TEXTO_SEM_CARACTERES_ESPECIAIS_COM_UNDERLINE)), 248 | /**Cadeia de caracteres apenas com texto e virgula, sem númeors ou caracteres especiais*/ 249 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_VIRGULA (new PatternValidator(Patterns.TEXTO_SEM_CARACTERES_ESPECIAIS_COM_VIRGULA)), 250 | /**Cadeia de caracteres apenas com texto e pontuação, sem númeors ou caracteres especiais*/ 251 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO (new PatternValidator(Patterns.TEXTO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO)), 252 | /**Cadeia de caracteres apenas com texto, pontuação, hífem e underline, sem númeors ou caracteres especiais*/ 253 | TEXTO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE (new PatternValidator(Patterns.TEXTO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE)), 254 | 255 | /**Cadeia de caracteres com texto e número, sem caracteres especiais*/ 256 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS (new PatternValidator(Patterns.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS)), 257 | /**Cadeia de caracteres com texto, números e hífem, sem caracteres especiais*/ 258 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_HIFEM (new PatternValidator(Patterns.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_HIFEM)), 259 | /**Cadeia de caracteres com texto, números e underline, sem caracteres especiais*/ 260 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_UNDERLINE (new PatternValidator(Patterns.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_UNDERLINE)), 261 | /**Cadeia de caracteres com texto, números e virgula, sem caracteres especiais*/ 262 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_VIRGULA (new PatternValidator(Patterns.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_VIRGULA)), 263 | /**Cadeia de caracteres com texto, números e pontuação, sem caracteres especiais*/ 264 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO (new PatternValidator(Patterns.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO)), 265 | /**Cadeia de caracteres com texto, números, pontuação, hífem e underline, sem caracteres especiais*/ 266 | TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE (new PatternValidator(Patterns.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE)), 267 | /**Cadeia de caracteres com texto, números, virgula, hífem e underline, sem caracteres especiais*/ 268 | TEXTO_NUMERO_VIRGULA_HIFEM_UNDERLINE_SEM_PONTUACAO (new PatternValidator(Patterns.TEXTO_NUMERO_VIRGULA_HIFEM_UNDERLINE_SEM_PONTUACAO)), 269 | 270 | /**Cadeia de caracteres contendo apenas números*/ 271 | NUMERO (new PatternValidator(Patterns.NUMERO)), 272 | 273 | /**Cadeia de caracteres que representa um email*/ 274 | EMAIL (new PatternValidator(Patterns.EMAIL)), 275 | 276 | /**Cadeia de caracteres que representa um CEP*/ 277 | CEP (new PatternValidator(Patterns.CEP)), 278 | /**Cadeia de caracteres que representa um CEP formatado*/ 279 | CEP_FORMATADO (new PatternValidator(Patterns.CEP_FORMATADO)), 280 | 281 | /**Cadeia de caracteres que representa uma placa de veículo*/ 282 | PLACA_DE_VEICULO_BRASIL (new PatternValidator(Patterns.PLACA_DE_VEICULO_BRASIL)), 283 | /**Cadeia de caracteres que representa uma placa de veículo formatado*/ 284 | PLACA_DE_VEICULO_FORMATADO_BRASIL (new PatternValidator(Patterns.PLACA_DE_VEICULO_FORMATADO_BRASIL)), 285 | 286 | /** 287 | * Cadeia de caracteres que representa um telefone fixo ou móvel com ou sem número da operadora, DD + NÚMERO 288 | * 289 | * 290 | * Exemplos: 291 | *
    292 | *
  • Com número da operadora 01211988774455, obs.: O dígito 9 pode ser omitido para telefones fixos 1133445566
  • 293 | *
  • Sem o número da operadora 11988774455
  • 294 | *
295 | * 296 | * 297 | */ 298 | TELEFONE (new PatternValidator(Patterns.TELEFONE)), 299 | 300 | /** 301 | * Cadeia de caracteres que representa um telefone fixo ou móvel com ou sem número da operadora, DD + NÚMERO formatado 302 | * 303 | * 304 | * Exemplos: 305 | *
    306 | *
  • Com número da operadora 012(11)98877-4455, obs.: O dígito 9 pode ser omitido para telefones fixos (11)3344-5566
  • 307 | *
  • Sem o número da operadora (11)98877-4455
  • 308 | *
309 | * 310 | * 311 | */ 312 | TELEFONE_FORMATADO_BRASIL (new PatternValidator(Patterns.TELEFONE_FORMATADO_BRASIL)), 313 | /** 314 | * Cadeia de caracteres que representa um telefone fixo ou móvel com o número do país, DD + NÚMERO formatado 315 | * 316 | * 317 | * Exemplos: 318 | *
    319 | *
  • Formato internacional: +55 11 98877-4455, obs.: O dígito 9 pode ser omitido para telefones fixos +55 11 3344-5566
  • 320 | *
321 | * 322 | * 323 | */ 324 | TELEFONE_FORMATADO_INTERNACIONAL (new PatternValidator(Patterns.TELEFONE_FORMATADO_INTERNACIONAL)); 325 | 326 | private Validator type; 327 | 328 | private ParametroTipo(Validator type){ 329 | this.type = type; 330 | } 331 | 332 | @Override 333 | public Validator getType() { 334 | return type; 335 | } 336 | 337 | } 338 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/validators/PatternValidator.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.validators; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.regex.Pattern; 6 | 7 | import br.com.caelum.stella.MessageProducer; 8 | import br.com.caelum.stella.ValidationMessage; 9 | import br.com.caelum.stella.validation.InvalidStateException; 10 | import br.com.caelum.stella.validation.Validator; 11 | import br.com.safeguard.interfaces.BasePattern; 12 | import br.com.safeguard.messages.ErrorMessage; 13 | import br.com.safeguard.patterns.Patterns; 14 | 15 | /** 16 | * Classe que verifica uma cadeia de caracteres baseado em padrões (Patterns), implementa 17 | * a interface {@link br.com.caelum.stella.validation.Validator} 18 | * 19 | * @author Gilmar Carlos 20 | * 21 | */ 22 | public class PatternValidator implements Validator { 23 | 24 | private MessageProducer message; 25 | private BasePattern pattern; 26 | 27 | /** 28 | * Construtror padrão que inicializa o pattern default e a classe de mensagens de erros (ErrorMessage) 29 | */ 30 | public PatternValidator() { 31 | 32 | this.pattern = Patterns.DEFAULT; 33 | this.message = new ErrorMessage(); 34 | } 35 | 36 | /** 37 | * Construtror genérico que recebe qualquer padrão que implemente (BasePattern) e inicializa a classe de mensagens de erros 38 | * 39 | * @param pattern Instancia do padrão a ser analisado 40 | */ 41 | public PatternValidator(BasePattern pattern){ 42 | this.pattern = pattern; 43 | this.message = new ErrorMessage(); 44 | } 45 | 46 | /** 47 | * Construtror distinto que recebe padrões do tipo (Patterns) e inicializa a classe de mensagens de erros 48 | * 49 | * @param pattern Instancia do padrão a ser analisado 50 | */ 51 | public PatternValidator(Patterns pattern) { 52 | this.pattern = pattern; 53 | this.message = new ErrorMessage(); 54 | } 55 | 56 | /** 57 | * 58 | * Método que adiciona elementos inválidos em um (List) caso sua validação contenha erros 59 | * 60 | * @param value Valor a ser analisado 61 | * @return List Lista de mensagens de erros 62 | */ 63 | private List getInvalidValues(String value) { 64 | List errors = new ArrayList<>(); 65 | if (!Pattern.matches(pattern.getPattern(), value)) { 66 | errors.add(message.getMessage(pattern)); 67 | } 68 | return errors; 69 | } 70 | 71 | @Override 72 | public void assertValid(String value) { 73 | List errors = getInvalidValues(value); 74 | if (!errors.isEmpty()) { 75 | throw new InvalidStateException(errors); 76 | } 77 | } 78 | 79 | 80 | @Override 81 | public List invalidMessagesFor(String value) { 82 | return getInvalidValues(value); 83 | } 84 | 85 | 86 | @Override 87 | public boolean isEligible(String object) { 88 | 89 | if (object != null) { 90 | return true; 91 | } 92 | 93 | return false; 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/br/com/safeguard/verifies/ParamVerify.java: -------------------------------------------------------------------------------- 1 | package br.com.safeguard.verifies; 2 | 3 | import java.lang.reflect.Field; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import br.com.caelum.stella.validation.InvalidStateException; 9 | import br.com.safeguard.constraint.annotations.Verify; 10 | import br.com.safeguard.exceptions.SafeguardException; 11 | import br.com.safeguard.interfaces.BaseParam; 12 | import br.com.safeguard.params.Param; 13 | 14 | /** 15 | * Classe de verificação genérica para uma cadeia de caracteres formatados ou não, os dados podem ser 16 | * validados a partir de uma (Map) com chaves do tipo (String) e valores de tipos (ParametroTipo) que implementam 17 | * a interface (BaseParam) 18 | * 19 | * @author Gilmar Carlos 20 | * 21 | */ 22 | public class ParamVerify { 23 | 24 | private List validElements; 25 | private List invalidElements; 26 | 27 | /** 28 | * Construtor padrão, que inicializa a implementação de (List) 29 | */ 30 | public ParamVerify() { 31 | this(new ArrayList(), new ArrayList()); 32 | } 33 | 34 | /** 35 | * Construtor secundário, que recebe a implementação de (List) 36 | * 37 | * @param validElements Lista de elementos válidos 38 | * @param invalidElements Lista de elementos inválidos 39 | * 40 | */ 41 | public ParamVerify(List validElements, List invalidElements) { 42 | this.validElements = validElements; 43 | this.invalidElements = invalidElements; 44 | } 45 | 46 | /** 47 | * Método public que recebe um (Map) de elementos, verifica se a coleção não está vazia, percorre os elementos e 48 | * chama o método {@code void assertValid(String value, BaseParam param)} para cada interação 49 | * 50 | * @param elements Uma coleção de elementos 51 | * @throws SafeguardException se o (Map) estiver vazio 52 | * 53 | */ 54 | public void validate(Map elements) throws SafeguardException { 55 | if(elements.isEmpty()) { 56 | throw new SafeguardException("The map can not be empty"); 57 | } 58 | elements.forEach((Integer, param) -> assertValid(param.getValue(), param.getType())); 59 | } 60 | 61 | /** 62 | * Método public que recebe um (List) de elementos, verifica se a coleção não está vazia, percorre os elementos e 63 | * chama o método {@code void validate(Object object)} para cada interação 64 | * 65 | * @param elements Uma lista de elementos 66 | * @throws SafeguardException se o (List) estiver vazio 67 | * 68 | */ 69 | public void validate(List elements) throws SafeguardException{ 70 | if(elements.isEmpty()) { 71 | throw new SafeguardException("The list can not be empty"); 72 | } 73 | elements.forEach( element -> validate(element)); 74 | } 75 | 76 | /** 77 | * Método public booleano que verifica se a (List) de elementos inválidos não está vazia 78 | * 79 | * @return boolean false se a lista estiver vazia, indicando que não há erros de validação 80 | * true caso contrário 81 | */ 82 | public boolean hasError() { 83 | if (invalidElements.isEmpty()) { 84 | return false; 85 | } 86 | return true; 87 | } 88 | 89 | /** 90 | * Método public que retorna uma lista de elementos inválidos 91 | * 92 | * @return List Lista de elementos inválidos 93 | */ 94 | public List getInvalidElements() { 95 | return invalidElements; 96 | } 97 | 98 | /** 99 | * Método public que retorna uma lista de elementos válidos 100 | * 101 | * @return List Lista de elementos válidos 102 | */ 103 | public List getValidElements() { 104 | return validElements; 105 | } 106 | 107 | /** 108 | * Método private que valida um objeto que tem atributos anotados com @Verify. 109 | *

Percorre um laço para verificar se cada atributo está anotado

110 | * 111 | * @param object Instancia da classe anotada com (@Verify) 112 | */ 113 | private void validate(Object object) { 114 | Class clazz = object.getClass(); 115 | for (Field field : clazz.getDeclaredFields()) { 116 | if (isVerifiable(field)) { 117 | validate(object, field); 118 | } 119 | } 120 | } 121 | 122 | /** 123 | * Método private que valida um objeto que tem atributos anotados com @Verify 124 | *

Pega o valor do atributo da classe e da anotação

125 | * 126 | * @param object Instancia da classe anotada com (@Verify) 127 | * @param field Atributos da classe anotadas com (@Verify) 128 | * 129 | * @throws InvalidStateException caso o valor do elemento seja inválido 130 | * @throws IllegalArgumentException olha java doc 131 | * @throws IllegalAccessException olhar java doc 132 | * 133 | * @see 134 | *
    135 | *
  • https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalAccessException.html
  • 136 | *
  • https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html
  • 137 | *
138 | */ 139 | private void validate(Object object, Field field) { 140 | try { 141 | for(BaseParam param : field.getAnnotation(Verify.class).value()) { 142 | String value = String.valueOf(field.get(object)); 143 | assertValid(value, param); 144 | } 145 | } catch (InvalidStateException e) { 146 | System.err.println(field.getName() + " isn't valid "); 147 | e.printStackTrace(); 148 | } catch (IllegalArgumentException e) { 149 | e.printStackTrace(); 150 | } catch (IllegalAccessException e) { 151 | e.printStackTrace(); 152 | } 153 | } 154 | 155 | /** 156 | * Método private que valida um objeto que tem atributos anotados com @Verify 157 | *

Verifica se o atributo da classe é acessível e está anotado

158 | * 159 | * @param field Atributos da classe anotadas com (@Verify) 160 | * @return boolean true se for acessível e estiver anotado 161 | * false caso contrário 162 | */ 163 | private boolean isVerifiable(Field field) { 164 | 165 | field.setAccessible(true); 166 | if (field.isAccessible() && field.isAnnotationPresent(Verify.class)) { 167 | return true; 168 | } 169 | return false; 170 | } 171 | 172 | /** 173 | * Método private que faz a validação do valor baseado no tipo do paramentro especificado 174 | * 175 | * @param value Valor a ser validado 176 | * @param param Tipo que contém o padrão para validação 177 | * 178 | * @throws InvalidStateException e caso o elemento tenha seu valor inválido 179 | */ 180 | private void assertValid(String value, BaseParam param) { 181 | try { 182 | param.getType().assertValid(value); 183 | validElements.add(value); 184 | } catch (InvalidStateException e) { 185 | invalidElements.add(value); 186 | e.printStackTrace(); 187 | } 188 | } 189 | 190 | } 191 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gilmardeveloper/java-validator-safeguard/63d6a2aa8452400f56622511b4cf220894cd8889/src/main/resources/application.properties -------------------------------------------------------------------------------- /src/test/java/com/gilmarcarlos/developer/safeguard/TesteDeObjetosAnotados.java: -------------------------------------------------------------------------------- 1 | package com.gilmarcarlos.developer.safeguard; 2 | 3 | import java.io.Serializable; 4 | import java.util.Set; 5 | 6 | import javax.validation.ConstraintViolation; 7 | import javax.validation.Validation; 8 | import javax.validation.ValidatorFactory; 9 | import javax.validation.groups.Default; 10 | 11 | import org.junit.Assert; 12 | import org.junit.Test; 13 | import org.junit.runner.RunWith; 14 | import org.springframework.boot.test.context.SpringBootTest; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | 17 | import br.com.safeguard.check.SafeguardCheck; 18 | import br.com.safeguard.constraint.annotations.Verify; 19 | import br.com.safeguard.interfaces.Check; 20 | import br.com.safeguard.types.ParametroTipo; 21 | 22 | @RunWith(SpringRunner.class) 23 | @SpringBootTest 24 | public class TesteDeObjetosAnotados { 25 | 26 | @Test 27 | public void loads() { 28 | 29 | Pessoa pessoa = new Pessoa(); 30 | pessoa.setNome("João da Silva"); 31 | pessoa.setCpf("12345678901"); 32 | pessoa.setTelefone("(11)3266-4455"); 33 | pessoa.setEndereco("Rua A, 123, Bananal, Guarulhos - SP"); 34 | 35 | Check check = new SafeguardCheck(); 36 | 37 | /*Validação manual usando a interface Check*/ 38 | Check resultados = check.elementOf(pessoa).validate(); 39 | int quantidadeDeElementosInvalidos = resultados.getInvalidElements().size(); 40 | boolean temErro = resultados.hasError(); 41 | 42 | /*Validação pelo provedor de validação, usando javax.validation*/ 43 | ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 44 | javax.validation.Validator validator = factory.getValidator(); 45 | Set> violacoes = validator.validate(pessoa, Default.class); 46 | 47 | Assert.assertEquals(1, quantidadeDeElementosInvalidos); 48 | Assert.assertEquals(true, temErro); 49 | Assert.assertEquals(1, violacoes.size()); 50 | 51 | } 52 | 53 | } 54 | 55 | class Pessoa implements Serializable{ 56 | 57 | private static final long serialVersionUID = 1L; 58 | 59 | @Verify(ParametroTipo.TEXTO_SEM_CARACTERES_ESPECIAIS) 60 | private String nome; 61 | 62 | @Verify(value = ParametroTipo.CPF) 63 | private String cpf; 64 | 65 | @Verify(ParametroTipo.TELEFONE_FORMATADO_BRASIL) 66 | private String telefone; 67 | 68 | @Verify(ParametroTipo.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO_HIFEM_UNDERLINE) 69 | private String endereco; 70 | 71 | public String getNome() { 72 | return nome; 73 | } 74 | public void setNome(String nome) { 75 | this.nome = nome; 76 | } 77 | public String getCpf() { 78 | return cpf; 79 | } 80 | public void setCpf(String cpf) { 81 | this.cpf = cpf; 82 | } 83 | public String getTelefone() { 84 | return telefone; 85 | } 86 | public void setTelefone(String telefone) { 87 | this.telefone = telefone; 88 | } 89 | public String getEndereco() { 90 | return endereco; 91 | } 92 | public void setEndereco(String endereco) { 93 | this.endereco = endereco; 94 | } 95 | 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/com/gilmarcarlos/developer/safeguard/TesteDeParametros.java: -------------------------------------------------------------------------------- 1 | package com.gilmarcarlos.developer.safeguard; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | import br.com.safeguard.check.SafeguardCheck; 10 | import br.com.safeguard.interfaces.Check; 11 | import br.com.safeguard.types.ParametroTipo; 12 | 13 | @RunWith(SpringRunner.class) 14 | @SpringBootTest 15 | public class TesteDeParametros { 16 | 17 | @Test 18 | public void loads() { 19 | 20 | Check check = new SafeguardCheck(); 21 | 22 | String textoPadraoSemCaracteresEspeciais = "Você pode digita apenas letras ou números"; 23 | String apenasTexto = "Apenas texto sem caracteres especiais ou números"; 24 | String apenasNumeros = "1234567890"; 25 | String textoEnumero = "texto com números 1234567890"; 26 | String textoEnumeroComPontuacao = "texto com números 1234567890 ?!.:;"; 27 | 28 | /*Testando varios parametros*/ 29 | boolean temErro1 = check.elementOf(textoPadraoSemCaracteresEspeciais, ParametroTipo.DEFAULT_SEM_CARACTERES_ESPECIAIS) 30 | .elementOf(apenasTexto, ParametroTipo.TEXTO_SEM_CARACTERES_ESPECIAIS) 31 | .elementOf(apenasNumeros, ParametroTipo.NUMERO) 32 | .elementOf(textoEnumero, ParametroTipo.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS) 33 | .elementOf(textoEnumeroComPontuacao, ParametroTipo.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS_COM_PONTUACAO) 34 | .validate() 35 | .hasError(); 36 | 37 | /* 38 | * Testando o mesmo paramentro 39 | * 40 | * O mesmo parametro pode ser testado com algumas opções do tipo Default, seguindo uma determinada ordem. 41 | * 42 | * Obs.: Apenas opções do tipo Default são validas para testar o mesmo parametro, o uso de outras opções 43 | * podem gerar erros de teste por negação de opções 44 | * 45 | */ 46 | 47 | 48 | /*As duas validações abaixo são equivaletnes a usar o tipo (ParametroTipo.TEXTO_NUMERO_SEM_CARACTERES_ESPECIAIS)*/ 49 | apenasTexto = "Apenas texto sem caracteres especiais ou números"; 50 | boolean temErro2 = check 51 | .elementOf(apenasTexto, ParametroTipo.DEFAULT_SEM_NUMEROS) 52 | .elementOf(apenasTexto, ParametroTipo.DEFAULT_SEM_CARACTERES_ESPECIAIS) 53 | .validate() 54 | .hasError(); 55 | 56 | 57 | apenasTexto = "Apenas texto, uso de caracteres especiais ou números não é permitido ex: <,90?!{"; 58 | boolean temErro3 = check 59 | .elementOf(apenasTexto, ParametroTipo.DEFAULT_SEM_NUMEROS) 60 | .elementOf(apenasTexto, ParametroTipo.DEFAULT_SEM_CARACTERES_ESPECIAIS) 61 | .validate() 62 | .hasError(); 63 | 64 | 65 | 66 | Assert.assertEquals(false, temErro1); 67 | Assert.assertEquals(false, temErro2); 68 | Assert.assertEquals(true, temErro3); 69 | 70 | } 71 | 72 | 73 | } --------------------------------------------------------------------------------