diff --git a/jrimum-utilix/.gitignore b/jrimum-utilix/.gitignore new file mode 100644 index 0000000..b52163d --- /dev/null +++ b/jrimum-utilix/.gitignore @@ -0,0 +1,6 @@ +/bin +/target +.classpath +.DS_Store +.project +.settings diff --git a/jrimum-utilix/CHANGELOG.md b/jrimum-utilix/CHANGELOG.md new file mode 100644 index 0000000..255285e --- /dev/null +++ b/jrimum-utilix/CHANGELOG.md @@ -0,0 +1,9 @@ +Utilix Changelog +============================= + +0.2.3 (2014/02/01) suport bopepo-0.2.3 +--------------------------------------- + +**Improvement** + + * #2: Remover classes relacionadas a LineOfFields \ No newline at end of file diff --git a/jrimum-utilix/LICENSE b/jrimum-utilix/LICENSE new file mode 100644 index 0000000..37ec93a --- /dev/null +++ b/jrimum-utilix/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/jrimum-utilix/README.md b/jrimum-utilix/README.md new file mode 100644 index 0000000..33f040e --- /dev/null +++ b/jrimum-utilix/README.md @@ -0,0 +1,6 @@ +Utilix +====== + +Utilitários usados no projeto [Lançado embutido, incubado] + +[![Build Status](https://ci-jrimum.rhcloud.com/buildStatus/icon?job=Utilix)](https://ci-jrimum.rhcloud.com) diff --git a/jrimum-utilix/pom.xml b/jrimum-utilix/pom.xml new file mode 100644 index 0000000..371ca0f --- /dev/null +++ b/jrimum-utilix/pom.xml @@ -0,0 +1,193 @@ + + + 4.0.0 + br.com.rjconsultores + jrimum-utilix + jar + Projeto Utilix + 1.0.0 + Projeto open source de componentes de software para o domínio de negócios do Brasil. + http://www.jrimum.org/utilix + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + Projeto JRimum + http://www.jrimum.org + + + + GitHub + https://github.com/jrimum/utilix/issues + + + + http://github.com/jrimum/utilix + + + + + Gilmar P. S. L. + gilmatryx@gmail.com + + + Misael Barreto + misaelbarreto@gmail.com + + + Rômulo Augusto + romulomail@gmail.com + + + + + UTF-8 + UTF-8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.5 + 1.5 + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.6 + + + org.codehaus.mojo.signature + java15 + 1.0 + + + + + animal-sniffer + compile + + check + + + + + + maven-assembly-plugin + 2.4 + + + org.apache.maven.plugins + maven-surefire-plugin + 2.16 + + false + + org/jrimum/utilix/**/* + + + org/jrimum/utilix/excludes/**/* + org/jrimum/utilix/**/*$* + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + package + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadoc + package + + jar + + + + + UTF-8 + UTF-8 + true + private + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.1 + + + + + + + commons-lang + commons-lang + 2.4 + + + + log4j + log4j + 1.2.15 + + + mail + javax.mail + + + jms + javax.jms + + + jmxtools + com.sun.jdmk + + + jmxri + com.sun.jmx + + + + + + junit + junit + 4.11 + test + + + + + + rj-releases + http://52.5.53.15:8081/nexus/content/repositories/releases/ + + + diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/Arrays.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/Arrays.java new file mode 100644 index 0000000..0ca4575 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/Arrays.java @@ -0,0 +1,412 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 21:30:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 21:30:00 + * + */ + +package org.jrimum.utilix; + +/** + *

+ * Classe utilitária para validações de arrays em geral. + *

+ * + *

+ * Inicialmente fornece métodos booleanos para verificação da existência de elementos. + *

+ * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public final class Arrays { + + /** + * Utility class pattern: classe não instanciável + * + * @throws IllegalStateException + * Caso haja alguma tentativa de utilização deste construtor. + */ + private Arrays() { + + Exceptions.throwIllegalStateException("Instanciação não permitida!"); + } + + /** + *

+ * Indica se um dado array de chars tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(char[] a){ + + return (a != null && a.length > 0); + } + + /** + *

+ * Indica se um dado array de booleans tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a + * - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(boolean[] a){ + + return (a != null && a.length > 0); + } + + /** + *

+ * Indica se um dado array de bytes tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(byte[] a){ + + return (a != null && a.length > 0); + } + + /** + *

+ * Indica se um dado array de shorts tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(short[] a){ + + return (a != null && a.length > 0); + } + + /** + *

+ * Indica se um dado array de ints tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(int[] a){ + + return (a != null && a.length > 0); + } + + /** + *

+ * Indica se um dado array de longs tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(long[] a){ + + return (a != null && a.length > 0); + } + + /** + *

+ * Indica se um dado array de floats tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(float[] a){ + + return (a != null && a.length > 0); + } + + /** + *

+ * Indica se um dado array de doubles tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(double[] a){ + + return (a != null && a.length > 0); + } + + /** + *

+ * Indica se um dado array de objetos tem elementos sem gerar NPE. + *

+ *

+ * Resposta direta para o seguinte código: + * (a != null && a > 0). + *

+ * + * @param a - O array a ser testado. + * + * @return (a != null && a > 0) + * + * @since 0.2 + */ + public static boolean hasElement(Object[] a) { + + return (a != null && a.length > 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(char[] a){ + + return (a != null ? a.length : 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(boolean[] a){ + + return (a != null ? a.length : 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(byte[] a){ + + return (a != null ? a.length : 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(short[] a){ + + return (a != null ? a.length : 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(int[] a){ + + return (a != null ? a.length : 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(long[] a){ + + return (a != null ? a.length : 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(float[] a){ + + return (a != null ? a.length : 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(double[] a){ + + return (a != null ? a.length : 0); + } + + /** + *

+ * Retorna a quantidade de elementos de um dado array sem gerar NPE. + *

+ *

+ * Resposta direata para o seguinte código: + * (a != null ? a.length : 0). + *

+ * + * @param a + * - Array com ou sem elementos. + * + * @return (a != null ? a.length : 0) + */ + public static int length(Object[] a){ + + return (a != null ? a.length : 0); + } + +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/ClassLoaders.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/ClassLoaders.java new file mode 100644 index 0000000..43fbc04 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/ClassLoaders.java @@ -0,0 +1,175 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 27/10/2010 - 01:40:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 27/10/2010 - 01:40:00 + * + */ + +package org.jrimum.utilix; + +import static java.lang.String.format; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +/** + * Utilitário para carregamento de recursos da apliacação por meio do classpath. + * + * + * @author Gilmar P.S.L. + */ +public final class ClassLoaders { + + /** + * Utility class pattern: classe não instanciável + * + * @throws IllegalStateException + * Caso haja alguma tentativa de utilização deste construtor. + */ + private ClassLoaders() { + + Exceptions.throwIllegalStateException("Instanciação não permitida!"); + } + + /** + * Carrega um recurso existente no classpath. + * + * @param resourceName + * - O nome do resource a ser carregado + * @return URL para o recurso (resource). + */ + public static URL getResource(String resourceName) { + + return getResource(resourceName, null); + } + + /** + * Carrega um recurso existente no classpath com ou sem uma classe + * informada. + * + *

+ * Informando a classe há necessidade de informar o caminho do pacote, caso + * o recurso esteja nele. + *

+ * + * @param resourceName + * - O nome do resource a ser carregado + * @param callingClass + * - A classe do objeto chamador ou outro. + * @return URL para o recurso (resource). + */ + public static URL getResource(String resourceName, Class callingClass) { + + URL url = null; + + if (callingClass != null) { + + url = callingClass.getResource(resourceName); + + if (url == null) { + + url = callingClass.getClassLoader().getResource(resourceName); + + }else{ + + return url; + } + + if (url == null) { + + String inPagckage = format("%s/%s", callingClass.getPackage().getName().replaceAll("\\.", "/"), resourceName); + + url = Thread.currentThread().getContextClassLoader().getResource(inPagckage); + + } else { + + return url; + } + } + + if (url == null) { + + url = ClassLoaders.class.getResource(resourceName); + + }else{ + + return url; + } + + if (url == null) { + + url = ClassLoaders.class.getClassLoader().getResource(resourceName); + + }else{ + + return url; + } + + if (url == null) { + + url = Thread.currentThread().getContextClassLoader().getResource( + resourceName); + } + + return url; + } + + /** + * Carrega um recurso existente no classpath sob a forma de stream. + * + * @param resourceName + * - O nome do resource a ser carregado + * @return Stream aberto para o recurso (resource). + */ + public static InputStream getResourceAsStream(String resourceName) { + + return getResourceAsStream(resourceName, null); + } + + /** + * Carrega um recurso existente no classpath sob a forma de stream com ou + * sem uma classe informada. + * + * @param resourceName + * - O nome do resource a ser carregado + * @param callingClass + * - A classe do objeto chamador ou outro. + * @return Stream aberto para o recurso (resource). + */ + public static InputStream getResourceAsStream(String resourceName, + Class callingClass) { + + try { + + return getResource(resourceName, callingClass).openStream(); + + } catch (IOException e) { + + return Exceptions.throwIllegalStateException(e); + } + } + +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/Collections.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/Collections.java new file mode 100644 index 0000000..4aee3ec --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/Collections.java @@ -0,0 +1,512 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 21:30:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 21:30:00 + * + */ + +package org.jrimum.utilix; + +import java.util.Collection; +import java.util.Map; + +/** + * Classe utilitária para validações de coleções em geral, com e sem exceções. + * + *

+ * Fornece métodos booleanos e métodos que verificam se uma coleção está de + * acordo com o desejado e, caso não estejam, lançam exceção. + *

+ * + * @author Gilmar P.S.L. + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public final class Collections { + + /** + * Utility class pattern: classe não instanciável + * + * @throws IllegalStateException + * Caso haja alguma tentativa de utilização deste construtor. + */ + private Collections() { + + Exceptions.throwIllegalStateException("Instanciação não permitida!"); + } + + /** + * Verifica se a Collection passada por parâmetro é + * null ou não possui elementos e lança + * exceção caso não preencha estes requisitos. + * + * @param collection + * - Instância de Collection analisada. + * + * @throws IllegalArgumentException - Caso a coleção não + * seja null e possua elementos. + * + * @see #checkEmpty(Collection, String) + * @see #isEmpty(Collection) + * @see #isNotEmpty(Collection) + * + * @since 0.2 + */ + public static void checkEmpty(Collection collection) { + + checkEmpty(collection, "Collection não nulo e com elementos! Valor [" + + collection + "]."); + } + + /** + * Verifica se a Collection passado por parâmetro é + * null ou não possui elementos e lança + * exceção, com a mensagem informada, caso não preencha estes requisitos. + * + * @param collection + * - Instância de Collection analisada. + * @param message + * - Mensagem utilizada na exceção. + * + * @throws IllegalArgumentException - Caso a coleção não + * seja null e possua elementos. + * + * @see #isEmpty(Collection) + * @see #isNotEmpty(Collection) + * + * @since 0.2 + */ + public static void checkEmpty(Collection collection, String message) { + + if (hasElement(collection)) { + + Exceptions.throwIllegalArgumentException(message); + } + } + + /** + * Verifica se a Collection passada por parâmetro + * não é null e possui elementos e lança + * exceção caso não preencha estes requisitos. + * + * @param collection + * - Instância de Collection analisada. + * + * @throws IllegalArgumentException + * - Caso a coleção seja null ou a coleção + * não possua elementos. + * + * @see #checkNotEmpty(Collection, String) + * @see #isEmpty(Collection) + * @see #isNotEmpty(Collection) + * + * @since 0.2 + */ + public static void checkNotEmpty(Collection collection) { + + checkNotEmpty(collection, "Objeto nulo!", "Collection sem elementos!"); + } + + /** + * Verifica se a Collection passada por parâmetro + * não é null e possui elementos e lança + * exceção, com a mensagem informada, caso não preencha estes requisitos. + * + * @param collection + * - Instância de Collection analisada. + * @param message + * - Mensagem utiliada na exceção. + * + * @throws IllegalArgumentException + * - Caso a coleção seja null ou a coleção + * não possua elementos. + * + * @see #isEmpty(Collection) + * @see #isNotEmpty(Collection) + * + * @since 0.2 + */ + public static void checkNotEmpty(Collection collection, String message) { + + checkNotEmpty(collection, message, message); + } + + /** + * Verifica se o Map passado por parâmetro é null + * ou não possui elementos e lança exceção caso não + * preencha estes requisitos. + * + * @param map + * - Instância de Map analisada. + * + * @throws IllegalArgumentException - Caso o mapa não seja + * null e possua elementos. + * + * @see #checkEmpty(Map, String) + * @see #isEmpty(Map) + * @see #isNotEmpty(Map) + * + * @since 0.2 + */ + public static void checkEmpty(Map map) { + + checkEmpty(map, "Map não nulo e com elementos. Valor [" + map + "]"); + } + + /** + * Verifica se o Map passado por parâmetro é null + * ou não possui elementos e lança exceção, com a mensagem + * informada, caso não preencha estes requisitos. + * + * @param map + * - Instância de Map analisada. + * @param message + * - Mensagem utilizada na exceção. + * + * @throws IllegalArgumentException - Caso o mapa não seja + * null e possua elementos. + * + * @see #isEmpty(Map) + * @see #isNotEmpty(Map) + * + * @since 0.2 + */ + public static void checkEmpty(Map map, String message) { + + if (hasElement(map)) { + + Exceptions.throwIllegalArgumentException(message); + } + } + + /** + * Verifica se o Map passado por parâmetro não + * é null e possui elementos e lança exceção caso não preencha + * estes requisitos. + * + * @param map + * - Instância de Map analisada. + * + * @throws IllegalArgumentException + * - Caso o mapa seja null ou o mapa + * não possua elementos. + * + * @see #checkNotEmpty(Map, String) + * @see #isEmpty(Map) + * @see #isNotEmpty(Map) + * + * @since 0.2 + */ + public static void checkNotEmpty(Map map) { + + checkNotEmpty(map, "Objeto nulo", "Map sem elementos"); + } + + /** + * Verifica se o Map passado por parâmetro não + * é null e possui elementos e lança exceção, com a mensagem + * informada, caso não preencha estes requisitos. + * + * @param map + * - Instância de Map analisada. + * @param message + * - Mensagem utiliada na exceção. + * + * @throws IllegalArgumentException + * - Caso o mapa seja null ou o mapa + * não possua elementos. + * + * @see #isEmpty(Map) + * @see #isNotEmpty(Map) + * + * @since 0.2 + */ + public static void checkNotEmpty(Map map, String message) { + + checkNotEmpty(map, message, message); + } + + /** + * Verifica se a Collection passada por parâmetro é + * null ou não possui elementos. + * + * @param collection + * - Instância de Collection analisada. + * @return !hasElement(collection) + * + * @since 0.2 + */ + public static boolean isEmpty(Collection collection) { + + return !hasElement(collection); + } + + /** + * Verifica se a Collection passada por parâmetro + * não é null e possui elementos. + * + * @param collection + * - Instância de Collection analisada. + * @return hasElement(collection) + * + * @see #isEmpty(Collection) + * + * @since 0.2 + */ + public static boolean isNotEmpty(Collection collection) { + + return hasElement(collection); + } + + /** + * Verifica se o Map passado por parâmetro é null + * ou não possui elementos. + * + * @param map + * - Instância de Map analisada. + * @return !hasElement(map) + * + * @since 0.2 + */ + public static boolean isEmpty(Map map) { + + return !hasElement(map); + } + + /** + * Verifica se o Map passado por parâmetro não + * é null e possui elementos. + * + * @param map + * - Instância de Map analisada. + * @return hasElement(map) + * + * @see #isEmpty(Map) + * + * @since 0.2 + */ + public static boolean isNotEmpty(Map map) { + + return hasElement(map); + } + + /** + * Indica se pelo menos uma coleção tem algum elemento sem gerar NPE. + * + * @param cols + * - Coleções para teste. + * + * @return indicativo + */ + public static boolean hasElement(Collection ... cols) { + + if(Arrays.hasElement(cols)){ + + for(Collection c : cols){ + if(hasElement(c)){ + return true; + } + } + } + + return false; + } + + /** + * Indica se pelo menos um mapa tem algum elemento sem gerar NPE. + * + * @param maps + * - Mapas para teste. + * + * @return indicativo + */ + public static boolean hasElement(Map ... maps) { + + if(Arrays.hasElement(maps)){ + + for(Map m : maps){ + if(hasElement(m)){ + return true; + } + } + } + + return false; + } + + /** + * Indica se uma dada coleção tem elementos sem gerar NPE. + *

+ * Resposta direta para o seguinte código: + * (c != null && !c.isEmpty()). + *

+ * + * @param c + * - A coleção a ser testada. + * + * @return (c != null && !c.isEmpty()) + * + * @since 0.2 + */ + public static boolean hasElement(Collection c) { + + return (c != null && !c.isEmpty()); + } + + /** + * Indica se um dado mapa tem elementos sem gerar NPE. + *

+ * Resposta direata para o seguinte código: + * (m != null && !m.isEmpty()). + *

+ * + * @param m + * - O mapa a ser testado. + * + * @return (m != null && !m.isEmpty()) + * + * @since 0.2 + */ + public static boolean hasElement(Map m) { + + return (m != null && !m.isEmpty()); + } + + /** + * Retorna a quantidade de elementos de uma dada coleção sem gerar NPE. + *

+ * Resposta direata para o seguinte código: + * (c != null ? c.size() : 0). + *

+ * + * @param c + * - Coleção com ou sem elementos. + * + * @return (c != null ? c.size() : 0) + */ + public static int size(Collection c) { + + return (c != null ? c.size() : 0); + } + + /** + * Retorna a quantidade de elementos de um dado mapa sem gerar NPE. + *

+ * Resposta direata para o seguinte código: + * (m != null ? m.size() : 0). + *

+ * + * @param m + * - Mapa com ou sem elementos. + * + * @return (m != null ? m.size() : 0) + */ + public static int size(Map m) { + + return (m != null ? m.size() : 0); + } + + /** + * Verifica se o coleção passado por parâmetro não é + * null ou se é vazio. + *

+ * Caso o objeto seja null, lança + * NullPointerException com a mensagem informada no parâmetro + * messageNullPointer (primeiro parâmetro String). Caso o + * objeto não seja null e não possua elementos, lança + * IllegalArgumentException com a mensagem informada no + * parâmetro messageIllegalArgument (segundo parâmetro String). + *

+ * + * @param collection + * - Objeto analisado. + * @param messageNullPointer + * - Mensagem utiliada na exceção + * IllegalArgumentException. + * @param messageIllegalArgument + * - Mensagem utiliada na exceção + * IllegalArgumentException. + * + * @throws IllegalArgumentException + * + * @since 0.2 + */ + public static void checkNotEmpty(Collection collection, + String messageNullPointer, String messageIllegalArgument) { + + if (collection == null) { + + Exceptions.throwIllegalArgumentException(messageNullPointer); + } + + if (collection.isEmpty()) { + + Exceptions.throwIllegalArgumentException(messageIllegalArgument); + } + } + + /** + * Verifica se o mapa passado por parâmetro não é + * null ou se é vazio. + *

+ * Caso o objeto seja null, lança + * NullPointerException com a mensagem informada no parâmetro + * messageNullPointer (primeiro parâmetro String). Caso o + * objeto não seja null e não possua elementos, lança + * IllegalArgumentException com a mensagem informada no + * parâmetro messageIllegalArgument (segundo parâmetro String). + *

+ * + * @param map + * - Objeto analisado. + * @param messageNullPointer + * - Mensagem utiliada na exceção + * IllegalArgumentException. + * @param messageIllegalArgument + * - Mensagem utiliada na exceção + * IllegalArgumentException. + * + * @throws IllegalArgumentException + * + * @since 0.2 + */ + public static void checkNotEmpty(Map map, String messageNullPointer, + String messageIllegalArgument) { + + if (map == null) { + + Exceptions.throwIllegalArgumentException(messageNullPointer); + } + + if (map.isEmpty()) { + + Exceptions.throwIllegalArgumentException(messageIllegalArgument); + } + } + +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/Dates.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/Dates.java new file mode 100644 index 0000000..412a3d7 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/Dates.java @@ -0,0 +1,253 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:17:40 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:17:40 + * + */ + +package org.jrimum.utilix; + +import static org.jrimum.utilix.Objects.isNotNull; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +import org.apache.commons.lang.time.DateUtils; + +/** + *

+ * Serviços utilitários relacionados a manipulação de Objetos + * Date, Calendar, GregorianCalendar. + *

+ * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ +public final class Dates { + + /** + *

+ * Representa uma data inexistente, pode ser usada em casos que não se pode + * usar null [ é obtida da seguinte forma: + * Calendar.set(1, 0, 1) ] + *

+ */ + private static final Date DATE_NULL; + + static { + + Calendar calendar = Calendar.getInstance(); + calendar.set(1, 0, 1); + calendar.setLenient(false); + DATE_NULL = DateUtils.truncate(calendar.getTime(), Calendar.YEAR); + } + + /** + * Utility class pattern: classe não instanciável + * + * @throws IllegalStateException + * Caso haja alguma tentativa de utilização deste construtor. + */ + private Dates() { + + Exceptions.throwIllegalStateException("Instanciação não permitida!"); + } + + /** + *

+ * Retorna uma data inexistente, pode ser usada em casos que não se pode + * usar null [ é obtida da seguinte forma: + * Calendar.set(1, 0, 1) ] + *

+ * + * @return data invalida - 01/01/0001 + */ + public static Date invalidDate(){ + + return (Date) DATE_NULL.clone(); + } + + /** + *

+ * Compara uma dada data qualquer com a data invalida 01/01/0001. + *

+ * + * @param date - Data qualquer + * + * @return igualdade - Se igual a data inválida + */ + public static boolean equalsInvalidDate(Date date){ + + if(date == null){ + + return false; + + }else{ + + return (DATE_NULL.compareTo(date) == 0); + } + } + + /** + *

+ * Calcula a diferença de dias entre duas datas. O resultado é modular, ou + * seja, maior ou igual a zero, logo a data final não precisa ser + * necessariamente maior que a data inicial. + *

+ * + * @param dataInicial + * - data inicial do intervalo. + * @param dataFinal + * - data final do intervalo. + * @return número(módulo) de dias entre as datas. + * + * @throws IllegalArgumentException + * Caso pelo menos uma das duas datas seja null. + * @since 0.2 + */ + public static long calculeDiferencaEmDias(final Date dataInicial, final Date dataFinal) { + + long fator = 0; + + Date dataInicialTruncada, dataFinalTruncada; + + if (isNotNull(dataInicial) && isNotNull(dataFinal)) { + + dataInicialTruncada = DateUtils.truncate(dataInicial, Calendar.DATE); + dataFinalTruncada = DateUtils.truncate(dataFinal, Calendar.DATE); + + fator = ((dataFinalTruncada.getTime() - dataInicialTruncada.getTime()) / DateUtils.MILLIS_PER_DAY); + + if (fator < 0) { + fator *= -1; + } + + } else { + + Exceptions.throwIllegalArgumentException("A data inicial [" + dataInicial + + "] e a data final [" + dataFinal + "] " + + "não podem ter valor 'null'."); + } + + return fator; + } + + /** + *

+ * Converte um objeto String em um objeto + * java.util.Date a partir do formato de data especificado. + *

+ *

+ * Utiliza a sobrecarca + * parse(String dateAsString, String dateFormat) para + * realizar a conversão. + *

+ * + * @param dateAsString + * - um valor de data em forma de String. + * @param dateFormat + * - formato de data em forma de String. + * @return Objeto java.util.Date convertido a partir do objeto + * String + * + * @throws IllegalArgumentException + * caso o objeto String não seja um valor válido de + * data suportado pelo formato. + * @since 0.2 + */ + public static Date parse(String dateAsString, String dateFormat) { + + if (dateFormat == null) { + throw new NullPointerException("O formato da data não pode ter valor [null]."); + } + + return parse(dateAsString, new SimpleDateFormat(dateFormat)); + } + + /** + *

+ * Converte um objeto String em um objeto + * java.util.Date através do objeto + * java.text.DateFormat especificado. + *

+ * + * @param dateAsString + * - um valor de data em forma de String. + * @param dateFormat + * - formatador para objetos java.util.Date. + * @return Objeto java.util.Date convertido a partir do objeto + * String + * + * @throws IllegalArgumentException + * caso o objeto String não seja um valor válido de + * data suportado pelo formatador. + * @since 0.2 + */ + public static Date parse(String dateAsString, DateFormat dateFormat) { + + Date date = null; + + if (dateAsString == null) { + throw new NullPointerException("A String a ser convertida não pode ter valor [null]."); + } + + if (dateFormat == null) { + throw new NullPointerException("O formatador não pode ter valor [null]."); + } + + try { + + date = dateFormat.parse(dateAsString); + + } catch (ParseException e) { + + String msg = "A String [" + dateAsString + + "] deve ser uma data válida no formato"; + if (dateFormat instanceof SimpleDateFormat) { + SimpleDateFormat sdf = (SimpleDateFormat) dateFormat; + msg += " [" + sdf.toPattern() + "]."; + + } else { + msg += " especificado."; + } + + IllegalArgumentException iae = new IllegalArgumentException(msg); + iae.initCause(e); + throw iae; + } + + return date; + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/Exceptions.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/Exceptions.java new file mode 100644 index 0000000..61ebce3 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/Exceptions.java @@ -0,0 +1,251 @@ +/* + * Copyright 2011 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 15/05/2011 - 17:54:00 + * + * ================================================================================ + * + * Direitos autorais 2011 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Created at: 15/05/2011 - 17:54:00 + * + */ + +package org.jrimum.utilix; + +/** + * Classe utilitária para lançar exceções de modo ecapsulado. + * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public class Exceptions { + + /** + * Utility class pattern: classe não instanciável + * + * @throws IllegalStateException + * Caso haja alguma tentativa de utilização deste construtor. + */ + private Exceptions() { + + throwIllegalStateException("Instanciação não permitida!"); + } + + /** + * Lança imediatamente uma {@linkplain IllegalArgumentException}. + * + * @param + * Qualquer tipo. + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwIllegalArgumentException() { + + throw new IllegalArgumentException(); + } + + /** + * Lança imediatamente uma {@linkplain IllegalArgumentException}. + * + * @param + * Qualquer tipo. + * @param message + * Mensagem usada na exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwIllegalArgumentException(String message) { + + throw new IllegalArgumentException(message); + } + + /** + * Lança imediatamente uma {@linkplain IllegalArgumentException}. + * + * @param + * Qualquer tipo. + * @param cause + * Causa da exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwIllegalArgumentException(Throwable cause) { + + throw new IllegalArgumentException(cause); + } + + /** + * Lança imediatamente uma {@linkplain IllegalArgumentException}. + * + * @param + * Qualquer tipo. + * + * @param message + * Mensagem usada na exceção + * @param cause + * Causa da exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwIllegalArgumentException(String message, + Throwable cause) { + + throw new IllegalArgumentException(message, cause); + } + + /** + * Lança imediatamente uma {@linkplain IllegalStateException}. + * + * @param + * Qualquer tipo. + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwIllegalStateException() { + + throw new IllegalStateException(); + } + + /** + * Lança imediatamente uma {@linkplain IllegalStateException}. + * + * @param + * Qualquer tipo. + * @param message + * Mensagem usada na exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwIllegalStateException(String message) { + + throw new IllegalStateException(message); + } + + /** + * Lança imediatamente uma {@linkplain IllegalStateException}. + * + * @param + * Qualquer tipo. + * @param cause + * Causa da exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwIllegalStateException(Throwable cause) { + + throw new IllegalStateException(cause); + } + + /** + * Lança imediatamente uma {@linkplain IllegalStateException}. + * + * @param + * Qualquer tipo. + * + * @param message + * Mensagem usada na exceção + * @param cause + * Causa da exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwIllegalStateException(String message, + Throwable cause) { + + throw new IllegalStateException(message, cause); + } + + /** + * Lança imediatamente uma {@linkplain UnsupportedOperationException}. + * + * @param + * Qualquer tipo. + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwUnsupportedOperationException() { + + throw new UnsupportedOperationException(); + } + + /** + * Lança imediatamente uma {@linkplain UnsupportedOperationException}. + * + * @param + * Qualquer tipo. + * @param message + * Mensagem usada na exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwUnsupportedOperationException(String message) { + + throw new UnsupportedOperationException(message); + } + + /** + * Lança imediatamente uma {@linkplain UnsupportedOperationException}. + * + * @param + * Qualquer tipo. + * @param cause + * Causa da exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwUnsupportedOperationException(Throwable cause) { + + throw new UnsupportedOperationException(cause); + } + + /** + * Lança imediatamente uma {@linkplain UnsupportedOperationException}. + * + * @param + * Qualquer tipo. + * + * @param message + * Mensagem usada na exceção + * @param cause + * Causa da exceção + * + * @return Não retorna nada, criado apenas para satisfazer alguma condição + * de retorno. + */ + public static T throwUnsupportedOperationException(String message, + Throwable cause) { + + throw new UnsupportedOperationException(message, cause); + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/Locales.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/Locales.java new file mode 100644 index 0000000..f70d348 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/Locales.java @@ -0,0 +1,64 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 21:30:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 21:30:00 + * + */ + +package org.jrimum.utilix; + +/** + *

+ * Locales não disponíveis em java.util.Locale. + *

+ * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public final class Locales { + + /** + *

+ * Localização pt-BR. + *

+ */ + public static final java.util.Locale BRASIL = new java.util.Locale("pt", "BR"); + + /** + *

+ * Utility class pattern: classe não instanciável + *

+ * + * @throws IllegalStateException + * Caso haja alguma tentativa de utilização deste construtor. + */ + private Locales() { + + Exceptions.throwIllegalStateException("Instanciação não permitida!"); + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/Objects.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/Objects.java new file mode 100644 index 0000000..01e8002 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/Objects.java @@ -0,0 +1,362 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:02:40 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:02:40 + * + */ + +package org.jrimum.utilix; + +import org.apache.commons.lang.builder.ToStringBuilder; + + +/** + * Classe utilitária para validações de objetos em geral, como verificações de + * objetos nulos, com e sem exceções. + * + *

+ * Fornece métodos booleanos e métodos que verificam se o valor do objeto está + * de acordo com o desejado e, caso não estejam, lançam exceção. + *

+ * + * @author Gilmar P.S.L. + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public final class Objects { + + /** + * Utility class pattern: classe não instanciável + * + * @throws IllegalStateException + * Caso haja alguma tentativa de utilização deste construtor. + */ + private Objects() { + + Exceptions.throwIllegalStateException("Instanciação não permitida!"); + } + + /** + * Verifica se o objeto passado por parâmetro é {@code null}. + * + * @param object + * - Objeto analisado + * + * @return (object == null) + * + * @since 0.2 + */ + public static boolean isNull(Object object) { + + return (object == null); + } + + /** + * Verifica se o objeto passado por parâmetro não é + * {@code null}. + *

+ * É o mesmo que usar o método {@code isNull} da forma + * {@code !isNull(obj)}, porém de forma mais legível. + *

+ * + * @param object + * - Objeto analisado + * + * @return (object != null) + * + * @see #isNull(Object) + * + * @since 0.2 + */ + public static boolean isNotNull(Object object) { + + return (object != null); + } + + /** + * Verifica se existe uma referência ao objeto dado. + * + * @param object + * - Objeto analisado + * + * @return (object != null); + * + * @see #isNotNull(Object) + * + * @since 0.2 + */ + public static boolean exists(Object object) { + + return (object != null); + } + + /** + * Verifica a verdade de uma expressão e lança uma + * {@code IllegalArgumentException}, caso a expressão seja + * false. + * + * @param expression + * - Qualquer expressão booleana + * @throws IllegalArgumentException + * se {@code expression == false} + * + * @since 0.2 + */ + public static void checkArgument(boolean expression) { + + if (!expression) { + Exceptions.throwIllegalArgumentException(); + } + } + + /** + * Verifica a verdade de uma expressão e lança uma + * {@code IllegalArgumentException}, com a mensagem iformada, caso a + * expressão seja false. + * + * @param expression + * - Qualquer expressão booleana + * @param message + * - Mensagem utilizada na exceção + * @throws IllegalArgumentException + * se {@code expression == false} + * + * @since 0.2 + */ + public static void checkArgument(boolean expression, String message) { + + if (!expression) { + Exceptions.throwIllegalArgumentException(message); + } + } + + /** + * Verifica a verdade de uma expressão e lança uma + * {@code IllegalStateException}, caso a expressão seja + * false. + * + * @param expression + * - Qualquer expressão booleana + * @throws IllegalStateException + * se {@code expression == false} + * + * @since 0.2 + */ + public static void checkState(boolean expression) { + + if (!expression) { + Exceptions.throwIllegalStateException(); + } + } + + /** + * Verifica a verdade de uma expressão e lança uma + * {@code IllegalStateException}, com a mensagem iformada, caso a + * expressão seja false. + * + * @param expression + * - Qualquer expressão booleana + * @param message + * - Mensagem utilizada na exceção + * @throws IllegalStateException + * se {@code expression == false} + * + * @since 0.2 + */ + public static void checkState(boolean expression, String message) { + + if (!expression) { + Exceptions.throwIllegalStateException(message); + } + } + + /** + * Verifica se o objeto é nulo e lança {@code IllegalArgumentException} + * , com a mensagem informada, caso não seja. + * + * @throws IllegalArgumentException - Caso o objeto não seja + * {@code null}. + * + * @see #isNull(Object) + * @see #isNotNull(Object) + * + * @since 0.2 + * + * @param object + * - Objeto analisado + * @param message + * - Mensagem utilizada na exceção + */ + public static void checkNull(Object object, String message) { + + if (object != null) { + + Exceptions.throwIllegalArgumentException(message); + } + } + + /** + * Verifica se o objeto é nulo e lança {@code IllegalArgumentException} + * caso não seja. + * + * @param object + * - Objeto analisado + * + * @throws IllegalArgumentException - Caso o objeto não seja + * {@code null}. + * + * @see #checkNull(Object, String) + * @see #isNull(Object) + * @see #isNotNull(Object) + * + * @since 0.2 + */ + public static void checkNull(Object object) { + + checkNull(object, new StringBuilder("Objeto não nulo! Valor [ ") + .append(object).append(" ].").toString()); + } + + /** + * Verifica se o objeto não é nulo e lança + * {@code IllegalArgumentException}, com a mensagem informada, caso + * seja. + * + * @param object + * - Objeto analisado + * @param message + * - Mensagem utilizada na exceção + * + * @throws IllegalArgumentException - Caso o objeto seja {@code null}. + * + * @see #isNull(Object) + * @see #isNotNull(Object) + * + * @since 0.2 + */ + public static void checkNotNull(Object object, String message) { + + if (object == null) { + + Exceptions.throwIllegalArgumentException(message); + } + } + + /** + * Verifica se o objeto não é nulo e lança + * {@code IllegalArgumentException} caso seja. + * + * @param object + * - Objeto analisado + * + * @throws IllegalArgumentException - Caso o objeto seja {@code null}. + * + * @see #checkNotNull(Object, String) + * @see #isNull(Object) + * @see #isNotNull(Object) + * + * @since 0.2 + */ + public static void checkNotNull(Object object) { + + checkNotNull(object, "Objeto nulo!"); + } + + /** + * Retorna um dado valor padrão quando o determinado objeto for nulo. + * + *
+	 * whenNull(null, null)      = null
+	 * whenNull(null, "")        = ""
+	 * whenNull(null, "ex")      = "ex"
+	 * whenNull("abc", *)        = "abc"
+	 * whenNull(Boolean.TRUE, *) = Boolean.TRUE
+	 * 
+ * + * @param + * tipo do objeto pretendido + * @param object + * - O {@code objeto} a testar, pode ser {@code null} + * @param defaultValue + * - O valor padrão retornado, pode ser {@code null} + * @return {@code object} - Se não nulo, caso contrário + * {@code defaultValue} + * + * @since 0.2 + */ + @SuppressWarnings("unchecked") + public static T whenNull(Object object, Object defaultValue) { + + return (T) (object != null ? object : defaultValue); + } + + /** + * Retorna um dado valor padrão quando o determinado objeto for nulo e outro + * valor quando contrário. + * + *
+	 * whenNull(null, null, null)       = null
+	 * whenNull(null, "1", "2")         = "1"
+	 * whenNull("ok", "1", "2")         = "2"
+	 * 
+ * + * @param + * tipo do objeto pretendido + * @param object + * - O {@code objeto} a testar, pode ser {@code null} + * @param defaultValue + * - O valor padrão retornado, pode ser {@code null} + * @param notDefaultValue + * - O valor quando {@code object} é nulo, pode ser + * {@code null} + * @return {@code defaultValue} - Se não nulo, caso contrário + * {@code notDefaultValue} + * + * @since 0.2 + */ + @SuppressWarnings("unchecked") + public static T whenNull(Object object, Object defaultValue, + Object notDefaultValue) { + + return (T) (object == null ? defaultValue : notDefaultValue); + } + + /** + * Exibe os valores de instância para um objeto JRimum. + * + * @see org.apache.commons.lang.builder.ToStringBuilder#reflectionToString + * + * @since 0.2 + * + * @see java.lang.Object#toString() + */ + public static String toString(Object obj) { + + return "JRimumObject: " + ToStringBuilder.reflectionToString(obj); + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/package-info.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/package-info.java new file mode 100644 index 0000000..d119745 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/package-info.java @@ -0,0 +1,35 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 15/08/2010 - 15:37:49 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 15/08/2010 - 15:37:49 + * + */ + +/** + * Classes utilitárias ou de propósito comum, que são necessárias ao projeto. + * + * @author Gilmar P.S.L + */ +package org.jrimum.utilix; \ No newline at end of file diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DateFormat.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DateFormat.java new file mode 100644 index 0000000..362b56f --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DateFormat.java @@ -0,0 +1,247 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 17:31:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 17:31:00 + * + */ + +package org.jrimum.utilix.text; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.jrimum.utilix.Exceptions; + +/** + *

+ * Formatadores de data thread-safe. Para uma mesma categoria, os formatadores + * atualmente são diferenciados pelos seus separadores ("formato_separador") + * exemplos: + *

    + *
  • DDMMYY default:ddMMyy
  • + *
  • DDMMYY_B barr:dd/MM/yy
  • + *
  • DDMMYY_H hyphen:dd-MM-yy
  • + *
  • DDMMYY_U underline:dd_MM_yy
  • + *
  • HHMMSS_C colon:"hh:mm:ss"
  • + *
  • etc.
  • + *
+ *

+ * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public enum DateFormat implements Format{ + + /** + *

+ * Formatador de datas no padrão "ddMMyy". + *

+ */ + DDMMYY("ddMMyy"), + + /** + *

+ * Formatador de datas no padrão "dd/MM/yy". + *

+ */ + DDMMYY_B("dd/MM/yy"), + + /** + *

+ * Formatador de datas no padrão "dd-MM-yy". + *

+ */ + DDMMYY_H("dd-MM-yy"), + + /** + *

+ * Formatador de datas no padrão "dd_MM_yy". + *

+ */ + DDMMYY_U("dd_MM_yy"), + + /** + *

+ * Formatador de datas no padrão "ddMMyyyy". + *

+ */ + DDMMYYYY("ddMMyyyy"), + + /** + *

+ * Formatador de datas no padrão "dd/MM/yyyy". + *

+ */ + DDMMYYYY_B("dd/MM/yyyy"), + + /** + *

+ * Formatador de datas no padrão "dd-MM-yyyy". + *

+ */ + DDMMYYYY_H("dd-MM-yyyy"), + + /** + *

+ * Formatador de datas no padrão "dd_MM_yyyy". + *

+ */ + DDMMYYYY_U("dd_MM_yyyy"), + + /** + *

+ * Formatador de datas no padrão "yyMMdd". + *

+ */ + YYMMDD("yyMMdd"), + + /** + *

+ * Formatador de datas no padrão "yy/MM/dd". + *

+ */ + YYMMDD_B("yy/MM/dd"), + + /** + *

+ * Formatador de datas no padrão "yy/MM/dd". + *

+ */ + YYMMDD_H("yy-MM-dd"), + + /** + *

+ * Formatador de datas no padrão "yy_MM_dd". + *

+ */ + YYMMDD_U("yy_MM_dd"), + + /** + *

+ * Formatador de datas no padrão "yyyyMMdd". + *

+ */ + YYYYMMDD("yyyyMMdd"), + + /** + *

+ * Formatador de datas no padrão "yyyy/MM/dd". + *

+ */ + YYYYMMDD_B("yyyy/MM/dd"), + + /** + *

+ * Formatador de datas no padrão "yyyy-MM-dd". + *

+ */ + YYYYMMDD_H("yyyy-MM-dd"), + + /** + *

+ * Formatador de datas no padrão "yyyy_MM_dd". + *

+ */ + YYYYMMDD_U("yyyy_MM_dd"), + + /** + *

+ * Formatador de datas no padrão "hhmmss". + *

+ */ + HHMMSS("hhmmss"), + + /** + *

+ * Formatador de datas no padrão "HHmmss". + *

+ */ + HHMMSS_24("HHmmss"), + + /** + *

+ * Formatador de datas no padrão "hh:mm:ss". + *

+ */ + HHMMSS_C("hh:mm:ss"), + + /** + *

+ * Formatador de datas no padrão "HH:mm:ss". + *

+ */ + HHMMSS_24C("HH:mm:ss"), + ; + + private final ThreadLocalFormat DATE_FORMAT; + + private DateFormat(String format) { + + DATE_FORMAT = new ThreadLocalFormat(format){ + + @Override + protected SimpleDateFormat initialValue() { + + return new SimpleDateFormat(format); + } + + }; + } + + /** + * @see org.jrimum.utilix.text.Format#format(java.lang.Object) + */ + public String format(Date obj) { + + return DATE_FORMAT.get().format(obj); + } + + /** + * @see org.jrimum.utilix.text.Format#parse(java.lang.String) + */ + public Date parse(String text) { + + try { + + return DATE_FORMAT.get().parse(text); + + } catch (ParseException e) { + + return Exceptions.throwIllegalArgumentException("DateFormat Exception!", e); + } + } + + /** + * @see org.jrimum.utilix.text.Format#copy() + */ + public SimpleDateFormat copy(){ + + return (SimpleDateFormat) DATE_FORMAT.get().clone(); + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DecimalFormat.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DecimalFormat.java new file mode 100644 index 0000000..4432546 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DecimalFormat.java @@ -0,0 +1,129 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 21:30:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 21:30:00 + * + */ + +package org.jrimum.utilix.text; + +import java.text.ParseException; + +import org.jrimum.utilix.Exceptions; + +/** + *

+ * Formatadores thread-safe relacionados a moeda e números decimais. + *

+ * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public enum DecimalFormat implements Format{ + + /** + *

+ * Formatador de decimais pt-BR para Float,Double,BigDecimal no padrão + * "#,##0.0". Exemplo: "1.500,9". + *

+ */ + NUMBER_D_BR("#,##0.0", DecimalFormatSymbols.BRASIL.copy()), + + /** + *

+ * Formatador de decimais pt-BR para Float,Double,BigDecimal no padrão + * "#,##0.00". Exemplo: "1.500,99". + *

+ */ + NUMBER_DD_BR("#,##0.00", DecimalFormatSymbols.BRASIL.copy()), + + /** + *

+ * Formatador de decimais Float,Double,BigDecimal no padrão de + * moeda (Real pt-BR): "R$ #,##0.0". Usado para formatar valores + * monetários em real com o prefixo R$, exemplo: R$ 10,0. + *

+ */ + MONEY_D_BR("\u00A4 #,##0.0", DecimalFormatSymbols.BRASIL.copy()), + + /** + *

+ * Formatador de decimais Float,Double,BigDecimal no padrão de + * moeda (Real pt-BR): "R$ #,##0.00". Usado para formatar valores + * monetários em real com o prefixo R$, exemplo: R$ 10,00. + *

+ */ + MONEY_DD_BR("\u00A4 #,##0.00", DecimalFormatSymbols.BRASIL.copy()), + + ; + + private final ThreadLocalLocalizedFormat DECIMAL_FORMAT; + + private DecimalFormat(String format, java.text.DecimalFormatSymbols formatSymbols) { + + DECIMAL_FORMAT = new ThreadLocalLocalizedFormat(format, formatSymbols){ + + @Override + protected java.text.DecimalFormat initialValue() { + + return new java.text.DecimalFormat(format, formatSymbols); + } + }; + } + + /** + * @see org.jrimum.utilix.text.Format#format(java.lang.Object) + */ + public String format(Number obj) { + + return DECIMAL_FORMAT.get().format(obj); + } + + /** + * @see org.jrimum.utilix.text.Format#parse(java.lang.String) + */ + public Number parse(String text) { + + try { + + return DECIMAL_FORMAT.get().parse(text); + + } catch (ParseException e) { + + return Exceptions.throwIllegalArgumentException("DecimalFormat Exception!", e); + } + } + + /** + * @see org.jrimum.utilix.text.Format#copy() + */ + public java.text.DecimalFormat copy(){ + + return (java.text.DecimalFormat) DECIMAL_FORMAT.get().clone(); + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DecimalFormatSymbols.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DecimalFormatSymbols.java new file mode 100644 index 0000000..e7c193c --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/DecimalFormatSymbols.java @@ -0,0 +1,93 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 21:30:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 21:30:00 + * + */ + +package org.jrimum.utilix.text; + +import java.util.Currency; + +import org.jrimum.utilix.Locales; + +/** + *

+ * DecimalFormatSymbols com localização (Processo de localização) inicialmente + * do Brasil. + *

+ * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public enum DecimalFormatSymbols { + + /** + * DecimalFormatSymbols relacionados aos padrões pt-BR. + */ + BRASIL; + + private final ThreadLocal DF_SYMBOLS; + + private DecimalFormatSymbols() { + + DF_SYMBOLS = new ThreadLocal() { + + protected java.text.DecimalFormatSymbols initialValue() { + + java.text.DecimalFormatSymbols dfSymbols = new java.text.DecimalFormatSymbols( + Locales.BRASIL); + + dfSymbols.setZeroDigit('0'); + dfSymbols.setDecimalSeparator(','); + dfSymbols.setMonetaryDecimalSeparator(','); + dfSymbols.setDigit('#'); + dfSymbols.setGroupingSeparator('.'); + dfSymbols.setCurrency(Currency.getInstance(Locales.BRASIL)); + + return dfSymbols; + } + + }; + } + + /** + *

+ * Cópia de símbolos utilizados em BRASIL. + *

+ * + * @return símbolos - Instância de + * java.text.DecimalFormatSymbols estilo pt-BR + * + * @since 0.2 + */ + public java.text.DecimalFormatSymbols copy() { + + return (java.text.DecimalFormatSymbols) DF_SYMBOLS.get().clone(); + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/text/Format.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/Format.java new file mode 100644 index 0000000..6d1fda4 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/Format.java @@ -0,0 +1,76 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 17:31:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 17:31:00 + * + */ + +package org.jrimum.utilix.text; + +/** + *

+ * Interface usada para objetos formatadores utilizados em leitura e escrita de + * textos. + *

+ * + * @author Gilmar P.S.L + * + * @since 0.2 + * + * @version 0.2 + */ +public interface Format { + + /** + *

+ * Formata um dado objeto para uma representação em string. + *

+ * + * @param obj + * - Objeto a ser formatado. + * @return string - String formatada. + */ + String format(T obj); + + /** + *

+ * Transforma uma string formatada em um objeto correspondente. + *

+ * + * @param text + * - Texto a ser analisado e transformado em objeto. + * @return objeto - Resultado da transformação da string. + */ + T parse(String text); + + /** + *

+ * Devolve uma cópia do formatador utilizado pela instância. + *

+ * + * @return formatador - Cópia da instância do formatador. + */ + F copy(); +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/text/Strings.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/Strings.java new file mode 100644 index 0000000..05bc70c --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/Strings.java @@ -0,0 +1,516 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:18:19 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:18:19 + * + */ + +package org.jrimum.utilix.text; + +import static java.lang.String.format; +import static org.apache.commons.lang.StringUtils.EMPTY; +import static org.apache.commons.lang.StringUtils.isBlank; +import static org.apache.commons.lang.StringUtils.isNotBlank; +import static org.apache.commons.lang.StringUtils.isNumeric; +import static org.apache.commons.lang.StringUtils.leftPad; +import static org.apache.commons.lang.StringUtils.removeStart; +import static org.apache.commons.lang.StringUtils.replace; +import static org.apache.commons.lang.StringUtils.replaceChars; +import static org.apache.commons.lang.StringUtils.startsWith; +import static org.jrimum.utilix.Objects.isNotNull; + +import org.apache.commons.lang.StringUtils; +import org.jrimum.utilix.Exceptions; +import org.jrimum.utilix.Objects; + +/** + * Esta classe tem a responsabilidade de prover serviços utilitários + * relacionados a manipulação de Strings + * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ +public final class Strings { + + public static final String WHITE_SPACE = " "; + + /** + * Utility class pattern: classe não instanciável + * + * @throws AssertionError + * caso haja alguma tentativa de utilização deste construtor. + */ + private Strings() { + + Exceptions.throwIllegalStateException("Instanciação não permitida!"); + } + + /** + * Elimina simbolos como: + * + *
>
+	 * <,;.:!*&%+-_<>[]\/
+	 * 
+ * + * @param str + * String com os símbolos a serem removidos. + * @return String sem símbolos. + * @since 0.2 + */ + public static String eliminateSymbols(final String str) { + + String modifiedStr = str; + + if (isNotBlank(modifiedStr)) { + + modifiedStr = replace(modifiedStr, "-", EMPTY); + modifiedStr = replace(modifiedStr, "_", EMPTY); + modifiedStr = replace(modifiedStr, "=", EMPTY); + modifiedStr = replace(modifiedStr, "+", EMPTY); + modifiedStr = replace(modifiedStr, "%", EMPTY); + modifiedStr = replace(modifiedStr, "*", EMPTY); + modifiedStr = replace(modifiedStr, "@", EMPTY); + modifiedStr = replace(modifiedStr, "#", EMPTY); + modifiedStr = replace(modifiedStr, "&", EMPTY); + modifiedStr = replace(modifiedStr, ":", EMPTY); + modifiedStr = replace(modifiedStr, ".", EMPTY); + modifiedStr = replace(modifiedStr, ";", EMPTY); + modifiedStr = replace(modifiedStr, ",", EMPTY); + modifiedStr = replace(modifiedStr, "!", EMPTY); + modifiedStr = replace(modifiedStr, "?", EMPTY); + modifiedStr = replace(modifiedStr, "(", EMPTY); + modifiedStr = replace(modifiedStr, ")", EMPTY); + modifiedStr = replace(modifiedStr, "{", EMPTY); + modifiedStr = replace(modifiedStr, "}", EMPTY); + modifiedStr = replace(modifiedStr, "[", EMPTY); + modifiedStr = replace(modifiedStr, "]", EMPTY); + modifiedStr = replace(modifiedStr, "/", EMPTY); + modifiedStr = replace(modifiedStr, "\\", EMPTY); + modifiedStr = replace(modifiedStr, ">", EMPTY); + modifiedStr = replace(modifiedStr, "<", EMPTY); + modifiedStr = replace(modifiedStr, "\"", EMPTY); + modifiedStr = replace(modifiedStr, "'", EMPTY); + modifiedStr = replace(modifiedStr, "`", EMPTY); + } + + return modifiedStr; + } + + /** + * Remove os zeros iniciais de uma String, seja ela numérica ou + * não. + *

+ * removeStartWithZeros("00000") => 0
+ * removeStartWithZeros("00023") => 23
+ * removeStartWithZeros("02003") => 2003 + *

+ * + * @param str + * @return a string sem zeros inicias ou um único zero. + * + * @since 0.2 + */ + + public static String removeStartWithZeros(final String str) { + + String withoutZeros = EMPTY; + final String zero = "0"; + + if (isNotNull(str)) { + + if (startsWith(str, zero)) { + + withoutZeros = removeStart(str, zero); + + while (startsWith(withoutZeros, zero)) { + withoutZeros = removeStart(withoutZeros, zero); + } + + if (withoutZeros.trim().length() == 0) { + withoutZeros = zero; + } + + } else { + withoutZeros = str; + } + } + + return withoutZeros; + } + + /** + * Remove a acentuação do texto, que inclui os acentos: + *

    + *
  • Agudo. ex.: á
  • + *
  • Grave. ex.: à
  • + *
  • Til. ex.: ã
  • + *
  • Trema. ex.: ä
  • + *
  • Circunflexo. ex.: â
  • + *
+ * e o Cedilha (ç). + *

+ * Os acentos são removidos tanto para letras minúsculas como para letras + * maiúsculas. + *

+ * + * @param value + * String com os caracteres a serem removidos. + * @return String sem acentuação. + * @since 0.2 + */ + public static String eliminateAccent(final String value) { + + String modifiedValue = value; + + // Para ç e Ç + modifiedValue = replaceChars(modifiedValue, '\u00E7', 'c'); + modifiedValue = replaceChars(modifiedValue, '\u00C7', 'C'); + + // Para à, á, â, ã e ä + modifiedValue = replaceChars(modifiedValue, '\u00E0', 'a'); + modifiedValue = replaceChars(modifiedValue, '\u00E1', 'a'); + modifiedValue = replaceChars(modifiedValue, '\u00E2', 'a'); + modifiedValue = replaceChars(modifiedValue, '\u00E3', 'a'); + modifiedValue = replaceChars(modifiedValue, '\u00E4', 'a'); + + // Para è, é, ê e ë + modifiedValue = replaceChars(modifiedValue, '\u00E8', 'e'); + modifiedValue = replaceChars(modifiedValue, '\u00E9', 'e'); + modifiedValue = replaceChars(modifiedValue, '\u00EA', 'e'); + modifiedValue = replaceChars(modifiedValue, '\u00EB', 'e'); + + // Para ì, í, î e ï + modifiedValue = replaceChars(modifiedValue, '\u00EC', 'i'); + modifiedValue = replaceChars(modifiedValue, '\u00ED', 'i'); + modifiedValue = replaceChars(modifiedValue, '\u00EE', 'i'); + modifiedValue = replaceChars(modifiedValue, '\u00EF', 'i'); + + // Para ò, ó, ô, õ e ö + modifiedValue = replaceChars(modifiedValue, '\u00F2', 'o'); + modifiedValue = replaceChars(modifiedValue, '\u00F3', 'o'); + modifiedValue = replaceChars(modifiedValue, '\u00F4', 'o'); + modifiedValue = replaceChars(modifiedValue, '\u00F5', 'o'); + modifiedValue = replaceChars(modifiedValue, '\u00F6', 'o'); + + // Para ù, ú, û e ü + modifiedValue = replaceChars(modifiedValue, '\u00F9', 'u'); + modifiedValue = replaceChars(modifiedValue, '\u00FA', 'u'); + modifiedValue = replaceChars(modifiedValue, '\u00FB', 'u'); + modifiedValue = replaceChars(modifiedValue, '\u00FC', 'u'); + + // Para À, Á, Â, Ã e Ä + modifiedValue = replaceChars(modifiedValue, '\u00C0', 'A'); + modifiedValue = replaceChars(modifiedValue, '\u00C1', 'A'); + modifiedValue = replaceChars(modifiedValue, '\u00C2', 'A'); + modifiedValue = replaceChars(modifiedValue, '\u00C3', 'A'); + modifiedValue = replaceChars(modifiedValue, '\u00C4', 'A'); + + // Para È, É, Ê e Ë + modifiedValue = replaceChars(modifiedValue, '\u00C8', 'E'); + modifiedValue = replaceChars(modifiedValue, '\u00C9', 'E'); + modifiedValue = replaceChars(modifiedValue, '\u00CA', 'E'); + modifiedValue = replaceChars(modifiedValue, '\u00CB', 'E'); + + // Para Ì, Í, Î e Ï + modifiedValue = replaceChars(modifiedValue, '\u00CC', 'I'); + modifiedValue = replaceChars(modifiedValue, '\u00CD', 'I'); + modifiedValue = replaceChars(modifiedValue, '\u00CE', 'I'); + modifiedValue = replaceChars(modifiedValue, '\u00CF', 'I'); + + // Para Ò, Ó, Ô, Õ e Ö + modifiedValue = replaceChars(modifiedValue, '\u00D2', 'O'); + modifiedValue = replaceChars(modifiedValue, '\u00D3', 'O'); + modifiedValue = replaceChars(modifiedValue, '\u00D4', 'O'); + modifiedValue = replaceChars(modifiedValue, '\u00D5', 'O'); + modifiedValue = replaceChars(modifiedValue, '\u00D6', 'O'); + + // Para Ù, Ú, Û e Ü + modifiedValue = replaceChars(modifiedValue, '\u00D9', 'U'); + modifiedValue = replaceChars(modifiedValue, '\u00DA', 'U'); + modifiedValue = replaceChars(modifiedValue, '\u00DB', 'U'); + modifiedValue = replaceChars(modifiedValue, '\u00DC', 'U'); + + return modifiedValue; + } + + /** + * Verifica se a String passada por parâmetro não é + * null e não é numérica, ou seja, se a string não contém + * somente dígitos unicode. + *

+ * Lança exceção, com a mensagem passada por parâmetro (segundo parâmetro + * String), caso não preencha estes requisitos. + *

+ * + * @param value + * - String analisada + * + * @param message + * - Mensagem utiliada na exceção. + * + * @throws IllegalArgumentException - Caso a string seja null ou + * caso a string não seja numérica. + * + * @since 0.2 + */ + public static void checkNotNumeric(String value, String message) { + + checkNotNumeric(value, message, message); + } + + /** + * Verifica se a String passada por parâmetro não é + * null e não é numérica, ou seja, se a string não contém + * somente dígitos unicode. + *

+ * Lança exceção, com a mensagem passada por parâmetro (segundo parâmetro + * String), caso não preencha estes requisitos. + *

+ * + * @param value + * - String analisada + * + * @throws IllegalArgumentException - Caso a string seja null ou + * caso a string não seja numérica. + * + * @since 0.2 + */ + public static void checkNotNumeric(String value) { + + checkNotNumeric(value, "String nula!", format( + "Valor inválido. String [\"%s\"] não numérica!", value)); + } + + /** + * Verifica se a String passada por parâmetro não é + * null, não é vazia (EMPTY) e não possui apenas + * espaços em branco. + *

+ * Lança exceção, com a mensagem passada por parâmetro (segundo parâmetro + * String), caso não preencha estes requisitos. + *

+ * + * @param value + * - String analisada + * + * @param message + * - Mensagem utiliada na exceção. + * + * @throws IllegalArgumentException - Caso a string seja null ou + * caso a string seja vazia. + * + * @since 0.2 + */ + public static void checkNotBlank(String value, String message) { + + checkNotBlank(value, message, message); + } + + /** + * Verifica se a String passada por parâmetro não é + * null, não é vazia (EMPTY) e não possui apenas + * espaços em branco. Lança exceção caso não preencha estes requisitos. + * + * @param value + * - String analisada + * + * @throws IllegalArgumentException - Caso a string seja null ou + * caso a string seja vazia. + * + * @since 0.2 + */ + public static void checkNotBlank(String value) { + + checkNotBlank( + value, + "String nula!", + format( + "Valor inválido. String [\"%s\"] vazia ou contendo somente espaços em branco!", + value)); + } + + /** + * Retorna uma dado valor padrão quando a string informada for considerada + * como blank por {@linkplain StringUtils#isBlank(String)}. + * + *
+	 * whenBlank(null, null)  = null
+	 * whenBlank(null, "")    = ""
+	 * whenBlank("", "")      = ""
+	 * whenBlank("", "a")     = "a"
+	 * whenBlank(" ", "ex")   = "ex"
+	 * whenBlank("abc", *)    = "abc"
+	 * 
+ * + * @param str + * String a testar e ser usada como valor de retorno se não for + * blank, pode ser null + * @param defaultValue + * - O valor padrão retornado caso a string testada seja blank, + * pode ser null + * @return String - Se não for blank, caso contrário + * defaultValue + * + * @since 0.2 + */ + public static String whenBlank(String str, String defaultValue) { + + return (isNotBlank(str) ? str : defaultValue); + } + + /** + * Método privado para fins de reutilização de código. + *

+ * Verifica se a String passada por parâmetro não é + * null e não é numérica, ou seja, se a string não contém + * somente dígitos unicode. + *

+ *

+ * Lança IllegalArgumentException, com a mensagem definida em + * messageNullPointer (segundo parâmetro String), caso o valor + * passado seja null + *

+ *

+ * Lança IllegalArgumentException, com a mensagem definida em + * messageIllegalArgument (terceiro parâmetro String), caso o + * valor passado não seja numérico. + *

+ * + * @param value + * - String analisada + * + * @param messageNullPointer + * - Mensagem utiliada na exceção. + * + * @param messageIllegalArgument + * - Mensagem utiliada na exceção. + * + * + * @throws IllegalArgumentException - Caso a string seja null ou + * caso a string não seja numérica. + * + * @since 0.2 + */ + private static void checkNotNumeric(String value, + String messageNullPointer, String messageIllegalArgument) { + + Objects.checkNotNull(value, messageNullPointer); + + if (!isNumeric(value)) { + Exceptions.throwIllegalArgumentException(messageIllegalArgument); + } + } + + /** + * Método privado para fins de reutilização de código. + *

+ * Verifica se a String passada por parâmetro não é + * null, não é vazia (StringUtils.EMPTY) e não + * possui apenas espaços em branco. + *

+ *

+ * Lança IllegalArgumentException, com a mensagem definida em + * messageNullPointer (segundo parâmetro String), caso o valor + * passado seja null + *

+ *

+ * Lança IllegalArgumentException, com a mensagem definida em + * messageIllegalArgument (terceiro parâmetro String), caso o + * valor passado seja vazio. + *

+ * + * @param value + * - String analisada + * + * @param messageNullPointer + * - Mensagem utiliada na exceção. + * + * @param messageIllegalArgument + * - Mensagem utiliada na exceção. + * + * @throws IllegalArgumentException - Caso a string seja null ou + * caso a string seja vazia. + * + * @since 0.2 + */ + private static void checkNotBlank(String value, String messageNullPointer, + String messageIllegalArgument) { + + Objects.checkNotNull(value, messageNullPointer); + + if (isBlank(value)) { + Exceptions.throwIllegalArgumentException(messageIllegalArgument); + } + } + + /** + * Retorna uma string de tamanho informado {@code length} com o + * preenchimento de zeros à esquerda para o número informado. + * + * @param numberToFill + * Número a ser transformado em string com zeros à esquerda + * @param length + * Tamanho final da string com zeros à esquerda + * @return string com zeros a esquerda + */ + public static String fillWithZeroLeft(int numberToFill, int length){ + return fillWithZeroLeft(String.valueOf(numberToFill), length); + } + + /** + * Retorna uma string de tamanho informado {@code length} com o + * preenchimento de zeros à esquerda para o número informado. + * + * @param numberToFill + * Número a ser transformado em string com zeros à esquerda + * @param length + * Tamanho final da string com zeros à esquerda + * @return string com zeros a esquerda + */ + public static String fillWithZeroLeft(long numberToFill, int length){ + return fillWithZeroLeft(String.valueOf(numberToFill), length); + } + + /** + * Retorna uma string de tamanho informado {@code length} com o + * preenchimento de zeros à esquerda para a string informada. + * + * @param stringToFill + * String a ser preenchida com zeros à esquerda + * @param length + * Tamanho final da string com zeros à esquerda + * @return string com zeros a esquerda + */ + public static String fillWithZeroLeft(String stringToFill, int length){ + return leftPad(stringToFill, length, "0"); + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/text/ThreadLocalFormat.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/ThreadLocalFormat.java new file mode 100644 index 0000000..2dd81cb --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/ThreadLocalFormat.java @@ -0,0 +1,55 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 17:31:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 17:31:00 + * + */ + +package org.jrimum.utilix.text; + +import org.jrimum.utilix.Objects; + +/** + *

+ * Abstração para o uso de formatadores thread-safe em enumerações. + *

+ * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public abstract class ThreadLocalFormat extends ThreadLocal { + + protected final String format; + + protected ThreadLocalFormat(String format) { + + Objects.checkNotNull(format, "INVALID NULL FORMAT!"); + + this.format = format; + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/text/ThreadLocalLocalizedFormat.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/ThreadLocalLocalizedFormat.java new file mode 100644 index 0000000..4d15932 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/ThreadLocalLocalizedFormat.java @@ -0,0 +1,84 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 01/08/2010 - 21:30:00 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 01/08/2010 - 21:30:00 + * + */ + +package org.jrimum.utilix.text; + +import java.util.Locale; + +import org.jrimum.utilix.Objects; + +/** + *

+ * Abstração para o uso de formatadores thread-safe com o uso de "localização" + * em enumerações. + *

+ * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public abstract class ThreadLocalLocalizedFormat extends ThreadLocalFormat { + + protected final Locale locale; + protected final S formatSymbols; + + protected ThreadLocalLocalizedFormat(String format, Locale locale) { + + super(format); + + Objects.checkNotNull(locale, "INVALID NULL LOCALE!"); + + this.locale = locale; + this.formatSymbols = null; + } + + protected ThreadLocalLocalizedFormat(String format, S formatSymbols) { + + super(format); + + Objects.checkNotNull(formatSymbols, "INVALID NULL FORMAT SYMBOLS!"); + + this.formatSymbols = formatSymbols; + this.locale = null; + } + + protected ThreadLocalLocalizedFormat(String format, Locale locale, + S formatSymbols) { + + super(format); + + Objects.checkNotNull(locale, "INVALID NULL LOCALE!"); + Objects.checkNotNull(formatSymbols, "INVALID NULL FORMAT SYMBOLS!"); + + this.formatSymbols = formatSymbols; + this.locale = locale; + } +} diff --git a/jrimum-utilix/src/main/java/org/jrimum/utilix/text/package-info.java b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/package-info.java new file mode 100644 index 0000000..a19b2f0 --- /dev/null +++ b/jrimum-utilix/src/main/java/org/jrimum/utilix/text/package-info.java @@ -0,0 +1,35 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 15/08/2010 - 15:37:49 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 15/08/2010 - 15:37:49 + * + */ + +/** + * Classes relacionadas a manipulação, extração, composição e formatação de textos. + * + * @author Gilmar P.S.L + */ +package org.jrimum.utilix.text; \ No newline at end of file diff --git a/jrimum-utilix/src/test/java/org/jrimum/utilix/TestCollections.java b/jrimum-utilix/src/test/java/org/jrimum/utilix/TestCollections.java new file mode 100644 index 0000000..6ce3fc0 --- /dev/null +++ b/jrimum-utilix/src/test/java/org/jrimum/utilix/TestCollections.java @@ -0,0 +1,230 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 31/07/2010 - 23:04:41 + */ + +package org.jrimum.utilix; + +import static java.util.Collections.EMPTY_LIST; +import static java.util.Collections.EMPTY_MAP; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +/** + *

+ * Teste unitário para a classe utilitária de coleções. + *

+ * + * @author Gilmar P.S.L. + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public class TestCollections { + + private static final Object EMPTY_OBJECT = new Object(); + + private static final Map NULL_MAP = null; + + private static final Collection NULL_COLLECTION = null; + + private static final Map MAP_COM_ELEMENTO; + + private static final Collection COLLECTION_COM_ELEMENTO; + + static { + + MAP_COM_ELEMENTO = new HashMap(); + MAP_COM_ELEMENTO.put(EMPTY_OBJECT, EMPTY_OBJECT); + + COLLECTION_COM_ELEMENTO = new ArrayList(); + COLLECTION_COM_ELEMENTO.add(EMPTY_OBJECT); + } + + @Test + public void testIsEmptyMap() { + + assertTrue(Collections.isEmpty(NULL_MAP)); + assertTrue(Collections.isEmpty(EMPTY_MAP)); + + assertFalse(Collections.isEmpty(MAP_COM_ELEMENTO)); + } + + @Test + public void testIsNotEmptyMap() { + + assertTrue(Collections.isNotEmpty(MAP_COM_ELEMENTO)); + + assertFalse(Collections.isNotEmpty(NULL_MAP)); + assertFalse(Collections.isNotEmpty(EMPTY_MAP)); + } + + @Test + public void testIsEmptyCollection() { + + assertTrue(Collections.isEmpty(NULL_COLLECTION)); + assertTrue(Collections.isEmpty(EMPTY_LIST)); + + assertFalse(Collections.isEmpty(COLLECTION_COM_ELEMENTO)); + } + + @Test + public void testIsNotEmptyCollection() { + + assertTrue(Collections.isNotEmpty(COLLECTION_COM_ELEMENTO)); + + assertFalse(Collections.isNotEmpty(NULL_COLLECTION)); + assertFalse(Collections.isNotEmpty(EMPTY_LIST)); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckEmptyMap() { + + Collections.checkEmpty(MAP_COM_ELEMENTO); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckEmptyMapComMensagem() { + Collections.checkEmpty(MAP_COM_ELEMENTO, "Argumento não nulo"); + } + + @Test + public void testMensagemCheckEmptyMapComMensagem() { + + try { + + Collections.checkEmpty(MAP_COM_ELEMENTO, "Argumento não nulo"); + Assert.fail("Exceção não disparada"); + + } catch (IllegalArgumentException e) { + assertEquals("Argumento não nulo", e.getMessage()); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotEmptyMapNullPointer() { + Collections.checkNotEmpty(NULL_MAP); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotEmptyMapIllegalArgument() { + Collections.checkNotEmpty(EMPTY_MAP); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotEmptyMapComMensagemNullPointer() { + Collections.checkNotEmpty(NULL_MAP, "Argumento nulo"); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotEmptyMapComMensagemIllegalArgument() { + Collections.checkNotEmpty(EMPTY_MAP, "Map vazio"); + } + + @Test + public void testMensagemCheckNotEmptyMapComMensagem() { + + try { + + Collections.checkNotEmpty(NULL_MAP, "Argumento nulo"); + Assert.fail("Exceção não disparada"); + + } catch (IllegalArgumentException e) { + assertEquals("Argumento nulo", e.getMessage()); + } + + try { + + Collections.checkNotEmpty(EMPTY_MAP, "Map vazio"); + Assert.fail("Exceção não disparada"); + + } catch (IllegalArgumentException e) { + assertEquals("Map vazio", e.getMessage()); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckEmptyCollection() { + Collections.checkEmpty(COLLECTION_COM_ELEMENTO); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckEmptyCollectionComMensagem() { + Collections.checkEmpty(COLLECTION_COM_ELEMENTO, "Argumento não nulo"); + } + + @Test + public void testMensagemCheckEmptyCollectionComMensagem() { + + try { + + Collections.checkEmpty(COLLECTION_COM_ELEMENTO, "Argumento não nulo"); + Assert.fail("Exceção não disparada"); + + } catch (IllegalArgumentException e) { + assertEquals("Argumento não nulo", e.getMessage()); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotEmptyCollectionNullPointer() { + Collections.checkNotEmpty(NULL_COLLECTION); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotEmptyCollectionIllegalArgument() { + Collections.checkNotEmpty(EMPTY_LIST); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotEmptyCollectionComMensagemNullPointer() { + Collections.checkNotEmpty(NULL_COLLECTION, "Argumento nulo"); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotEmptyCollectionComMensagemIllegalArgument() { + Collections.checkNotEmpty(EMPTY_LIST, "Coleção vazia"); + } + + @Test + public void testMensagemCheckNotEmptyCollectionComMensagem() { + + try { + + Collections.checkNotEmpty(NULL_COLLECTION, "Argumento nulo"); + Assert.fail("Exceção não disparada"); + + } catch (IllegalArgumentException e) { + assertEquals("Argumento nulo", e.getMessage()); + } + + try { + + Collections.checkNotEmpty(EMPTY_LIST, "Coleção vazia"); + Assert.fail("Exceção não disparada"); + + } catch (IllegalArgumentException e) { + assertEquals("Coleção vazia", e.getMessage()); + } + } +} diff --git a/jrimum-utilix/src/test/java/org/jrimum/utilix/TestDates.java b/jrimum-utilix/src/test/java/org/jrimum/utilix/TestDates.java new file mode 100644 index 0000000..2dcdcb5 --- /dev/null +++ b/jrimum-utilix/src/test/java/org/jrimum/utilix/TestDates.java @@ -0,0 +1,161 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:15:33 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:15:33 + * + */ + +package org.jrimum.utilix; +import static org.jrimum.utilix.text.DateFormat.DDMMYYYY_B; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Calendar; +import java.util.Date; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + *

+ * Teste unitário para a classe utilitária de coleções. + *

+ * + * @author Gilmar P.S.L. + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public class TestDates { + + private static Date dataInicial; + + private static Date dataFinal; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + Calendar calendar1 = Calendar.getInstance(); + calendar1.set(2007, Calendar.OCTOBER, 16); + dataInicial = calendar1.getTime(); + + Calendar calendar2 = Calendar.getInstance(); + calendar2.set(2007, Calendar.NOVEMBER, 16); + dataFinal = calendar2.getTime(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + + dataInicial = null; + dataFinal = null; + } + + @Test(expected = IllegalArgumentException.class) + public void testCalculeDiferencaEmDiasDatasNull() { + + Dates.calculeDiferencaEmDias(null, null); + } + + @Test(expected = IllegalArgumentException.class) + public void testCalculeDiferencaEmDiasDataInicialNull() { + + Dates.calculeDiferencaEmDias(null, dataFinal); + } + + @Test(expected = IllegalArgumentException.class) + public void testCalculeDiferencaEmDiasDataFinalNull() { + + Dates.calculeDiferencaEmDias(dataInicial, null); + } + + @Test + public void testCalculeDiferencaEmDiasGaranteModulo() { + + assertTrue(Dates.calculeDiferencaEmDias(dataInicial, dataFinal) > 0); + assertTrue(Dates.calculeDiferencaEmDias(dataFinal, dataInicial) > 0); + } + + @Test + public void testCalculeDiferencaEmDias() { + + assertEquals(0, Dates.calculeDiferencaEmDias(dataInicial, + dataInicial)); + assertEquals(0, Dates.calculeDiferencaEmDias(dataFinal, dataFinal)); + assertEquals(31, Dates + .calculeDiferencaEmDias(dataInicial, dataFinal)); + assertEquals(31, Dates + .calculeDiferencaEmDias(dataFinal, dataInicial)); + } + + @Test + public void testParseFormatoDDMMYYYY() { + assertNotNull(DDMMYYYY_B.parse("01/01/2000")); + } + + @Test(expected = NullPointerException.class) + public void testParseFormatoDDMMYYYYNullPointerException() { + assertNotNull(DDMMYYYY_B.parse(null)); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseFormatoDDMMYYYYIllegalArgumentException() { + assertNotNull(DDMMYYYY_B.parse("")); + assertNotNull(DDMMYYYY_B.parse("2000-01-01")); + } + + @Test + public void testParseStringString() { + assertNotNull(Dates.parse("2000-01-01", "yyyy-MM-dd")); + } + + @Test(expected = NullPointerException.class) + public void testParseStringStringDataNull() { + assertNotNull(Dates.parse(null, "yyyy-MM-dd")); + } + + @Test(expected = NullPointerException.class) + public void testParseStringStringFormatoNull() { + String formato = null; + assertNotNull(Dates.parse("2000-01-01", formato)); + } + + @Test(expected = NullPointerException.class) + public void testParseStringStringAmbosNull() { + String formato = null; + assertNotNull(Dates.parse(null, formato)); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseStringStringIllegalArgumentException() { + assertNotNull(Dates.parse("", "yyyy-MM-dd")); + assertNotNull(Dates.parse("01/01/2000", "")); + assertNotNull(Dates.parse("01/01/2000", "yyyy-MM-dd")); + } +} diff --git a/jrimum-utilix/src/test/java/org/jrimum/utilix/TestObjects.java b/jrimum-utilix/src/test/java/org/jrimum/utilix/TestObjects.java new file mode 100644 index 0000000..5eb107f --- /dev/null +++ b/jrimum-utilix/src/test/java/org/jrimum/utilix/TestObjects.java @@ -0,0 +1,133 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 16/02/2010 - 18:40:40 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 16/02/2010 - 18:40:40 + * + */ + +package org.jrimum.utilix; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Assert; +import org.junit.Test; + +/** + *

+ * Teste unitário para a classe utilitária de objetos + *

+ * + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + * + */ +public class TestObjects { + + private static final Object NULL_OBJECT = null; + + private static final Object EMPTY_OBJECT = new Object(); + + @Test + public void testIsNull() { + assertTrue(Objects.isNull(NULL_OBJECT)); + assertFalse(Objects.isNull(EMPTY_OBJECT)); + } + + @Test + public void testIsNotNull() { + assertTrue(Objects.isNotNull(EMPTY_OBJECT)); + assertFalse(Objects.isNotNull(NULL_OBJECT)); + } + + + @Test(expected = IllegalArgumentException.class) + public void testCheckNull() { + Objects.checkNull(EMPTY_OBJECT); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNullComMensagem() { + Objects.checkNull(EMPTY_OBJECT, "Argumento não nulo"); + } + + @Test + public void testMensagemCheckNullComMensagem() { + + try { + + Objects.checkNull(EMPTY_OBJECT, "Argumento não nulo"); + Assert.fail("Exceção não disparada."); + + } catch (IllegalArgumentException e) { + assertEquals("Argumento não nulo", e.getMessage()); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotNull() { + Objects.checkNotNull(NULL_OBJECT); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotNullComMensagem() { + Objects.checkNotNull(NULL_OBJECT, "Argumento nulo"); + } + + @Test + public void testMensagemChecNotkNullComMensagem() { + + try { + + Objects.checkNotNull(null, "Argumento nulo"); + Assert.fail("Exceção não disparada."); + + } catch (IllegalArgumentException e) { + assertEquals("Argumento nulo", e.getMessage()); + } + } + + @Test + public void testWhenNull1(){ + + assertTrue(null == Objects.whenNull(null, null)); + assertEquals("ok", Objects.whenNull(null, "ok")); + assertEquals("ok", Objects.whenNull("ok", "is ok?")); + assertFalse("ok".equals(Objects.whenNull(Boolean.TRUE, "ok"))); + } + + @Test + public void testWhenNull2(){ + + assertTrue(null == Objects.whenNull(null, null,null)); + assertEquals("ok:1", Objects.whenNull(null, "ok:1","ok:2")); + assertEquals("ok:2", Objects.whenNull("ok", "ok:1","ok:2")); + assertFalse("ok".equals(Objects.whenNull(Boolean.TRUE, "ok","nops"))); + } +} diff --git a/jrimum-utilix/src/test/java/org/jrimum/utilix/text/TestStrings.java b/jrimum-utilix/src/test/java/org/jrimum/utilix/text/TestStrings.java new file mode 100644 index 0000000..a408f1a --- /dev/null +++ b/jrimum-utilix/src/test/java/org/jrimum/utilix/text/TestStrings.java @@ -0,0 +1,172 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:15:10 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:15:10 + * + */ + +package org.jrimum.utilix.text; + +import static org.apache.commons.lang.StringUtils.EMPTY; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + *

+ * Teste unitário para a classe utilitária de strings. + *

+ * + * @author Gilmar P.S.L. + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public class TestStrings { + + @Test + public void testEliminateSymbols() { + + assertEquals(EMPTY, Strings.eliminateSymbols("><,;.:!*&%+-_<>[]\\/")); + } + + @Test + public void testEliminateAccent() { + + assertEquals("c", Strings.eliminateAccent("ç")); + assertEquals("C", Strings.eliminateAccent("Ç")); + + assertEquals("a", Strings.eliminateAccent("à")); + assertEquals("a", Strings.eliminateAccent("á")); + assertEquals("a", Strings.eliminateAccent("â")); + assertEquals("a", Strings.eliminateAccent("ã")); + assertEquals("a", Strings.eliminateAccent("ä")); + + assertEquals("e", Strings.eliminateAccent("è")); + assertEquals("e", Strings.eliminateAccent("é")); + assertEquals("e", Strings.eliminateAccent("ê")); + assertEquals("e", Strings.eliminateAccent("ë")); + + assertEquals("i", Strings.eliminateAccent("ì")); + assertEquals("i", Strings.eliminateAccent("í")); + assertEquals("i", Strings.eliminateAccent("î")); + assertEquals("i", Strings.eliminateAccent("ï")); + + assertEquals("o", Strings.eliminateAccent("ò")); + assertEquals("o", Strings.eliminateAccent("ó")); + assertEquals("o", Strings.eliminateAccent("ô")); + assertEquals("o", Strings.eliminateAccent("õ")); + assertEquals("o", Strings.eliminateAccent("ö")); + + assertEquals("u", Strings.eliminateAccent("ù")); + assertEquals("u", Strings.eliminateAccent("ú")); + assertEquals("u", Strings.eliminateAccent("û")); + assertEquals("u", Strings.eliminateAccent("ü")); + + assertEquals("A", Strings.eliminateAccent("À")); + assertEquals("A", Strings.eliminateAccent("Á")); + assertEquals("A", Strings.eliminateAccent("Â")); + assertEquals("A", Strings.eliminateAccent("Ã")); + assertEquals("A", Strings.eliminateAccent("Ä")); + + assertEquals("E", Strings.eliminateAccent("È")); + assertEquals("E", Strings.eliminateAccent("É")); + assertEquals("E", Strings.eliminateAccent("Ê")); + assertEquals("E", Strings.eliminateAccent("Ë")); + + assertEquals("I", Strings.eliminateAccent("Ì")); + assertEquals("I", Strings.eliminateAccent("Í")); + assertEquals("I", Strings.eliminateAccent("Î")); + assertEquals("I", Strings.eliminateAccent("Ï")); + + assertEquals("O", Strings.eliminateAccent("Ò")); + assertEquals("O", Strings.eliminateAccent("Ó")); + assertEquals("O", Strings.eliminateAccent("Ô")); + assertEquals("O", Strings.eliminateAccent("Õ")); + assertEquals("O", Strings.eliminateAccent("Ö")); + + assertEquals("U", Strings.eliminateAccent("Ù")); + assertEquals("U", Strings.eliminateAccent("Ú")); + assertEquals("U", Strings.eliminateAccent("Û")); + assertEquals("U", Strings.eliminateAccent("Ü")); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotNumericNull() { + Strings.checkNotNumeric(null); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotNumericBlank() { + Strings.checkNotNumeric(" 192343 "); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotNumericWithAlpha() { + Strings.checkNotNumeric("A192343B"); + } + + @Test + public void testCheckNotNumeric() { + Strings.checkNotNumeric("123"); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotBlankNull() { + Strings.checkNotBlank(null); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotBlankEmpty() { + Strings.checkNotBlank(""); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotBlankWithBlank() { + Strings.checkNotBlank(" "); + } + + @Test + public void testCheckNotBlank() { + Strings.checkNotBlank("Ok, Not Blank!"); + } + + @Test + public void testFillWithZeroLeftString(){ + assertEquals("012",Strings.fillWithZeroLeft("12", 3)); + } + + @Test + public void testFillWithZeroLeftInt(){ + assertEquals("012345678",Strings.fillWithZeroLeft(12345678, 9)); + } + + @Test + public void testFillWithZeroLeftLong(){ + assertEquals("012345678901",Strings.fillWithZeroLeft(12345678901L, 12)); + } +} diff --git a/jrimum-vallia/.gitignore b/jrimum-vallia/.gitignore new file mode 100644 index 0000000..700e479 --- /dev/null +++ b/jrimum-vallia/.gitignore @@ -0,0 +1,6 @@ +/bin +/target +.classpath +.DS_Store +.project +.settings \ No newline at end of file diff --git a/jrimum-vallia/CHANGELOG.md b/jrimum-vallia/CHANGELOG.md new file mode 100644 index 0000000..0dbb2a1 --- /dev/null +++ b/jrimum-vallia/CHANGELOG.md @@ -0,0 +1,6 @@ +Vallia Changelog +============================= + +0.2.3 (2014/02/01) suport bopepo-0.2.3 +--------------------------------------- + diff --git a/jrimum-vallia/LICENSE b/jrimum-vallia/LICENSE new file mode 100644 index 0000000..37ec93a --- /dev/null +++ b/jrimum-vallia/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/jrimum-vallia/README.md b/jrimum-vallia/README.md new file mode 100644 index 0000000..781a99f --- /dev/null +++ b/jrimum-vallia/README.md @@ -0,0 +1,6 @@ +Vallia +====== + +Validadores usados no projeto [Lançado embutido, incubado] + +[![Build Status](https://ci-jrimum.rhcloud.com/buildStatus/icon?job=Vallia)](https://ci-jrimum.rhcloud.com) diff --git a/jrimum-vallia/pom.xml b/jrimum-vallia/pom.xml new file mode 100644 index 0000000..75057f9 --- /dev/null +++ b/jrimum-vallia/pom.xml @@ -0,0 +1,182 @@ + + + 4.0.0 + br.com.rjconsultores + jrimum-vallia + jar + Projeto Vallia + 1.0.0 + Projeto open source de componentes de software para o domínio de negócios do Brasil. + http://www.jrimum.org/vallia + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + Projeto JRimum + http://www.jrimum.org + + + + http://github.com/jrimum/vallia/issues + GitHub + + + + http://github.com/jrimum/vallia + + + + + Gilmar P. S. L. + gilmatryx@gmail.com + + + Misael Barreto + misaelbarreto@gmail.com + + + Rômulo Augusto + romulomail@gmail.com + + + + + UTF-8 + UTF-8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.5 + 1.5 + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.6 + + + org.codehaus.mojo.signature + java15 + 1.0 + + + + + animal-sniffer + compile + + check + + + + + + maven-assembly-plugin + 2.4 + + + src/main/assembly/jrimum-vallia-with-dependencies.xml + + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.16 + + false + + org/jrimum/vallia/**/* + + + org/jrimum/vallia/excludes/**/* + org/jrimum/vallia/**/*$* + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + package + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadoc + package + + jar + + + + + UTF-8 + UTF-8 + true + private + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.1 + + + + + + + br.com.rjconsultores + jrimum-utilix + 1.0.0 + + + junit + junit + 4.11 + test + + + + + + rj-releases + http://52.5.53.15:8081/nexus/content/repositories/releases/ + + + diff --git a/jrimum-vallia/src/main/assembly/jrimum-vallia-with-dependencies.xml b/jrimum-vallia/src/main/assembly/jrimum-vallia-with-dependencies.xml new file mode 100644 index 0000000..76b72ff --- /dev/null +++ b/jrimum-vallia/src/main/assembly/jrimum-vallia-with-dependencies.xml @@ -0,0 +1,22 @@ + + dep + + jar + + false + + + / + true + true + runtime + + commons-lang:commons-lang + log4j:log4j + + + + \ No newline at end of file diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/AbstractCPRFValidator.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/AbstractCPRFValidator.java new file mode 100644 index 0000000..75c4d32 --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/AbstractCPRFValidator.java @@ -0,0 +1,344 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:19:24 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:19:24 + * + */ + +package org.jrimum.vallia; + +import static org.jrimum.utilix.Objects.isNotNull; + +import java.io.Serializable; +import java.util.regex.Pattern; + +import org.apache.commons.lang.StringUtils; +import org.jrimum.utilix.Exceptions; +import org.jrimum.utilix.Objects; +import org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador; +import org.jrimum.vallia.digitoverificador.CNPJDV; +import org.jrimum.vallia.digitoverificador.CPFDV; + +/** + * Representa a família de validadores para o cadastro de pessoa na receita + * federal (CPRF). + * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + * + */ +public abstract class AbstractCPRFValidator { + + /** + * Cadastro de pessoa para validação. + */ + protected StringBuilder codigoDoCadastro; + + /** + * Validador de dígito verificador do cadastro de Pessoa. + */ + protected AbstractDigitoVerificador digitoVerificador; + + /** + * Expressão regular para validação de CPF: "###.###.###-##" ou + * "###########". + */ + private static final String REGEX_CPF = "(\\d{3}\\.\\d{3}\\.\\d{3}\\-\\d{2})|(\\d{11})"; + + /** + * Expressão regular para validação de CNPJ: "##.###.###/####-##" ou + * "##############". + */ + private static final String REGEX_CNPJ = "(\\d{2}\\.\\d{3}\\.\\d{3}\\/\\d{4}\\-\\d{2})|(\\d{14})"; + + /** + * Expressão regular para validação de um cadastro: "###" ou + * "##############". + */ + private static final String REGEX_CADASTRO = "\\d{3,14}"; + + /** + * Representa o tipo de cadastro e fornece o autenticador correto de a cordo + * com este tipo. + * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ + public enum TipoDeCPRF implements Serializable { + + CPF, CNPJ; + + public AbstractCPRFValidator getAutenticador() { + + AbstractCPRFValidator validador = null; + + switch (this) { + + case CPF: + + validador = new CPFValidator(); + validador.digitoVerificador = new CPFDV(); + + break; + + case CNPJ: + + validador = new CNPJValidator(); + validador.digitoVerificador = new CNPJDV(); + + break; + } + + return validador; + } + + /** + * @see org.jrimum.utilix.Objects#toString() + * @see java.lang.Enum#toString() + */ + public String toString() { + return Objects.toString(this); + } + } + + /** + * @see org.jrimum.vallia.AbstractCPRFValidator.TipoDeCPRF + */ + private TipoDeCPRF tipoDeCadastro; + + /** + * Valida o dígito verificador do cadastro de pessoa passado durante a + * instanciação do validador. + * + * @return verdadeiro se o dígito verificador for válido. + */ + public abstract boolean isValido(); + + /** + * Revome a formatação existente em códigoDoCadastro. + */ + protected abstract void removeFormatacao(); + + /** + * Recupera uma instância de um validador para o cadastro de pessoa a partir + * de um identificador. + *

+ * Primeiro é feita uma pré-validação que consiste em: + *

    + *
  • Verificar se o parâmetro não é nulo.
  • + *
  • Verificar se o parâmetro não é vazio.
  • + *
  • Verificar se o parâmetro está em algum formatador válido para + * cadastro de pessoa.
  • + *
+ *

+ * + * @param codigoDoCadastro + * - identificador do cadastro de pessoa. + * @return uma instância de AbstractCPRFValidator. + * @exception IllegalArgumentException + * - caso o parâmetro não esteja em um formatador válido de + * cadastro de pessoa. + * @since 0.2 + */ + public static final AbstractCPRFValidator create(String codigoDoCadastro) + throws IllegalArgumentException { + + AbstractCPRFValidator validatorCPRF = null; + + validatorCPRF = create(selectTipoDeCadastro(codigoDoCadastro)); + + validatorCPRF.codigoDoCadastro = new StringBuilder(codigoDoCadastro); + validatorCPRF.removeFormatacao(); + + return validatorCPRF; + } + + /** + * Cria um validador a partir do tipo de CPRF. + * + * @param tipoDeCadastro + * @return um validador + * + * @since 0.2 + */ + public static final AbstractCPRFValidator create(TipoDeCPRF tipoDeCadastro) { + + AbstractCPRFValidator validatorCPRF = null; + + if (isNotNull(tipoDeCadastro)) { + + validatorCPRF = tipoDeCadastro.getAutenticador(); + + validatorCPRF.tipoDeCadastro = tipoDeCadastro; + + } else { + Exceptions.throwIllegalArgumentException("Tipo de Cadastro [ \"" + + tipoDeCadastro + "\" ] nulo !"); + } + + return validatorCPRF; + } + + /** + * Faz a pré-validação e se correto identifica o tipo de cadastro. + * + * @param codigoDoCadastro + * @return Tipo de CPRF + * @throws IllegalArgumentException + * + * @since 0.2 + */ + private static TipoDeCPRF selectTipoDeCadastro(String codigoDoCadastro) + throws IllegalArgumentException { + + TipoDeCPRF tipo = null; + + switch_Tipo: { + + if (StringUtils.isNotBlank(codigoDoCadastro)) { + + /* + * FILTRO + */ + + if (Pattern.matches(REGEX_CPF, codigoDoCadastro)) { + + tipo = TipoDeCPRF.CPF; + + break switch_Tipo; + } + + if (Pattern.matches(REGEX_CNPJ, codigoDoCadastro)) { + + tipo = TipoDeCPRF.CNPJ; + + break switch_Tipo; + } + + } + + Exceptions.throwIllegalArgumentException("O código de cadastro [ \"" + + codigoDoCadastro + + "\" ] não está em um formato válido !"); + } + + return tipo; + } + + /** + * Define se os parâmetros válidos em relação a nulidade e formato de CPRF. + * + * @param codigoDoCadastro + * @param tipoDeCadastro + * @return indicação de aprovação + * @throws IllegalArgumentException + * + * @since 0.2 + */ + public static final boolean isParametrosValidos(String codigoDoCadastro, + TipoDeCPRF tipoDeCadastro) throws IllegalArgumentException { + + boolean isValido = false; + + if (isNotNull(codigoDoCadastro) && isNotNull(tipoDeCadastro)) { + + if (Pattern.matches(REGEX_CADASTRO, codigoDoCadastro)) { + + isValido = true; + + } else { + + Exceptions.throwIllegalArgumentException( + "O cadastro está em um tamanho incorreto ou não exsite: [ \"" + + codigoDoCadastro + "\" ]"); + } + } else { + + Exceptions.throwIllegalArgumentException( + "O tipo de cadastro está incorreto: [ \"" + tipoDeCadastro + + "\" ] ou o cadastro não exsite: [ \"" + + codigoDoCadastro + "\" ]"); + } + + return isValido; + } + + /** + * Recupera o cadastro de pessoa a ser validado.
+ * Obs.: A String retornada não possui formatação, ou seja, possui apenas os + * dígitos. + * + * @return cadastro de pessoa a ser validado. + * + * @since 0.2 + */ + public final String getCodigoDoCadastro() { + + return codigoDoCadastro.toString(); + } + + /** + * Indica se o validador é de pessoa física. + * + * @return verdadeiro se for de pessoa física. + * @since 0.2 + */ + public final boolean isFisica() { + + return this instanceof CPFValidator; + } + + /** + * Indica se o validador é de pessoa jurídica. + * + * @return verdadeiro se for de pessoa jurídica. + * @since 0.2 + */ + public final boolean isJuridica() { + + return this instanceof CNPJValidator; + } + + /** + * @return the tipoDeCadastro + */ + public final TipoDeCPRF getTipoDeCadastro() { + return tipoDeCadastro; + } +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/CNPJValidator.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/CNPJValidator.java new file mode 100644 index 0000000..1ed1077 --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/CNPJValidator.java @@ -0,0 +1,100 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:19:49 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:19:49 + * + */ + +package org.jrimum.vallia; + +/** + * Validador especialista para CNPJ. + * + *

+ * O cadastro de pessoa jurídica tem as seguintes características: + *

    + *
  • Contém apenas números.
  • + *
  • Possui tamanho 14 sem formatação e 18 com formatação.
  • + *
  • Pode estar no formato ##.###.###/####-XX, onde XX é o dígito verificador. + *
  • + *
+ *

+ *

+ * A validação consiste em verificar essas características e se o dígito + * verificador é válido. + *

+ * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ +class CNPJValidator extends AbstractCPRFValidator { + + /** + * @see org.jrimum.vallia.AbstractCPRFValidator#isValido() + * @since 0.2 + */ + @Override + public boolean isValido() { + + boolean isValido = false; + int dv = 0; + int dvCalculado = -1; + + dv = Integer.parseInt(getCodigoDoCadastro().substring(12, 14)); + + dvCalculado = digitoVerificador.calcule(getCodigoDoCadastro() + .substring(0, 12)); + + isValido = (dv == dvCalculado); + + return isValido; + } + + /** + * @see org.jrimum.vallia.AbstractCPRFValidator#removeFormatacao() + * @since 0.2 + */ + @Override + protected void removeFormatacao() { + + String codigo = codigoDoCadastro.toString(); + + codigo = codigo.replace(".", ""); + codigo = codigo.replace("/", ""); + codigo = codigo.replace("-", ""); + + codigoDoCadastro.delete(0, codigoDoCadastro.length()); + + codigoDoCadastro.append(codigo); + } + +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/CPFValidator.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/CPFValidator.java new file mode 100644 index 0000000..575c92e --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/CPFValidator.java @@ -0,0 +1,99 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:21:21 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:21:21 + * + */ + +package org.jrimum.vallia; + +/** + * Validador especialista para CPF. + * + *

+ * O cadastro de pessoa física tem as seguintes características: + *

    + *
  • Contém apenas números.
  • + *
  • Possui tamanho 11 sem formatação e 14 com formatação.
  • + *
  • Pode estar no formato ###.###.###-XX, onde XX é o dígito verificador.
  • + *
+ *

+ *

+ * A validação consiste em verificar essas características e se o dígito + * verificador é válido. + *

+ * + * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ +class CPFValidator extends AbstractCPRFValidator { + + /** + * @see org.jrimum.vallia.AbstractCPRFValidator#isValido() + * @since 0.2 + */ + @Override + public boolean isValido() { + + boolean isValido = false; + int dv = 0; + int dvCalculado = -1; + + dv = Integer.parseInt(getCodigoDoCadastro().substring(9, 11)); + + dvCalculado = digitoVerificador.calcule(getCodigoDoCadastro() + .substring(0, 9)); + + isValido = (dvCalculado >= 0 && dv == dvCalculado); + + return isValido; + } + + /** + * @see org.jrimum.vallia.AbstractCPRFValidator#removeFormatacao() + * @since 0.2 + */ + @Override + protected void removeFormatacao() { + + String codigo = getCodigoDoCadastro(); + + codigo = codigo.replace(".", ""); + codigo = codigo.replace("-", ""); + + codigoDoCadastro.delete(0, codigoDoCadastro.length()); + + codigoDoCadastro.append(codigo); + } + +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/AbstractDigitoVerificador.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/AbstractDigitoVerificador.java new file mode 100644 index 0000000..89bea95 --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/AbstractDigitoVerificador.java @@ -0,0 +1,86 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:21:41 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:21:41 + * + */ + +package org.jrimum.vallia.digitoverificador; + +/** + *

+ * Define o comportamento de classes que implementam uma lógica de cálculo de + * um dígito verificador. + *

+ * + * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ +public abstract class AbstractDigitoVerificador { + + /** + *

+ * Calcula o dígito verificador de um número de acordo com uma lógica + * específica. + *

+ * + * @param numero + * - número que será calculado o dígito verificador. + * @return dígito verificador. + * @throws IllegalArgumentException + * caso a String não esteja em um formato aceitável. (O + * formato é definido nas subclasses implementadoras). + * @since 0.2 + */ + public abstract int calcule(String numero) throws IllegalArgumentException; + + /** + *

+ * Calcula o dígito verificador de um número de acordo com uma lógica + * específica. + *

+ *

+ * Se não sobrescrito o retorno é sempre igual a 0 (zero). + *

+ * + * @param numero + * - número que será calculado o dígito verificador. + * @return dígito verificador + * @since 0.2 + */ + public int calcule(long numero) { + + return 0; + } + +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/BoletoCodigoDeBarrasDV.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/BoletoCodigoDeBarrasDV.java new file mode 100644 index 0000000..370402c --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/BoletoCodigoDeBarrasDV.java @@ -0,0 +1,108 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:22:11 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:22:11 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import org.apache.commons.lang.StringUtils; +import org.jrimum.utilix.Exceptions; + +/** + *

+ * Lógica de cálculo do dígito verificador do código de barras de um boleto.
+ * A lógica funciona da seguinte forma: + *

+ *

+ * Utilizando-se o módulo 11, considerando-se os 43 dígitos que compõem o código + * de barras, já excluída a 5ª posição (posição do dígito verificador), segue-se + * o procedimento abaixo: + *

+ *

+ * Calcula-se o dígito verificador através da expressão DV = 11 - R + * , onde R é o resultado do cálculo do módulo.
+ * Observação: O dígito verificador será 1 para os restos (resultado do módulo): + * 0 , 10 ou 1 (zero, dez, um). + *

+ *

+ * Obs.: A rotina de módulo utilizada é o módulo 11. + *

+ * + * @see Modulo + * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @version 0.2 + * + * @since 0.2 + */ +public class BoletoCodigoDeBarrasDV extends AbstractDigitoVerificador { + + private static final int TAMANHO_SEM_DV = 43; + + private static final Modulo modulo11 = new Modulo(TipoDeModulo.MODULO11); + + /** + * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(String) + * @since 0.2 + */ + @Override + public int calcule(String numero) throws IllegalArgumentException { + + int dv = 0; + int resto = 0; + + if (StringUtils.isNotBlank(numero) && StringUtils.isNumeric(numero) + && (numero.length() == TAMANHO_SEM_DV)) { + + // Realizando o cálculo do dígito verificador utilizando módulo 11. + // Obtendo o resto da divisão por 11. + resto = modulo11.calcule(numero); + + // Seguindo as especificações da FEBRABAN, caso o resto seja + // (0), (1) ou (10), será atribuído (1) ao digito verificador. + if ((resto == 0) || (resto == 1) || (resto == 10)) { + dv = 1; + // Caso contrário, dv = 11 - resto. + } else { + dv = modulo11.valor() - resto; + } + + } else { + Exceptions.throwIllegalArgumentException("O código de barras " + "[ " + + numero + " ] deve conter apenas números e " + + TAMANHO_SEM_DV + " dígitos."); + } + + return dv; + } + +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/BoletoLinhaDigitavelDV.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/BoletoLinhaDigitavelDV.java new file mode 100644 index 0000000..6e036fa --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/BoletoLinhaDigitavelDV.java @@ -0,0 +1,138 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:22:21 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:22:21 + * + */ + +package org.jrimum.vallia.digitoverificador; + + +import static java.util.regex.Pattern.matches; +import static org.apache.commons.lang.StringUtils.isNotBlank; +import static org.apache.commons.lang.StringUtils.replaceChars; +import static org.jrimum.utilix.text.Strings.fillWithZeroLeft; + +import org.jrimum.utilix.Exceptions; + +/** + *

+ * Segundo o padrão FEBRABAN a linha digitável possui cinco campos, dos quais + * apenas os três primeiros necessitam de validação com dígito verificador. + *

+ *

+ * Para fins de validação é preciso saber o seguinte: + *

    + *
  • O primerio campo tem tamanho 9 (nove) mais o dígito verificador.
  • + *
  • O segundo campo tem tamanho 10 (dez) mais o dígito verificador.
  • + *
  • O terceiro campo tem tamanho 10 (dez) mais o dígito verificador.
  • + *
+ *

+ *

+ * Obs1.: Todos os campos listados podem vir com um ponto (.) de separação + * exatamente após o dígito da 5ª posição.
+ * Exemplo de linha digitável:
+ * 99997.77213 30530.150082 18975.000003 1 10010000035000 + *

+ *

+ * O cálculo do dígito verificador é descrito através da expressão + * DV = 11 - R, onde R é o resultado do cálculo do módulo.
+ * Obs1.: O dígito verificador será 0 (zero) se o resto (resultado do módulo) + * for 0 (zero).
+ * Obs2.: A rotina de módulo utilizada é a módulo 10. + *

+ * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ +public class BoletoLinhaDigitavelDV extends AbstractDigitoVerificador { + + /** + *

+ * Módulo 10 utilizado no cálculo. + *

+ */ + private static final Modulo modulo10 = new Modulo(TipoDeModulo.MODULO10); + + /** + *

+ * Expressão regular para validação do campo da linha digitável, aceita os + * seguintes formatos: + *

+ *
    + *
  • #########
  • + *
  • #####.####
  • + *
  • ##########
  • + *
  • #####.#####
  • + *
+ */ + private static final String REGEX_CAMPO = "(\\d{9})|(\\d{10})|(\\d{5})\\.(\\d{4})|(\\d{5})\\.(\\d{5})"; + + /** + * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String) + * @since 0.2 + */ + @Override + public int calcule(long numero) { + + return calcule(fillWithZeroLeft(numero, 10)); + } + + /** + * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String) + * @since 0.2 + */ + @Override + public int calcule(String numero) throws IllegalArgumentException { + + int dv = 0; + int resto = 0; + + if (isNotBlank(numero) + && matches(REGEX_CAMPO, numero)) { + + numero = replaceChars(numero, ".", ""); + + resto = modulo10.calcule(numero); + + if (resto != 0) { + dv = modulo10.valor() - resto; + } + } else { + Exceptions.throwIllegalArgumentException("O campo [" + numero + + "] da linha digitável deve conter apenas números com 9 ou 10 dígitos " + + "ou nos formatos [#####.####, #####.#####]"); + } + + return dv; + } +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CNPJDV.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CNPJDV.java new file mode 100644 index 0000000..2d4b1ba --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CNPJDV.java @@ -0,0 +1,231 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:22:39 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:22:39 + * + */ + +package org.jrimum.vallia.digitoverificador; + + +import static org.apache.commons.lang.StringUtils.isNotBlank; +import static org.apache.commons.lang.StringUtils.replaceChars; +import static org.jrimum.utilix.text.Strings.fillWithZeroLeft; + +import java.util.regex.Pattern; + +import org.jrimum.utilix.Exceptions; + +/** + *

+ * O cálculo do dígito verificador do CNPJ é realizado em duas etapas e é + * auxiliado pela rotina de módulo 11. + *

+ *

+ * Abaixo é demonstrado como esse cálculo é feito: + *

+ *

Exemplo para um número hipotético 11.222.333/0001-XX:

+ *

+ * Primeiramente obtém-se um número R, calculado através da rotina de módulo 11, + * a partir dos doze primeiros números do CNPJ, nesse caso 112223330001.
+ * Para obter o primeiro dígito verificador deve-se seguir a seguinte lógica:
+ *
+ * Se o número R for menor que 2, o dígito terá valor 0 (zero); senão, será a + * subtração do valor do módulo (11) menos o valor do número R, ou seja, + * DV = 11 - R. + *

+ *

+ * Para obter o segundo dígito verificador é da mesma forma do primeiro, porém + * deve ser calculado a partir dos treze primeiros números do CNPJ, ou seja, + * 112223330001 + primeiro dígito. + *

+ *

+ * Obs.: O limite mínimo e máximo do módulo 11 são 2 e 9, respectivamente. + *

+ * + * @see Modulo + * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ +public class CNPJDV extends AbstractDigitoVerificador { + + /** + *

+ * Liminte mínimo do para cálculo no módulo 11. + *

+ */ + private static final int LIMITE_MINIMO = 2; + + /** + *

+ * Liminte máximo do para cálculo no módulo 11. + *

+ */ + private static final int LIMITE_MAXIMO = 9; + + /** + *

+ * Expressão regular para validação dos doze primeiros números do CNPJ sem + * formatação: "############". + *

+ */ + private static final String REGEX_CNPJ_DV = "\\d{12}"; + + /** + *

+ * Expressão regular para validação dos doze primeiros números do CNPJ + * formatado: "##.###.###/####". + *

+ */ + private static final String REGEX_CNPJ_DV_FORMATTED = "\\d{2}\\.\\d{3}\\.\\d{3}\\/\\d{4}"; + + /** + * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(long) + * @since 0.2 + */ + @Override + public int calcule(long numero) { + + return calcule(fillWithZeroLeft(numero, 12)); + } + + /** + *

+ *

+ * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String) + * @since 0.2 + */ + @Override + public int calcule(String numero) throws IllegalArgumentException { + + int dv1 = 0; + int dv2 = 0; + + numero = removaFormatacao(numero); + + if (isFormatoValido(numero)) { + + dv1 = calculeDigito(numero); + dv2 = calculeDigito(numero + dv1); + + } else { + + Exceptions.throwIllegalArgumentException( + "O CNPJ [ " + numero + + " ] deve conter apenas números, sendo eles no formato ##.###.###/#### ou ############ !"); + } + + return Integer.parseInt(dv1 + "" + dv2); + } + + /** + * Método null-safe que remove a formatação da String, com a intenção de deixar + * apenas números. + * + * @param numero - CNPJ que pode estar formatado. + * @return Número CNPJ sem formatação. + */ + private String removaFormatacao(String numero) { + + numero = replaceChars(numero, ".", ""); + numero = replaceChars(numero, "/", ""); + + return numero; + } + + /** + *

+ * Verifica se o número passado está em um formato aceitável para a realização do cálculo, + * ou seja: + *

+ *
    + *
  • Não é null
  • + *
  • Não é vazio
  • + *
  • Apenas números
  • + *
  • Não é somente zeros
  • + *
  • Está no formato ##.###.###/#### ou ############
  • + *
+ * + * @param numero - CNPJ para ser validado + * @return true caso o número esteja em um formato válido; false, + * caso contrário. + */ + private boolean isFormatoValido(String numero) { + + boolean isValido = false; + + if (isNotBlank(numero)) { + + boolean formatoValido = (Pattern.matches(REGEX_CNPJ_DV, numero) || Pattern.matches(REGEX_CNPJ_DV_FORMATTED, numero)); + + if (formatoValido) { + + isValido = Long.parseLong(numero) > 0; + } + } + + return isValido; + } + + /** + *

+ * Método auxiliar para o cálculo do dígito verificador. + *

+ *

+ * Calcula os dígitos separadamente. + *

+ * + * @param numero + * - número a partir do qual será extraído o dígito verificador. + * @return Um número que faz parte de um dígito verificador. + * @throws IllegalArgumentException + * caso o número não esteja no formatador desejável. + * + * @since 0.2 + */ + private int calculeDigito(String numero) throws IllegalArgumentException { + + int dv = 0; + int resto = 0; + + resto = Modulo.calculeMod11(numero, LIMITE_MINIMO, LIMITE_MAXIMO); + + if (resto >= 2) { + + dv = TipoDeModulo.MODULO11.valor() - resto; + } + + return dv; + } + +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CPFDV.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CPFDV.java new file mode 100644 index 0000000..d480be0 --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CPFDV.java @@ -0,0 +1,223 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:51:09 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:51:09 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import static org.apache.commons.lang.StringUtils.isNotBlank; +import static org.apache.commons.lang.StringUtils.replaceChars; +import static org.jrimum.utilix.text.Strings.fillWithZeroLeft; + +import java.util.regex.Pattern; + +import org.jrimum.utilix.Exceptions; + +/** + *

+ * O cálculo do dígito verificador do CPF é realizado em duas etapas e é + * auxiliado pela rotina de módulo 11. + *

+ *

+ * Abaixo é demonstrado como esse cálculo é feito: + *

+ *

Exemplo para um número hipotético 222.333.666-XX:

+ *

+ * Primeiramente obtém-se um número R, calculado através da rotina de módulo 11, + * a partir dos nove primeiros números do CPF, nesse caso 222333666.
+ * Para obter o primeiro dígito verificador deve-se seguir a seguinte lógica:
+ *
+ * Se o número R for menor que 2, o dígito terá valor 0 (zero); senão, será a + * subtração do valor do módulo (11) menos o valor do número R, ou seja, + * DV = 11 - R. + *

+ *

+ * Para obter o segundo dígito verificador é da mesma forma do primeiro, porém + * deve ser calculado a partir dos dez primeiros números do CPF, ou seja, + * 222333666 + primeiro dígito. + *

+ *

+ * Obs.: Os limites mínimos e máximos do módulo 11 para o cálculo do primeiro e + * do segundo dígito verificador são 2 - 10 e 2 e 11, respectivamente. + *

+ * + * @see Modulo + * + * @author Gilmar P.S.L + * @author Misael Barreto + * @author Rômulo Augusto + * @author Nordeste Fomento + * Mercantil + * + * @since 0.2 + * + * @version 0.2 + */ +public class CPFDV extends AbstractDigitoVerificador { + + /** + *

+ * Liminte mínimo do para cálculo no módulo 11. + *

+ */ + private static final int LIMITE_MINIMO = 2; + + /** + *

+ * Expressão regular para validação dos nove primeiros números do CPF sem + * formatação: "#########". + *

+ */ + private static final String REGEX_CPF_DV = "\\d{9}"; + + /** + *

+ * Expressão regular para validação dos nove primeiros números do CPF + * formatado: "###.###.###". + *

+ */ + private static final String REGEX_CPF_DV_FORMATTED = "\\d{3}\\.\\d{3}\\.\\d{3}"; + + /** + * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(long) + * @since 0.2 + */ + @Override + public int calcule(long numero) { + + return calcule(fillWithZeroLeft(numero, 9)); + } + + /** + * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String) + * @since 0.2 + */ + @Override + public int calcule(String numero) throws IllegalArgumentException { + + int dv1 = 0; + int dv2 = 0; + + numero = removaFormatacao(numero); + + if (isFormatoValido(numero)) { + + dv1 = calcule(numero, 10); + dv2 = calcule(numero + dv1, 11); + + } else { + + Exceptions.throwIllegalArgumentException("O CPF [ " + numero + + " ] deve conter apenas números, sendo eles no formato ###.###.### ou ######### !"); + } + + return Integer.parseInt(dv1 + "" + dv2); + + } + + /** + * Método null-safe que remove a formatação da String, com a intenção de deixar + * apenas números. + * + * @param numero - CNPJ que pode estar formatado. + * @return Número CNPJ sem formatação. + */ + private String removaFormatacao(String numero) { + + numero = replaceChars(numero, ".", ""); + + return numero; + } + + /** + *

+ * Verifica se o número passado está em um formato aceitável para a realização do cálculo, + * ou seja: + *

+ *
    + *
  • Não é null
  • + *
  • Não é vazio
  • + *
  • Apenas números
  • + *
  • Não é somente zeros
  • + *
  • Está no formato ##.###.###/#### ou ############
  • + *
+ * + * @param numero - CNPJ para ser validado + * @return true caso o número esteja em um formato válido; false, + * caso contrário. + */ + private boolean isFormatoValido(String numero) { + + boolean isValido = false; + + if (isNotBlank(numero)) { + + boolean formatoValido = (Pattern.matches(REGEX_CPF_DV, numero) || Pattern.matches(REGEX_CPF_DV_FORMATTED, numero)); + + if (formatoValido) { + + isValido = Long.parseLong(numero) > 0; + } + } + + return isValido; + } + + /** + *

+ * Método auxiliar para o cálculo do dígito verificador. + *

+ *

+ * Calcula os dígitos separadamente. + *

+ * + * @param numero + * - número a partir do qual será extraído o dígito verificador. + * @param limiteMaximoDoModulo + * - limite máximo do módulo utilizado, no caso, módulo 11. + * @return um número que faz parte de um dígito verificador. + * @throws IllegalArgumentException + * caso o número não esteja no formatador desejável. + * @since 0.2 + */ + private int calcule(String numero, int limiteMaximoDoModulo) + throws IllegalArgumentException { + + int dv = 0; + int resto = 0; + + resto = Modulo + .calculeMod11(numero, LIMITE_MINIMO, limiteMaximoDoModulo); + + if (resto >= 2) { + + dv = TipoDeModulo.MODULO11.valor() - resto; + } + + return dv; + } +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CodigoDeCompensacaoBancosBACENDV.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CodigoDeCompensacaoBancosBACENDV.java new file mode 100644 index 0000000..7292eae --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/CodigoDeCompensacaoBancosBACENDV.java @@ -0,0 +1,194 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + * + * Created at: 15/06/2008 - 12:00:00 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode + * usar esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob esta + * LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER TIPO, sejam + * expressas ou tácitas. Veja a LICENÇA para a redação específica a reger permissões + * e limitações sob esta LICENÇA. + * + * Criado em: 15/06/2008 - 12:00:00 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import org.apache.commons.lang.StringUtils; +import org.jrimum.utilix.Exceptions; + +/** + *

+ * Cálculo para o dígito verificador do código de compensação dos bancos + * supervisionados pelo BACEN + *

+ * + * @author Gilmar P.S.L. + * @author Misael Barreto + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public class CodigoDeCompensacaoBancosBACENDV extends AbstractDigitoVerificador { + + /** + * Valor mínimo do código de compensação + */ + public static final int LIMITE_MINIMO = 1; + + /** + * Valor máximo do código de compensação + */ + public static final int LIMITE_MAXIMO = 999; + + /** + *

+ * Mesagem padrão para erro. + *

+ */ + private static final String MSG = "O código de compensação do banco deve ser um número entre 1 e 999."; + + /** + *

+ * Calcula o dígito verificador para código de compensação passado. + *

+ * + * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String) + * + * @param numero - Código de compensação + * @return Dígito verificador que foi calculado + * + * @throws IllegalArgumentException Caso não seja um código válido + * + * @since 0.2 + */ + @Override + public int calcule(String numero) { + + if (!isCodigoValido(numero)) { + Exceptions.throwIllegalArgumentException(MSG); + } + + return calcule(Integer.valueOf(numero.trim())); + } + + /** + *

+ * Calcula o dígito verificador para o código de compensação passado. + *

+ * + * @param numero - Código de compensação + * + * @return Dígito verificador que foi calculado + * + * @since 0.2 + */ + public int calcule(int numero) { + + return calcule((long) numero); + } + + /** + *

+ * Calcula o dígito verificador para o código de compensação passado. + *

+ * + * @param numero - Código de compensação + * + * @return Dígito verificador que foi calculado + * + * @since 0.2 + * + * @see org.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(long) + */ + @Override + public int calcule(long numero) { + + int dv = -1; + + if (!isCodigoValido(numero)) { + Exceptions.throwIllegalArgumentException(MSG); + } + + int soma = Modulo.calculeSomaSequencialMod11( + String.valueOf(numero), 2, 9); + + soma *= 10; + + dv = soma % 11; + + dv = (dv == 10) ? 0 : dv; + + return dv; + } + + /** + *

+ * Retorna se um código de compensação passado é válido, ou seja, se está entre os + * valores inteiros de 1 a 999. + *

+ * + * @param codigo - Código de compensação + * @return true se for númerio entre 1 e 999; false caso contrário + * + * @since 0.2 + */ + public boolean isCodigoValido(String codigo) { + + boolean codigoValido = false; + + if (StringUtils.isNotBlank(codigo) && StringUtils.isNumeric(codigo)) { + codigoValido = isCodigoValido(Integer.valueOf(codigo.trim())); + } + + return codigoValido; + } + + /** + *

+ * Retorna se um código de compensação passado é válido. + *

+ * + * @param codigo - Código de compensação + * @return true se entre 0 (não incluso) e 999; false caso contrário + * + * @since 0.2 + */ + public boolean isCodigoValido(int codigo) { + + return isCodigoValido((long) codigo); + } + + /** + *

+ * Retorna se um código de compensação passado é válido. + *

+ * + * @param codigo - Código de compensação + * @return true se entre 0 (não incluso) e 999; false caso contrário + * + * @since 0.2 + */ + public boolean isCodigoValido(long codigo) { + + return (codigo >= LIMITE_MINIMO) && (codigo <= LIMITE_MAXIMO); + } +} \ No newline at end of file diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/Modulo.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/Modulo.java new file mode 100644 index 0000000..1dd44c2 --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/Modulo.java @@ -0,0 +1,518 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + * + * Created at: 20/04/2008 - 18:11:05 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode + * usar esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob esta + * LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER TIPO, sejam + * expressas ou tácitas. Veja a LICENÇA para a redação específica a reger permissões + * e limitações sob esta LICENÇA. + * + * Criado em: 20/04/2008 - 18:11:05 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import static org.jrimum.vallia.digitoverificador.TipoDeModulo.MODULO10; +import static org.jrimum.vallia.digitoverificador.TipoDeModulo.MODULO11; + +import org.apache.commons.lang.StringUtils; +import org.jrimum.utilix.Exceptions; +import org.jrimum.utilix.Objects; + +/** + * Representa o módulo no contexto de autenticação, ou seja, uma rotina que + * auxilia no cálculo do dígito verificador. + + *

+ * As rotinas tradicionais são Módulo 10 e Módulo 11. + *

+ * + * @author Gilmar P.S.L. + * + * @version 0.2 + * + * @since 0.2 + */ +public class Modulo { + + /** + * Mensagem da exceção lançada no método calcular. + */ + private static final String O_ARGUMENTO_DEVE_CONTER_APENAS_NUMEROS = "O argumento deve conter apenas números !"; + + /** + * Valor inteiro do módulo 10 + */ + public static final int MOD10 = TipoDeModulo.MODULO10.valor(); + + /** + * Valor inteiro do módulo 11 + */ + public static final int MOD11 = TipoDeModulo.MODULO11.valor(); + + /** + * Tipo do módulo + */ + private TipoDeModulo mod; + + /** + * Valor inteiro do "peso" mínimo mutiplicador utilizado no cálculo do + * módulo. + */ + private int limiteMaximo; + + /** + * Valor inteiro do "peso" máximo mutiplicador utilizado no cálculo do + * módulo. + */ + private int limiteMinimo; + + /** + * Inicializa um módulo com valores default. + * + * @param mod + * tipo do módulo + * @see #initDefault + * @see #calcule(String) + * @since 0.2 + */ + public Modulo(TipoDeModulo mod) { + super(); + + Objects.checkNotNull(mod, "Módulo nulo!"); + + this.mod = mod; + initDefault(); + } + + /** + * Inicializa um módulo com o tipo definido com valores default. + * + * @param limiteMaximo + * peso máximo + * @param limiteMinimo + * peso mínimo + * @param mod + * tipo do módulo + * @see #calcule(String) + * @since 0.2 + */ + public Modulo(TipoDeModulo mod, int limiteMaximo, int limiteMinimo) { + super(); + + Objects.checkNotNull(mod, "Módulo nulo!"); + + this.limiteMaximo = limiteMaximo; + this.limiteMinimo = limiteMinimo; + this.mod = mod; + } + + /** + * Retorna o valor da instância do módulo de acordo com a enum + * da instância. + * + *

+ * Se por um acaso a instância enum for nula uma + * NullPointerException será lançada. Caso a enum + * contenha um módulo não implementado por essa classe o retorno será + * -1 + *

+ * + * @return valor da instância do módulo. + * + * @since 0.2 + */ + public int valor() { + + switch (mod) { + + case MODULO10: + + return MODULO10.valor(); + + case MODULO11: + + return MODULO11.valor(); + + default: + return -1; + } + } + + /** + * Executa o cáculo do módulo 11 com os limites definidos. + * + *

+ * Executa o método calculeSomaSequencialMod11 e aplica o + * resultado em % 11 + *

+ * + * @param numero + * @param limiteMin + * @param limiteMax + * @return Resultado de calculeSomaSequencialMod11 % 11 + * + * @since 0.2 + * @see #calculeSomaSequencialMod11(String, int, int) + */ + public static int calculeMod11(String numero, int limiteMin, int limiteMax) + throws IllegalArgumentException { + + return (calculeSomaSequencialMod11(numero, limiteMin, limiteMax) % MOD11); + } + + /** + *

+ * Executa o cáculo do módulo 11 com os limites definidos. + *

+ * + *

+ * Transforma o numero em string e executa o método + * calculeMod11 + *

+ * + * @param numero + * @param limiteMin + * @param limiteMax + * @return resultado do cálculo + * + * @since 0.2 + * @see #calculeMod11(String, int, int) + */ + public static int calculeMod11(long numero, int limiteMin, int limiteMax) { + + return calculeMod11(String.valueOf(numero), limiteMin, limiteMax); + } + + /** + * Realiza o cálculo da soma na forma do módulo 11. + *

+ * O módulo 11 funciona da seguinte maneira: + *

+ *

+ * Cada dígito do número, começando da direita para a esquerda (menos + * significativo para o mais significativo), é multiplicado pelo números + * limite mínimo, limite mínimo + 1, limite mínimo + 2 e assim + * sucessivamente até o limite máxmio definido, então inicia-se novamente a + * contagem. + *

+ *

+ * Exemplo para o número 654321: + * + *

+	 * +---+---+---+---+---+---+
+	 * | 6 | 5 | 4 | 3 | 2 | 1 |
+	 * +---+---+---+---+---+---+
+	 *   |   |   |   |   |   |
+	 *  x7  x6  x5  x4  x3  x2
+	 *   |   |   |   |   |   |
+	 *  =42 =30 =20 =12 =6  =2
+	 *   +---+---+---+---+---+->
+	 * 
+ * + * @param numero + * @param limiteMin + * @param limiteMax + * @return Soma da sequencia sem executar Mod 11 + * @throws IllegalArgumentException + * + * @since 0.2 + */ + public static int calculeSomaSequencialMod11(String numero, int limiteMin, + int limiteMax) throws IllegalArgumentException { + + int peso = 0; + int soma = 0; + + if (StringUtils.isNotBlank(numero) && StringUtils.isNumeric(numero)) { + + StringBuilder sb = new StringBuilder(numero); + sb.reverse(); + + peso = limiteMin; + + for (char c : sb.toString().toCharArray()) { + soma += peso * Character.getNumericValue(c); + peso++; + + if (peso > limiteMax) + peso = limiteMin; + } + + } else + Exceptions.throwIllegalArgumentException( + O_ARGUMENTO_DEVE_CONTER_APENAS_NUMEROS); + + return soma; + } + + /** + * Executa o cáculo do módulo 10 com os limites definidos. + * + *

+ * Transforma o numero em string e executa o método + * calculeMod10 + *

+ * + * @param numero + * @param limiteMin + * @param limiteMax + * @return resultado do cálculo + * + * @since 0.2 + * @see #calculeMod10(String, int, int) + */ + public static int calculeMod10(long numero, int limiteMin, int limiteMax) { + + return calculeMod10(String.valueOf(numero), limiteMin, limiteMax); + } + + /** + * Executa o cáculo do módulo 10 com os limites definidos. + * + *

+ * Executa o método calculeSomaSequencialMod10 e aplica o + * resultado em % 10 + *

+ * + * @param numero + * @param limiteMin + * @param limiteMax + * @return resultado de calculeSomaSequencialMod10 % 10 + * + * @since 0.2 + * @see #calculeSomaSequencialMod10(String, int, int) + */ + public static int calculeMod10(String numero, int limiteMin, int limiteMax) + throws IllegalArgumentException { + + return (calculeSomaSequencialMod10(numero, limiteMin, limiteMax) % MOD10); + } + + /** + * Realiza o cálculo da soma na forma do módulo 10. + *

+ * O módulo 10 funciona da seguinte maneira: + *

+ *

+ * Cada dígito do número, começando da direita para a esquerda (menos + * significativo para o mais significativo), é multiplicado pelo números + * limite mínimo, limite mínimo + 1, limite mínimo + 2 e assim + * sucessivamente até o limite máxmio definido, então inicia-se novamente a + * contagem. + *

+ *

+ * Exemplo para o número 123456: + * + *

+	 * +---+---+---+---+---+---+
+	 * | 1 | 2 | 3 | 4 | 5 | 6 |
+	 * +---+---+---+---+---+---+
+	 *   |   |   |   |   |   |
+	 *  x1  x2  x1  x2  x1  x2
+	 *   |   |   |   |   |   |
+	 *  =1  =4  =3  =8  =5  =[ 3 <= ( 1 + 2 <==12 ) ] = 24
+	 *   +---+---+---+---+---+-> = (24 / 10) = 3, resto 3; Então o módulo é igual a 3.
+	 * 
+ * + *

+ * + *

+ * Geralmente os limites para o módulo 10 são mínimo 1 e máximo 2 apenas. + *

+ * + * @param numero + * @param limiteMin + * @param limiteMax + * @return soma sequencial usada no cálculo do módulo + * @throws IllegalArgumentException + * + * @since 0.2 + */ + public static int calculeSomaSequencialMod10(String numero, int limiteMin, + int limiteMax) throws IllegalArgumentException { + + int produto = 0; + int peso = 0; + int soma = 0; + + if (StringUtils.isNotBlank(numero) && StringUtils.isNumeric(numero)) { + + StringBuilder sb = new StringBuilder(numero); + sb.reverse(); + + peso = limiteMax; + + for (char c : sb.toString().toCharArray()) { + + produto = peso * Character.getNumericValue(c); + + if (produto > 9) { + + soma += produto / 10; + soma += produto % 10; + } else + soma += produto; + + peso = (peso == limiteMax) ? limiteMin : limiteMax; + } + + } else + Exceptions.throwIllegalArgumentException( + O_ARGUMENTO_DEVE_CONTER_APENAS_NUMEROS); + + return soma; + } + + /** + * Executa o cáculo do módulo da instância. + * + * @param numero + * @return Módulo + * @throws IllegalArgumentException + * + * @since 0.2 + */ + public int calcule(String numero) throws IllegalArgumentException { + + int modulo = 0; + + switch (mod) { + + case MODULO10: + + modulo = calculeMod10(numero, getLimiteMinimo(), getLimiteMaximo()); + + break; + + case MODULO11: + + modulo = calculeMod11(numero, getLimiteMinimo(), getLimiteMaximo()); + + break; + } + + return modulo; + } + + /** + * Executa o cáculo do módulo da instância. + * + * @param numero + * @return módulo + * + * @since 0.2 + */ + public int calcule(long numero) { + + return calcule(String.valueOf(numero)); + } + + /** + * Inicializa as variáveis limiteMaximo e + * limiteMinimo com os valores padrões de acordo com a + * instância do módulo da classe. + * + *

+ * Valores padrões:
+ *
+ * MODULO10: (limiteMinimo = 1 e limiteMaximo = 2)
+ * + * MODULO11: (limiteMinimo = 2 e limiteMaximo = 9)
+ *

+ * + * @since 0.2 + */ + private void initDefault() { + + switch (mod) { + + case MODULO10: + + setLimiteMinimo(1); + setLimiteMaximo(2); + + break; + + case MODULO11: + + setLimiteMinimo(2); + setLimiteMaximo(9); + + break; + } + } + + /** + * @return the limiteMaximo + */ + public int getLimiteMaximo() { + return limiteMaximo; + } + + /** + * @param limiteMaximo + * the limiteMaximo to set + */ + public void setLimiteMaximo(int limiteMaximo) { + this.limiteMaximo = limiteMaximo; + } + + /** + * @return the limiteMinimo + */ + public int getLimiteMinimo() { + return limiteMinimo; + } + + /** + * @param limiteMinimo + * the limiteMinimo to set + */ + public void setLimiteMinimo(int limiteMinimo) { + this.limiteMinimo = limiteMinimo; + } + + /** + * @return Tipo do módulo + */ + public TipoDeModulo getMod() { + return mod; + } + + /** + * @param mod + * Tipo do módulo + */ + public void setMod(TipoDeModulo mod) { + this.mod = mod; + } + + /** + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return Objects.toString(this); + } +} diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/TipoDeModulo.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/TipoDeModulo.java new file mode 100644 index 0000000..5096e7a --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/TipoDeModulo.java @@ -0,0 +1,83 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:51:20 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:51:20 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import java.io.Serializable; + +/** + * Enumeração das implementações dos módulos. + * + * @author Gilmar P.S.L. + * + * @since 0.2 + * + * @version 0.2 + */ +public enum TipoDeModulo implements Serializable { + + /** + * Módulo do tipo 11. + * + * @since 0.2 + */ + MODULO10 { + /** + * @see org.jrimum.vallia.digitoverificador.TipoDeModulo#valor() + * @since 0.2 + */ + public int valor() { + return 10; + } + }, + + /** + * Módulo do tipo 11. + * + * @since 0.2 + */ + MODULO11 { + /** + * @see org.jrimum.vallia.digitoverificador.TipoDeModulo#valor() + * @since 0.2 + */ + public int valor() { + return 11; + } + }; + + /** + * Retorna o valor do módulo. + * + * @return 10 ou 11 + * + * @since 0.2 + */ + public abstract int valor(); +} \ No newline at end of file diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/package-info.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/package-info.java new file mode 100644 index 0000000..216910b --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/digitoverificador/package-info.java @@ -0,0 +1,35 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 15/08/2010 - 15:37:49 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 15/08/2010 - 15:37:49 + * + */ + +/** + * Validadores e métodos de validação usados no projeto como módulos 10 e 11, dígitos verificadores, etc. + * + * @author Gilmar P.S.L + */ +package org.jrimum.vallia.digitoverificador; \ No newline at end of file diff --git a/jrimum-vallia/src/main/java/org/jrimum/vallia/package-info.java b/jrimum-vallia/src/main/java/org/jrimum/vallia/package-info.java new file mode 100644 index 0000000..d2c9a63 --- /dev/null +++ b/jrimum-vallia/src/main/java/org/jrimum/vallia/package-info.java @@ -0,0 +1,35 @@ +/* + * Copyright 2010 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 15/08/2010 - 15:37:49 + * + * ================================================================================ + * + * Direitos autorais 2010 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 15/08/2010 - 15:37:49 + * + */ + +/** + * Validadores usados no projeto, ex: CPF e CNPJ. + * + * @author Gilmar P.S.L + */ +package org.jrimum.vallia; \ No newline at end of file diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/TestAbstractCPRFValidator.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/TestAbstractCPRFValidator.java new file mode 100644 index 0000000..a1a5903 --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/TestAbstractCPRFValidator.java @@ -0,0 +1,140 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:52:12 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:52:12 + * + */ + + +package org.jrimum.vallia; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.jrimum.vallia.AbstractCPRFValidator.TipoDeCPRF; +import org.junit.Test; + + +/** + * Teste da classe AbstractCPRFValidator. + * + * + * @author Gabriel Guimarães + * @author Gilmar P.S.L. + * @author Misael Barreto + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public class TestAbstractCPRFValidator{ + + private AbstractCPRFValidator validator; + + @Test + public void testGetInstance() { + + try { + + TipoDeCPRF nulo = null; + + AbstractCPRFValidator.create(nulo); + + fail("IllegalArgumentException esperado não ocorreu."); + assertTrue(false); + + } catch (IllegalArgumentException iaex) { + + assertTrue(true); + System.out.println(iaex.getMessage()); + } + + try { + + AbstractCPRFValidator.create("abc123"); + + fail("IllegalArgumentException esperado não ocorreu."); + assertTrue(false); + + } catch (IllegalArgumentException iaex) { + + assertTrue(true); + System.out.println(iaex.getMessage()); + } + + try { + + AbstractCPRFValidator.create("222333666"); + + fail("IllegalArgumentException esperado não ocorreu."); + assertTrue(false); + + } catch (IllegalArgumentException iaex) { + + assertTrue(true); + System.out.println(iaex.getMessage()); + } + + try { + + AbstractCPRFValidator.create("112223330001"); + + fail("IllegalArgumentException esperado não ocorreu."); + assertTrue(false); + + } catch (IllegalArgumentException iaex) { + + assertTrue(true); + System.out.println(iaex.getMessage()); + } + + assertNotNull(AbstractCPRFValidator.create("22233366638")); + assertNotNull(AbstractCPRFValidator.create("222.333.666-38")); + + assertNotNull(AbstractCPRFValidator.create("11222333000181")); + assertNotNull(AbstractCPRFValidator.create("11.222.333/0001-81")); + + } + + @Test + public void testIsFisica() { + + validator = AbstractCPRFValidator.create("22233366638"); + + assertTrue(validator instanceof CPFValidator); + } + + @Test + public void testIsJuridica() { + + validator = AbstractCPRFValidator.create("11222333000181"); + + assertTrue(validator instanceof CNPJValidator); + + } + +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/TestCNPJValidator.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/TestCNPJValidator.java new file mode 100644 index 0000000..7c663c6 --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/TestCNPJValidator.java @@ -0,0 +1,67 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:52:37 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:52:37 + * + */ + + +package org.jrimum.vallia; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Teste da classe Validator_CadastroDePessoaJurídica. + * + * + * @author Gabriel Guimarães + * @author Gilmar P.S.L. + * @author Misael Barreto + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public class TestCNPJValidator{ + + private AbstractCPRFValidator validadorCNPJ; + + @Test + public void testIsValido() { + + validadorCNPJ = AbstractCPRFValidator.create("11222333000181"); + + assertTrue(validadorCNPJ.isValido()); + + validadorCNPJ = AbstractCPRFValidator.create("11222333000182"); + + assertFalse(validadorCNPJ.isValido()); + } + +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/TestCPFValidator.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/TestCPFValidator.java new file mode 100644 index 0000000..b33a70e --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/TestCPFValidator.java @@ -0,0 +1,67 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:52:49 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:52:49 + * + */ + + +package org.jrimum.vallia; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Teste da classe Validator_CadastroDePessoaFísica. + * + * + * @author Gabriel Guimarães + * @author Gilmar P.S.L. + * @author Misael Barreto + * @author Rômulo Augusto + * + * @since 0.2 + * + * @version 0.2 + */ +public class TestCPFValidator{ + + private AbstractCPRFValidator validadorCPF; + + @Test + public void testIsValido() { + + validadorCPF = AbstractCPRFValidator.create("22233366638"); + + assertTrue(validadorCPF.isValido()); + + validadorCPF = AbstractCPRFValidator.create("22233366639"); + + assertFalse(validadorCPF.isValido()); + } + +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestBoletoCodigoDeBarrasDV.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestBoletoCodigoDeBarrasDV.java new file mode 100644 index 0000000..e261b40 --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestBoletoCodigoDeBarrasDV.java @@ -0,0 +1,83 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:53:16 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:53:16 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +/** + * Teste da classe BoletoCodigoDeBarrasDV. + * + * @author Gabriel Guimarães + * @author Gilmar P.S.L. + * @author Misael Barreto + * @author Rômulo Augusto + * @since 16/03/2007 + */ +public class TestBoletoCodigoDeBarrasDV{ + + private static final String CODIGO_DE_BARRAS_VALIDO = "1049300600000022061014044910000000020061732"; + + private AbstractDigitoVerificador codigoDeBarrasDV; + + @Before + public void setUp() throws Exception { + + codigoDeBarrasDV = new BoletoCodigoDeBarrasDV(); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroNullDisparaExcecao() { + codigoDeBarrasDV.calcule(null); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroEmBrancoDisparaExcecao() { + codigoDeBarrasDV.calcule(" "); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroComMenosDe43DigitosDisparaExececao() { + codigoDeBarrasDV.calcule("123456789"); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoStringComLetrasDisparaExececao() { + codigoDeBarrasDV.calcule("123A45B678C9"); + } + + @Test + public void quandoCodigoDeBarrasValidoDigitoCalculadoCorreto() { + assertEquals(6, codigoDeBarrasDV.calcule(CODIGO_DE_BARRAS_VALIDO)); + } + +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestBoletoLinhaDigitavelDV.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestBoletoLinhaDigitavelDV.java new file mode 100644 index 0000000..68c50e1 --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestBoletoLinhaDigitavelDV.java @@ -0,0 +1,105 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:53:28 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:53:28 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +/** + * Teste da classe BoletoLinhaDigitavelDV + * + * @author Gabriel Guimarães + * @author Gilmar P.S.L. + * @author Misael Barreto + * @author Rômulo Augusto + * + * @since JRimum 1.0 + * + * @version 1.0 + */ +public class TestBoletoLinhaDigitavelDV{ + + private AbstractDigitoVerificador dvLinhaDigitavel; + + @Before + public void setUp() throws Exception { + + dvLinhaDigitavel = new BoletoLinhaDigitavelDV(); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroNullDisparaExcecao() { + dvLinhaDigitavel.calcule(null); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoStringComLetrasDisparaExcecao() { + dvLinhaDigitavel.calcule("1A2B3C"); + } + + @Test(expected = IllegalArgumentException.class) + public void seNumeroSemPontoMenorQue9DigitosDisparaExcecao() { + dvLinhaDigitavel.calcule("12345678"); + } + + @Test(expected = IllegalArgumentException.class) + public void seNumeroComPontoMenorQue9DigitosDisparaExcecao() { + dvLinhaDigitavel.calcule("12345.678"); + } + + @Test(expected = IllegalArgumentException.class) + public void seNumeroSemPontoMaiorQue10DigitosDisparaExcecao() { + dvLinhaDigitavel.calcule("12345678901"); + } + + @Test(expected = IllegalArgumentException.class) + public void seNumeroComPontoMaiorQue10DigitosDisparaExcecao() { + dvLinhaDigitavel.calcule("12345.678901"); + } + + @Test + public void quandoNumeroNoFormatoCorretoCalculaDigitoCorretamente_String() { + + assertEquals(3, dvLinhaDigitavel.calcule("999977721")); + assertEquals(3, dvLinhaDigitavel.calcule("99997.7721")); + assertEquals(2, dvLinhaDigitavel.calcule("3053015008")); + assertEquals(2, dvLinhaDigitavel.calcule("30530.15008")); + } + + @Test + public void quandoNumeroNoFormatoCorretoCalculaDigitoCorretamente_Long() { + + assertEquals(0, dvLinhaDigitavel.calcule(0)); + assertEquals(3, dvLinhaDigitavel.calcule(999977721L)); + assertEquals(2, dvLinhaDigitavel.calcule(3053015008L)); + } +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCNPJDV.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCNPJDV.java new file mode 100644 index 0000000..6c5143b --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCNPJDV.java @@ -0,0 +1,101 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:53:39 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:53:39 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +/** + * Teste da classe CNPJDV. + * + * @author Gabriel Guimarães + * @author Gilmar P.S.L. + * @author Misael Barreto + * @author Rômulo Augusto + * + * @since JRimum 1.0 + * + * @version 1.0 + * + */ +public class TestCNPJDV{ + + private CNPJDV dvCNPJ; + + @Before + public void setUp() throws Exception { + + dvCNPJ = new CNPJDV(); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroNullDisparaExcecao() { + dvCNPJ.calcule(null); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroEmBrancoDisparaExcecao() { + dvCNPJ.calcule(" "); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoStringComLetrasDisparaExcecao() { + dvCNPJ.calcule("1A2B3C"); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroApenasZerosDisparaExcecao() { + dvCNPJ.calcule("000000000000"); + } + + @Test + public void quandoNumeroNoFormatoCorretoSemFormatacaoCalculaCorretamente() { + assertEquals(81, dvCNPJ.calcule("112223330001")); + } + + @Test + public void quandoNumeroNoFormatoCorretoComFormatacaoCalculaCorretamente() { + assertEquals(81, dvCNPJ.calcule("11.222.333/0001")); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroLongMaiorQue12DigitosDisparaExcecao() { + dvCNPJ.calcule(1112223330001L); + } + + @Test + public void quandoNumeroLongMenorQue12DigitosCalculaCorretamente() { + + assertEquals(81, dvCNPJ.calcule(112223330001L)); + assertEquals(65, dvCNPJ.calcule(2223330001L)); + } +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCPFDV.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCPFDV.java new file mode 100644 index 0000000..457b700 --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCPFDV.java @@ -0,0 +1,100 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:53:54 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:53:54 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +/** + * Teste da classe CPFDV. + * + * @author Gabriel Guimarães + * @author Gilmar P.S.L. + * @author Misael Barreto + * @author Rômulo Augusto + * + * @since JRimum 1.0 + * + * @version 1.0 + */ +public class TestCPFDV{ + + private CPFDV dvCPF; + + @Before + public void setUp() throws Exception { + + dvCPF = new CPFDV(); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroNullDisparaExcecao() { + dvCPF.calcule(null); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroEmBrancoDisparaExcecao() { + dvCPF.calcule(" "); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoStringComLetrasDisparaExcecao() { + dvCPF.calcule("1A2B3C"); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroApenasZerosDisparaExcecao() { + dvCPF.calcule("000000000"); + } + + @Test + public void quandoNumeroNoFormatoCorretoSemFormatacaoCalculaCorretamente() { + assertEquals(38, dvCPF.calcule("222333666")); + } + + @Test + public void quandoNumeroNoFormatoCorretoComFormatacaoCalculaCorretamente() { + assertEquals(38, dvCPF.calcule("222.333.666")); + } + + @Test(expected = IllegalArgumentException.class) + public void quandoNumeroLongMaiorQue9DigitosDisparaExcecao() { + dvCPF.calcule(2223336661L); + } + + @Test + public void quandoNumeroLongMenorQue9DigitosCalculaCorretamente() { + + assertEquals(38, dvCPF.calcule(222333666L)); + assertEquals(87, dvCPF.calcule(2333666L)); + } +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCodigoDeCompensacaoBancosBACENDV.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCodigoDeCompensacaoBancosBACENDV.java new file mode 100644 index 0000000..dcbb864 --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestCodigoDeCompensacaoBancosBACENDV.java @@ -0,0 +1,211 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + * + * Created at: 15/06/2008 - 12:00:00 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode + * usar esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob esta + * LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER TIPO, sejam + * expressas ou tácitas. Veja a LICENÇA para a redação específica a reger permissões + * e limitações sob esta LICENÇA. + * + * Criado em: 15/06/2008 - 12:00:00 + * + */ + +package org.jrimum.vallia.digitoverificador; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.lang.StringUtils; +import org.jrimum.utilix.text.Strings; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + + + +/** + * + *

+ * Testa o calculo dos códigos de compensação dos bancos. + *

+ * + * @author Gilmar P.S.L. + * @author Misael Barreto + * + * @since 0.2 + * + * @version 0.2 + */ + +public class TestCodigoDeCompensacaoBancosBACENDV { + + private CodigoDeCompensacaoBancosBACENDV dv4CodigoCompensacaoBanco = null; + + @Before + public void setUp() throws Exception { + dv4CodigoCompensacaoBanco = new CodigoDeCompensacaoBancosBACENDV(); + } + + @After + public void tearDown() throws Exception { + dv4CodigoCompensacaoBanco = null; + } + + @Test + public void testCalculeString() { + + assertEquals(9, dv4CodigoCompensacaoBanco.calcule("001"));//BancoDoBrasil + assertEquals(0, dv4CodigoCompensacaoBanco.calcule("104"));//CaixaEconomicaFederal + assertEquals(2, dv4CodigoCompensacaoBanco.calcule("237"));//Bradesco + assertEquals(7, dv4CodigoCompensacaoBanco.calcule("341"));//Itau + assertEquals(5, dv4CodigoCompensacaoBanco.calcule("356"));//BancoReal + assertEquals(0, dv4CodigoCompensacaoBanco.calcule("409"));//Unibanco + assertEquals(7, dv4CodigoCompensacaoBanco.calcule("422"));//BancoSafra + assertEquals(0, dv4CodigoCompensacaoBanco.calcule("748"));//Sicredi + + } + + @Test(expected = IllegalArgumentException.class) + public void testCalculeStringNull() { + + String codigo = null; + dv4CodigoCompensacaoBanco.calcule(codigo); + } + + @Test(expected = IllegalArgumentException.class) + public void testCalculeStringEmpty() { + dv4CodigoCompensacaoBanco.calcule(StringUtils.EMPTY); + } + + @Test(expected = IllegalArgumentException.class) + public void testCalculeStringBlank() { + dv4CodigoCompensacaoBanco.calcule(Strings.WHITE_SPACE); + } + + @Test(expected = IllegalArgumentException.class) + public void testCalculeStringNaoNumerico() { + dv4CodigoCompensacaoBanco.calcule("abc"); + } + + @Test + public void testCalculeLong() { + + assertEquals(9, dv4CodigoCompensacaoBanco.calcule(1L));//BancoDoBrasil + assertEquals(0, dv4CodigoCompensacaoBanco.calcule(104L));//CaixaEconomicaFederal + assertEquals(2, dv4CodigoCompensacaoBanco.calcule(237L));//Bradesco + assertEquals(7, dv4CodigoCompensacaoBanco.calcule(341L));//Itau + assertEquals(5, dv4CodigoCompensacaoBanco.calcule(356L));//BancoReal + assertEquals(0, dv4CodigoCompensacaoBanco.calcule(409L));//Unibanco + assertEquals(7, dv4CodigoCompensacaoBanco.calcule(422L));//BancoSafra + assertEquals(0, dv4CodigoCompensacaoBanco.calcule(748L));//Sicredi + } + + @Test + public void testCalculeInt() { + + assertEquals(9, dv4CodigoCompensacaoBanco.calcule(1));//BancoDoBrasil + assertEquals(0, dv4CodigoCompensacaoBanco.calcule(104));//CaixaEconomicaFederal + assertEquals(2, dv4CodigoCompensacaoBanco.calcule(237));//Bradesco + assertEquals(7, dv4CodigoCompensacaoBanco.calcule(341));//Itau + assertEquals(5, dv4CodigoCompensacaoBanco.calcule(356));//BancoReal + assertEquals(0, dv4CodigoCompensacaoBanco.calcule(409));//Unibanco + assertEquals(7, dv4CodigoCompensacaoBanco.calcule(422));//BancoSafra + assertEquals(0, dv4CodigoCompensacaoBanco.calcule(748));//Sicredi + } + + @Test(expected=IllegalArgumentException.class) + public void testCalculeCodigoDeCompensacaoMenorQueLimiteMinimo() { + dv4CodigoCompensacaoBanco.calcule(CodigoDeCompensacaoBancosBACENDV.LIMITE_MINIMO - 1); + } + + @Test(expected=IllegalArgumentException.class) + public void testCalculeCodigoDeCompensacaoMaiorQueLimiteMaximo() { + dv4CodigoCompensacaoBanco.calcule(CodigoDeCompensacaoBancosBACENDV.LIMITE_MAXIMO + 1); + } + + @Test + public void testIsCodigoValidoString() { + assertTrue(dv4CodigoCompensacaoBanco.isCodigoValido("001")); + } + + @Test + public void testIsCodigoValidoStringNull() { + + String codigo = null; + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido(codigo)); + } + + @Test + public void testIsCodigoValidoStringEmpty() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido(StringUtils.EMPTY)); + } + + @Test + public void testIsCodigoValidoStringBlank() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido(Strings.WHITE_SPACE)); + } + + @Test + public void testIsCodigoValidoStringNaoNumerico() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido("abc")); + } + + @Test + public void testIsCodigoValidoStringMenorQueLimiteMinimo() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido("000")); + } + + @Test + public void testIsCodigoValidoStringMaiorQueLimiteMaximo() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido("1000")); + } + + @Test + public void testIsCodigoValidoInt() { + assertTrue(dv4CodigoCompensacaoBanco.isCodigoValido(1)); + } + + @Test + public void testIsCodigoValidoIntMenorQueLimiteMinimo() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido(0)); + } + + @Test + public void testIsCodigoValidoIntMaiorQueLimiteMaximo() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido(1000)); + } + + @Test + public void testIsCodigoValidoLong() { + assertTrue(dv4CodigoCompensacaoBanco.isCodigoValido(1L)); + } + + @Test + public void testIsCodigoValidoLongMenorQueLimiteMinimo() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido(0L)); + } + + @Test + public void testIsCodigoValidoLongMaiorQueLimiteMaximo() { + assertFalse(dv4CodigoCompensacaoBanco.isCodigoValido(1000L)); + } +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestModulo.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestModulo.java new file mode 100644 index 0000000..9beb3fa --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestModulo.java @@ -0,0 +1,127 @@ +/* + * Copyright 2008 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by + * applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Created at: 30/03/2008 - 18:53:54 + * + * ================================================================================ + * + * Direitos autorais 2008 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar + * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob + * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER + * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a + * reger permissões e limitações sob esta LICENÇA. + * + * Criado em: 30/03/2008 - 18:53:54 + */ + +package org.jrimum.vallia.digitoverificador; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; + +public class TestModulo { + + private static Modulo modulo10 = new Modulo(TipoDeModulo.MODULO10); + + private static Modulo modulo11 = new Modulo(TipoDeModulo.MODULO11); + + @Test(expected = IllegalArgumentException.class) + public void quandoTipoDeModuloNullDisparaExcecao() { + new Modulo(null); + new Modulo(null, 0, 0); + } + + @Test + public final void testCalculeMod11LongIntInt() { + + assertEquals(2, Modulo.calculeMod11(654321, 2, 9)); + } + + @Test + public final void testCalculeMod11StringIntInt() { + + try { + + Modulo.calculeMod11("abc123", 2, 9); + + assertTrue(false); + fail("IllegalArgumentException esperado não ocorreu."); + + } catch (IllegalArgumentException iaex) { + + assertTrue(true); + System.out.println(iaex.getMessage()); + } + + assertEquals(2, Modulo.calculeMod11("654321", 2, 9)); + } + + @Test + public final void testCalculeSomaSequencialMod11() { + + assertEquals(112, Modulo.calculeSomaSequencialMod11("654321", 2, 9)); + } + + @Test + public final void testCalculeMod10LongIntInt() { + + assertEquals(4, Modulo.calculeMod10(123456, 1, 2)); + } + + @Test + public final void testCalculeMod10StringIntInt() { + + try { + + Modulo.calculeMod10("acb123", 1, 2); + + assertTrue(false); + fail("IllegalArgumentException esperado não ocorreu."); + + } catch (IllegalArgumentException iaex) { + + assertTrue(true); + System.out.println(iaex.getMessage()); + } + + assertEquals(4, Modulo.calculeMod10("123456", 1, 2)); + } + + @Test + public final void testCalculeSomaSequencialMod10() { + + assertEquals(24, Modulo.calculeSomaSequencialMod10("123456", 1, 2)); + } + + @Test + public final void testCalculeString() { + + assertEquals(2, modulo11.calcule("654321")); + + assertEquals(4, modulo10.calcule("123456")); + } + + @Test + public final void testCalculeLong() { + + assertEquals(2, modulo11.calcule(654321)); + + assertEquals(4, modulo10.calcule(123456)); + } + +} diff --git a/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestTipoDeModulo.java b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestTipoDeModulo.java new file mode 100644 index 0000000..b8739d9 --- /dev/null +++ b/jrimum-vallia/src/test/java/org/jrimum/vallia/digitoverificador/TestTipoDeModulo.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 JRimum Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + * + * Created at: 14/10/2013 - 16:03:53 + * + * ================================================================================ + * + * Direitos autorais 2013 JRimum Project + * + * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode + * usar esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma + * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que + * haja exigência legal ou acordo por escrito, a distribuição de software sob esta + * LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER TIPO, sejam + * expressas ou tácitas. Veja a LICENÇA para a redação específica a reger permissões + * e limitações sob esta LICENÇA. + * + * Criado em: 14/10/2013 - 16:03:53 + * + */ + + +package org.jrimum.vallia.digitoverificador; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * @author Gilmar P.S.L. + */ +public class TestTipoDeModulo { + + @Test + public void deve_retornar_10_como_valor_do_modulo(){ + + assertEquals(10, TipoDeModulo.MODULO10.valor()); + } + + @Test + public void deve_retornar_11_como_valor_do_modulo(){ + + assertEquals(11, TipoDeModulo.MODULO11.valor()); + } +}