commit inicial

master
fabiorj 2021-12-04 12:21:20 -03:00
parent 72153fd56a
commit 8dcb49d9d9
54 changed files with 8062 additions and 0 deletions

6
jrimum-utilix/.gitignore vendored 100644
View File

@ -0,0 +1,6 @@
/bin
/target
.classpath
.DS_Store
.project
.settings

View File

@ -0,0 +1,9 @@
Utilix Changelog
=============================
0.2.3 (2014/02/01) suport bopepo-0.2.3
---------------------------------------
**Improvement**
* #2: Remover classes relacionadas a LineOfFields

View File

@ -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.

View File

@ -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)

View File

@ -0,0 +1,193 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.rjconsultores</groupId>
<artifactId>jrimum-utilix</artifactId>
<packaging>jar</packaging>
<name>Projeto Utilix</name>
<version>1.0.0</version>
<description>Projeto open source de componentes de software para o domínio de negócios do Brasil.</description>
<url>http://www.jrimum.org/utilix</url>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<organization>
<name>Projeto JRimum</name>
<url>http://www.jrimum.org</url>
</organization>
<issueManagement>
<system>GitHub</system>
<url>https://github.com/jrimum/utilix/issues</url>
</issueManagement>
<scm>
<url>http://github.com/jrimum/utilix</url>
</scm>
<developers>
<developer>
<name>Gilmar P. S. L.</name>
<email>gilmatryx@gmail.com</email>
</developer>
<developer>
<name>Misael Barreto</name>
<email>misaelbarreto@gmail.com</email>
</developer>
<developer>
<name>Rômulo Augusto</name>
<email>romulomail@gmail.com</email>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
<version>1.6</version>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
<artifactId>java15</artifactId>
<version>1.0</version>
</signature>
</configuration>
<executions>
<execution>
<id>animal-sniffer</id>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<skipTests>false</skipTests>
<includes>
<include>org/jrimum/utilix/**/*</include>
</includes>
<excludes>
<exclude>org/jrimum/utilix/excludes/**/*</exclude>
<exclude>org/jrimum/utilix/**/*$*</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>attach-javadoc</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<charset>UTF-8</charset>
<docencoding>UTF-8</docencoding>
<docfilessubdirs>true</docfilessubdirs>
<show>private</show>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
<scope></scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<artifactId>mail</artifactId>
<groupId>javax.mail</groupId>
</exclusion>
<exclusion>
<artifactId>jms</artifactId>
<groupId>javax.jms</groupId>
</exclusion>
<exclusion>
<artifactId>jmxtools</artifactId>
<groupId>com.sun.jdmk</groupId>
</exclusion>
<exclusion>
<artifactId>jmxri</artifactId>
<groupId>com.sun.jmx</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<id>rj-releases</id>
<url>http://52.5.53.15:8081/nexus/content/repositories/releases/</url>
</repository>
</distributionManagement>
</project>

View File

@ -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;
/**
* <p>
* Classe utilitária para validações de arrays em geral.
* </p>
*
* <p>
* Inicialmente fornece métodos booleanos para verificação da existência de elementos.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*
* @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!");
}
/**
* <p>
* Indica se um dado array de chars tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Indica se um dado array de booleans tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Indica se um dado array de bytes tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Indica se um dado array de shorts tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Indica se um dado array de ints tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Indica se um dado array de longs tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Indica se um dado array de floats tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Indica se um dado array de doubles tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Indica se um dado array de objetos tem elementos sem gerar NPE.
* </p>
* <p>
* Resposta direta para o seguinte código:
* <code>(a != null && a > 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
/**
* <p>
* Retorna a quantidade de elementos de um dado array sem gerar NPE.
* </p>
* <p>
* Resposta direata para o seguinte código:
* <code>(a != null ? a.length : 0)</code>.
* </p>
*
* @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);
}
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*/
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.
*
* <p>
* Informando a classe há necessidade de informar o caminho do pacote, caso
* o recurso esteja nele.
* </p>
*
* @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);
}
}
}

View File

@ -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.
*
* <p>
* 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.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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 <code>Collection</code> passada por parâmetro é
* <code>null</code> ou <strong>não</strong> possui elementos e lança
* exceção caso não preencha estes requisitos.
*
* @param collection
* - Instância de <code>Collection</code> analisada.
*
* @throws IllegalArgumentException - Caso a coleção <strong>não</strong>
* seja <code>null</code> 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 <code>Collection</code> passado por parâmetro é
* <code>null</code> ou <strong>não</strong> possui elementos e lança
* exceção, com a mensagem informada, caso não preencha estes requisitos.
*
* @param collection
* - Instância de <code>Collection</code> analisada.
* @param message
* - Mensagem utilizada na exceção.
*
* @throws IllegalArgumentException - Caso a coleção <strong>não</strong>
* seja <code>null</code> 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 <code>Collection</code> passada por parâmetro
* <strong>não</strong> é <code>null</code> e possui elementos e lança
* exceção caso não preencha estes requisitos.
*
* @param collection
* - Instância de <code>Collection</code> analisada.
*
* @throws IllegalArgumentException
* - Caso a coleção seja <code>null</code> ou a coleção
* <strong>não</strong> 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 <code>Collection</code> passada por parâmetro
* <strong>não</strong> é <code>null</code> e possui elementos e lança
* exceção, com a mensagem informada, caso não preencha estes requisitos.
*
* @param collection
* - Instância de <code>Collection</code> analisada.
* @param message
* - Mensagem utiliada na exceção.
*
* @throws IllegalArgumentException
* - Caso a coleção seja <code>null</code> ou a coleção
* <strong>não</strong> 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 <code>Map</code> passado por parâmetro é <code>null</code>
* ou <strong>não</strong> possui elementos e lança exceção caso não
* preencha estes requisitos.
*
* @param map
* - Instância de <code>Map</code> analisada.
*
* @throws IllegalArgumentException - Caso o mapa <strong>não</strong> seja
* <code>null</code> 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 <code>Map</code> passado por parâmetro é <code>null</code>
* ou <strong>não</strong> possui elementos e lança exceção, com a mensagem
* informada, caso não preencha estes requisitos.
*
* @param map
* - Instância de <code>Map</code> analisada.
* @param message
* - Mensagem utilizada na exceção.
*
* @throws IllegalArgumentException - Caso o mapa <strong>não</strong> seja
* <code>null</code> 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 <code>Map</code> passado por parâmetro <strong>não</strong>
* é <code>null</code> e possui elementos e lança exceção caso não preencha
* estes requisitos.
*
* @param map
* - Instância de <code>Map</code> analisada.
*
* @throws IllegalArgumentException
* - Caso o mapa seja <code>null</code> ou o mapa
* <strong>não</strong> 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 <code>Map</code> passado por parâmetro <strong>não</strong>
* é <code>null</code> e possui elementos e lança exceção, com a mensagem
* informada, caso não preencha estes requisitos.
*
* @param map
* - Instância de <code>Map</code> analisada.
* @param message
* - Mensagem utiliada na exceção.
*
* @throws IllegalArgumentException
* - Caso o mapa seja <code>null</code> ou o mapa
* <strong>não</strong> 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 <code>Collection</code> passada por parâmetro é
* <code>null</code> ou <strong>não</strong> possui elementos.
*
* @param collection
* - Instância de <code>Collection</code> analisada.
* @return <code>!hasElement(collection)</code>
*
* @since 0.2
*/
public static boolean isEmpty(Collection<?> collection) {
return !hasElement(collection);
}
/**
* Verifica se a <code>Collection</code> passada por parâmetro
* <strong>não</strong> é <code>null</code> e possui elementos.
*
* @param collection
* - Instância de <code>Collection</code> analisada.
* @return <code>hasElement(collection)</code>
*
* @see #isEmpty(Collection)
*
* @since 0.2
*/
public static boolean isNotEmpty(Collection<?> collection) {
return hasElement(collection);
}
/**
* Verifica se o <code>Map</code> passado por parâmetro é <code>null</code>
* ou <strong>não</strong> possui elementos.
*
* @param map
* - Instância de <code>Map</code> analisada.
* @return <code>!hasElement(map)</code>
*
* @since 0.2
*/
public static boolean isEmpty(Map<?, ?> map) {
return !hasElement(map);
}
/**
* Verifica se o <code>Map</code> passado por parâmetro <strong>não</strong>
* é <code>null</code> e possui elementos.
*
* @param map
* - Instância de <code>Map</code> analisada.
* @return <code>hasElement(map)</code>
*
* @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.
* <p>
* Resposta direta para o seguinte código:
* <code>(c != null && !c.isEmpty())</code>.
* </p>
*
* @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.
* <p>
* Resposta direata para o seguinte código:
* <code>(m != null && !m.isEmpty())</code>.
* </p>
*
* @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.
* <p>
* Resposta direata para o seguinte código:
* <code>(c != null ? c.size() : 0)</code>.
* </p>
*
* @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.
* <p>
* Resposta direata para o seguinte código:
* <code>(m != null ? m.size() : 0)</code>.
* </p>
*
* @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 <strong>não</strong> é
* <code>null</code> ou se é vazio.
* <p>
* Caso o objeto seja <code>null</code>, lança
* <code>NullPointerException</code> com a mensagem informada no parâmetro
* <code>messageNullPointer</code> (primeiro parâmetro String). Caso o
* objeto não seja <code>null</code> e não possua elementos, lança
* <code>IllegalArgumentException</code> com a mensagem informada no
* parâmetro <code>messageIllegalArgument</code> (segundo parâmetro String).
* </p>
*
* @param collection
* - Objeto analisado.
* @param messageNullPointer
* - Mensagem utiliada na exceção
* <code>IllegalArgumentException</code>.
* @param messageIllegalArgument
* - Mensagem utiliada na exceção
* <code>IllegalArgumentException</code>.
*
* @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 <strong>não</strong> é
* <code>null</code> ou se é vazio.
* <p>
* Caso o objeto seja <code>null</code>, lança
* <code>NullPointerException</code> com a mensagem informada no parâmetro
* <code>messageNullPointer</code> (primeiro parâmetro String). Caso o
* objeto não seja <code>null</code> e não possua elementos, lança
* <code>IllegalArgumentException</code> com a mensagem informada no
* parâmetro <code>messageIllegalArgument</code> (segundo parâmetro String).
* </p>
*
* @param map
* - Objeto analisado.
* @param messageNullPointer
* - Mensagem utiliada na exceção
* <code>IllegalArgumentException</code>.
* @param messageIllegalArgument
* - Mensagem utiliada na exceção
* <code>IllegalArgumentException</code>.
*
* @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);
}
}
}

View File

@ -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;
/**
* <p>
* Serviços utilitários relacionados a manipulação de Objetos
* <code>Date, Calendar, GregorianCalendar.</code>
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @since 0.2
*
* @version 0.2
*/
public final class Dates {
/**
* <p>
* Representa uma data inexistente, pode ser usada em casos que não se pode
* usar <code>null</code> [ <em>é obtida da seguinte forma:
* <code>Calendar.set(1, 0, 1)</code></em> ]
* </p>
*/
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!");
}
/**
* <p>
* Retorna uma data inexistente, pode ser usada em casos que não se pode
* usar <code>null</code> [ <em>é obtida da seguinte forma:
* <code>Calendar.set(1, 0, 1)</code></em> ]
* </p>
*
* @return data invalida - 01/01/0001
*/
public static Date invalidDate(){
return (Date) DATE_NULL.clone();
}
/**
* <p>
* Compara uma dada data qualquer com a data invalida 01/01/0001.
* </p>
*
* @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);
}
}
/**
* <p>
* 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.
* </p>
*
* @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 <code>null</code>.
* @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;
}
/**
* <p>
* Converte um objeto <code>String</code> em um objeto
* <code>java.util.Date</code> a partir do formato de data especificado.
* </p>
* <p>
* Utiliza a sobrecarca
* <code>parse(String dateAsString, String dateFormat)</code> para
* realizar a conversão.
* </p>
*
* @param dateAsString
* - um valor de data em forma de <code>String</code>.
* @param dateFormat
* - formato de data em forma de <code>String</code>.
* @return Objeto <code>java.util.Date</code> convertido a partir do objeto
* <code>String</code>
*
* @throws IllegalArgumentException
* caso o objeto <code>String</code> 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));
}
/**
* <p>
* Converte um objeto <code>String</code> em um objeto
* <code>java.util.Date</code> através do objeto
* <code>java.text.DateFormat</code> especificado.
* </p>
*
* @param dateAsString
* - um valor de data em forma de <code>String</code>.
* @param dateFormat
* - formatador para objetos <code>java.util.Date</code>.
* @return Objeto <code>java.util.Date</code> convertido a partir do objeto
* <code>String</code>
*
* @throws IllegalArgumentException
* caso o objeto <code>String</code> 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;
}
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*
* @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 <T>
* Qualquer tipo.
*
* @return Não retorna nada, criado apenas para satisfazer alguma condição
* de retorno.
*/
public static <T> T throwIllegalArgumentException() {
throw new IllegalArgumentException();
}
/**
* Lança imediatamente uma {@linkplain IllegalArgumentException}.
*
* @param <T>
* 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> T throwIllegalArgumentException(String message) {
throw new IllegalArgumentException(message);
}
/**
* Lança imediatamente uma {@linkplain IllegalArgumentException}.
*
* @param <T>
* 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> T throwIllegalArgumentException(Throwable cause) {
throw new IllegalArgumentException(cause);
}
/**
* Lança imediatamente uma {@linkplain IllegalArgumentException}.
*
* @param <T>
* 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> T throwIllegalArgumentException(String message,
Throwable cause) {
throw new IllegalArgumentException(message, cause);
}
/**
* Lança imediatamente uma {@linkplain IllegalStateException}.
*
* @param <T>
* Qualquer tipo.
*
* @return Não retorna nada, criado apenas para satisfazer alguma condição
* de retorno.
*/
public static <T> T throwIllegalStateException() {
throw new IllegalStateException();
}
/**
* Lança imediatamente uma {@linkplain IllegalStateException}.
*
* @param <T>
* 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> T throwIllegalStateException(String message) {
throw new IllegalStateException(message);
}
/**
* Lança imediatamente uma {@linkplain IllegalStateException}.
*
* @param <T>
* 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> T throwIllegalStateException(Throwable cause) {
throw new IllegalStateException(cause);
}
/**
* Lança imediatamente uma {@linkplain IllegalStateException}.
*
* @param <T>
* 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> T throwIllegalStateException(String message,
Throwable cause) {
throw new IllegalStateException(message, cause);
}
/**
* Lança imediatamente uma {@linkplain UnsupportedOperationException}.
*
* @param <T>
* Qualquer tipo.
*
* @return Não retorna nada, criado apenas para satisfazer alguma condição
* de retorno.
*/
public static <T> T throwUnsupportedOperationException() {
throw new UnsupportedOperationException();
}
/**
* Lança imediatamente uma {@linkplain UnsupportedOperationException}.
*
* @param <T>
* 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> T throwUnsupportedOperationException(String message) {
throw new UnsupportedOperationException(message);
}
/**
* Lança imediatamente uma {@linkplain UnsupportedOperationException}.
*
* @param <T>
* 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> T throwUnsupportedOperationException(Throwable cause) {
throw new UnsupportedOperationException(cause);
}
/**
* Lança imediatamente uma {@linkplain UnsupportedOperationException}.
*
* @param <T>
* 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> T throwUnsupportedOperationException(String message,
Throwable cause) {
throw new UnsupportedOperationException(message, cause);
}
}

View File

@ -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;
/**
* <p>
* Locales não disponíveis em <code>java.util.Locale</code>.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*
* @since 0.2
*
* @version 0.2
*/
public final class Locales {
/**
* <p>
* Localização pt-BR.
* </p>
*/
public static final java.util.Locale BRASIL = new java.util.Locale("pt", "BR");
/**
* <p>
* Utility class pattern: classe não instanciável
* </p>
*
* @throws IllegalStateException
* Caso haja alguma tentativa de utilização deste construtor.
*/
private Locales() {
Exceptions.throwIllegalStateException("Instanciação não permitida!");
}
}

View File

@ -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.
*
* <p>
* 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.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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 <strong>não</strong> é
* {@code null}.
* <p>
* É o mesmo que usar o método {@code isNull} da forma
* {@code !isNull(obj)}, porém de forma mais legível.
* </p>
*
* @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
* <strong>false</strong>.
*
* @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 <strong>false</strong>.
*
* @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
* <strong>false</strong>.
*
* @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 <strong>false</strong>.
*
* @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 <strong>não</strong> seja.
*
* @throws IllegalArgumentException - Caso o objeto <strong>não</strong> 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 <strong>não</strong> seja.
*
* @param object
* - Objeto analisado
*
* @throws IllegalArgumentException - Caso o objeto <strong>não</strong> 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 <strong>não</strong> é 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 <strong>não</strong> é 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.
*
* <pre>
* whenNull(null, null) = null
* whenNull(null, "") = ""
* whenNull(null, "ex") = "ex"
* whenNull("abc", *) = "abc"
* whenNull(Boolean.TRUE, *) = Boolean.TRUE
* </pre>
*
* @param <T>
* 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> 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.
*
* <pre>
* whenNull(null, null, null) = null
* whenNull(null, "1", "2") = "1"
* whenNull("ok", "1", "2") = "2"
* </pre>
*
* @param <T>
* 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> 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);
}
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
*/
package org.jrimum.utilix;

View File

@ -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;
/**
* <p>
* Formatadores de data thread-safe. Para uma mesma categoria, os formatadores
* atualmente são diferenciados pelos seus separadores ("formato_separador")
* exemplos:
* <ul>
* <li>DDMMYY <code>default:ddMMyy</code></li>
* <li>DDMMYY_B <code>barr:dd/MM/yy</code></li>
* <li>DDMMYY_H <code>hyphen:dd-MM-yy</code></li>
* <li>DDMMYY_U <code>underline:dd_MM_yy</code></li>
* <li>HHMMSS_C <code>colon:"hh:mm:ss"</code></li>
* <li>etc.</li>
* </ul>
* </p>
*
* @author <a href=http://gilmatryx.googlepages.com/>Gilmar P.S.L.</a>
*
* @since 0.2
*
* @version 0.2
*/
public enum DateFormat implements Format<Date, SimpleDateFormat>{
/**
* <p>
* Formatador de datas no padrão <tt>"ddMMyy"</tt>.
* </p>
*/
DDMMYY("ddMMyy"),
/**
* <p>
* Formatador de datas no padrão <tt>"dd/MM/yy"</tt>.
* </p>
*/
DDMMYY_B("dd/MM/yy"),
/**
* <p>
* Formatador de datas no padrão <tt>"dd-MM-yy"</tt>.
* </p>
*/
DDMMYY_H("dd-MM-yy"),
/**
* <p>
* Formatador de datas no padrão <tt>"dd_MM_yy"</tt>.
* </p>
*/
DDMMYY_U("dd_MM_yy"),
/**
* <p>
* Formatador de datas no padrão <tt>"ddMMyyyy"</tt>.
* </p>
*/
DDMMYYYY("ddMMyyyy"),
/**
* <p>
* Formatador de datas no padrão <tt>"dd/MM/yyyy"</tt>.
* </p>
*/
DDMMYYYY_B("dd/MM/yyyy"),
/**
* <p>
* Formatador de datas no padrão <tt>"dd-MM-yyyy"</tt>.
* </p>
*/
DDMMYYYY_H("dd-MM-yyyy"),
/**
* <p>
* Formatador de datas no padrão <tt>"dd_MM_yyyy"</tt>.
* </p>
*/
DDMMYYYY_U("dd_MM_yyyy"),
/**
* <p>
* Formatador de datas no padrão <tt>"yyMMdd"</tt>.
* </p>
*/
YYMMDD("yyMMdd"),
/**
* <p>
* Formatador de datas no padrão <tt>"yy/MM/dd"</tt>.
* </p>
*/
YYMMDD_B("yy/MM/dd"),
/**
* <p>
* Formatador de datas no padrão <tt>"yy/MM/dd"</tt>.
* </p>
*/
YYMMDD_H("yy-MM-dd"),
/**
* <p>
* Formatador de datas no padrão <tt>"yy_MM_dd"</tt>.
* </p>
*/
YYMMDD_U("yy_MM_dd"),
/**
* <p>
* Formatador de datas no padrão <tt>"yyyyMMdd"</tt>.
* </p>
*/
YYYYMMDD("yyyyMMdd"),
/**
* <p>
* Formatador de datas no padrão <tt>"yyyy/MM/dd"</tt>.
* </p>
*/
YYYYMMDD_B("yyyy/MM/dd"),
/**
* <p>
* Formatador de datas no padrão <tt>"yyyy-MM-dd"</tt>.
* </p>
*/
YYYYMMDD_H("yyyy-MM-dd"),
/**
* <p>
* Formatador de datas no padrão <tt>"yyyy_MM_dd"</tt>.
* </p>
*/
YYYYMMDD_U("yyyy_MM_dd"),
/**
* <p>
* Formatador de datas no padrão <tt>"hhmmss"</tt>.
* </p>
*/
HHMMSS("hhmmss"),
/**
* <p>
* Formatador de datas no padrão <tt>"HHmmss"</tt>.
* </p>
*/
HHMMSS_24("HHmmss"),
/**
* <p>
* Formatador de datas no padrão <tt>"hh:mm:ss"</tt>.
* </p>
*/
HHMMSS_C("hh:mm:ss"),
/**
* <p>
* Formatador de datas no padrão <tt>"HH:mm:ss"</tt>.
* </p>
*/
HHMMSS_24C("HH:mm:ss"),
;
private final ThreadLocalFormat<SimpleDateFormat> DATE_FORMAT;
private DateFormat(String format) {
DATE_FORMAT = new ThreadLocalFormat<SimpleDateFormat>(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();
}
}

View File

@ -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;
/**
* <p>
* Formatadores thread-safe relacionados a moeda e números decimais.
* </p>
*
* @author <a href=http://gilmatryx.googlepages.com/>Gilmar P.S.L.</a>
*
* @since 0.2
*
* @version 0.2
*/
public enum DecimalFormat implements Format<Number, java.text.DecimalFormat>{
/**
* <p>
* Formatador de decimais pt-BR para <code>Float,Double,BigDecimal</code> no padrão
* <tt>"#,##0.0"</tt>. Exemplo: <tt>"1.500,9"</tt>.
* </p>
*/
NUMBER_D_BR("#,##0.0", DecimalFormatSymbols.BRASIL.copy()),
/**
* <p>
* Formatador de decimais pt-BR para <code>Float,Double,BigDecimal</code> no padrão
* <tt>"#,##0.00"</tt>. Exemplo: <tt>"1.500,99"</tt>.
* </p>
*/
NUMBER_DD_BR("#,##0.00", DecimalFormatSymbols.BRASIL.copy()),
/**
* <p>
* Formatador de decimais <code>Float,Double,BigDecimal</code> no padrão de
* moeda (Real pt-BR): <tt>"R$ #,##0.0"</tt>. Usado para formatar valores
* monetários em real com o prefixo R$, exemplo: R$ 10,0.
* </p>
*/
MONEY_D_BR("\u00A4 #,##0.0", DecimalFormatSymbols.BRASIL.copy()),
/**
* <p>
* Formatador de decimais <code>Float,Double,BigDecimal</code> no padrão de
* moeda (Real pt-BR): <tt>"R$ #,##0.00"</tt>. Usado para formatar valores
* monetários em real com o prefixo R$, exemplo: R$ 10,00.
* </p>
*/
MONEY_DD_BR("\u00A4 #,##0.00", DecimalFormatSymbols.BRASIL.copy()),
;
private final ThreadLocalLocalizedFormat<java.text.DecimalFormat, java.text.DecimalFormatSymbols> DECIMAL_FORMAT;
private DecimalFormat(String format, java.text.DecimalFormatSymbols formatSymbols) {
DECIMAL_FORMAT = new ThreadLocalLocalizedFormat<java.text.DecimalFormat, java.text.DecimalFormatSymbols>(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();
}
}

View File

@ -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;
/**
* <p>
* DecimalFormatSymbols com localização (Processo de localização) inicialmente
* do Brasil.
* </p>
*
* @author <a href=http://gilmatryx.googlepages.com/>Gilmar P.S.L.</a>
*
* @since 0.2
*
* @version 0.2
*/
public enum DecimalFormatSymbols {
/**
* DecimalFormatSymbols relacionados aos padrões pt-BR.
*/
BRASIL;
private final ThreadLocal<java.text.DecimalFormatSymbols> DF_SYMBOLS;
private DecimalFormatSymbols() {
DF_SYMBOLS = new ThreadLocal<java.text.DecimalFormatSymbols>() {
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;
}
};
}
/**
* <p>
* Cópia de símbolos utilizados em <code>BRASIL</code>.
* </p>
*
* @return símbolos - Instância de
* <code>java.text.DecimalFormatSymbols</code> estilo pt-BR
*
* @since 0.2
*/
public java.text.DecimalFormatSymbols copy() {
return (java.text.DecimalFormatSymbols) DF_SYMBOLS.get().clone();
}
}

View File

@ -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;
/**
* <p>
* Interface usada para objetos formatadores utilizados em leitura e escrita de
* textos.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
*
* @since 0.2
*
* @version 0.2
*/
public interface Format<T, F extends java.text.Format> {
/**
* <p>
* Formata um dado objeto para uma representação em string.
* </p>
*
* @param obj
* - Objeto a ser formatado.
* @return string - String formatada.
*/
String format(T obj);
/**
* <p>
* Transforma uma string formatada em um objeto correspondente.
* </p>
*
* @param text
* - Texto a ser analisado e transformado em objeto.
* @return objeto - Resultado da transformação da string.
*/
T parse(String text);
/**
* <p>
* Devolve uma cópia do formatador utilizado pela instância.
* </p>
*
* @return formatador - Cópia da instância do formatador.
*/
F copy();
}

View File

@ -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 <code>Strings</code>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @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:
*
* <pre>>
* <,;.:!*&%+-_<>[]\/
* </pre>
*
* @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 <code>String</code>, seja ela numérica ou
* não.
* <p>
* <code>removeStartWithZeros("00000") => 0</code><br />
* <code>removeStartWithZeros("00023") => 23</code><br />
* <code>removeStartWithZeros("02003") => 2003</code>
* <p>
*
* @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:
* <ul>
* <li>Agudo. ex.: á</li>
* <li>Grave. ex.: à</li>
* <li>Til. ex.: ã</li>
* <li>Trema. ex.: ä</li>
* <li>Circunflexo. ex.: â</li>
* </ul>
* e o Cedilha (ç).
* <p>
* Os acentos são removidos tanto para letras minúsculas como para letras
* maiúsculas.
* </p>
*
* @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 <code>String</code> passada por parâmetro não é
* <code>null</code> e não é numérica, ou seja, se a string não contém
* somente dígitos unicode.
* <p>
* Lança exceção, com a mensagem passada por parâmetro (segundo parâmetro
* String), caso não preencha estes requisitos.
* </p>
*
* @param value
* - String analisada
*
* @param message
* - Mensagem utiliada na exceção.
*
* @throws IllegalArgumentException - Caso a string seja <code>null</code> 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 <code>String</code> passada por parâmetro não é
* <code>null</code> e não é numérica, ou seja, se a string não contém
* somente dígitos unicode.
* <p>
* Lança exceção, com a mensagem passada por parâmetro (segundo parâmetro
* String), caso não preencha estes requisitos.
* </p>
*
* @param value
* - String analisada
*
* @throws IllegalArgumentException - Caso a string seja <code>null</code> 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 <code>String</code> passada por parâmetro não é
* <code>null</code>, não é vazia (<code>EMPTY</code>) e não possui apenas
* espaços em branco.
* <p>
* Lança exceção, com a mensagem passada por parâmetro (segundo parâmetro
* String), caso não preencha estes requisitos.
* </p>
*
* @param value
* - String analisada
*
* @param message
* - Mensagem utiliada na exceção.
*
* @throws IllegalArgumentException - Caso a string seja <code>null</code> ou
* caso a string seja vazia.
*
* @since 0.2
*/
public static void checkNotBlank(String value, String message) {
checkNotBlank(value, message, message);
}
/**
* Verifica se a <code>String</code> passada por parâmetro não é
* <code>null</code>, não é vazia (<code>EMPTY</code>) 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 <code>null</code> 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)}.
*
* <pre>
* whenBlank(null, null) = null
* whenBlank(null, "") = ""
* whenBlank("", "") = ""
* whenBlank("", "a") = "a"
* whenBlank(" ", "ex") = "ex"
* whenBlank("abc", *) = "abc"
* </pre>
*
* @param str
* String a testar e ser usada como valor de retorno se não for
* blank, pode ser <code>null</code>
* @param defaultValue
* - O valor padrão retornado caso a string testada seja blank,
* pode ser <code>null</code>
* @return <code>String</code> - Se não for blank, caso contrário
* <code>defaultValue</code>
*
* @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.
* <p>
* Verifica se a <code>String</code> passada por parâmetro não é
* <code>null</code> e não é numérica, ou seja, se a string não contém
* somente dígitos unicode.
* </p>
* <p>
* Lança <code>IllegalArgumentException</code>, com a mensagem definida em
* <code>messageNullPointer</code> (segundo parâmetro String), caso o valor
* passado seja <code>null</code>
* </p>
* <p>
* Lança <code>IllegalArgumentException</code>, com a mensagem definida em
* <code>messageIllegalArgument</code> (terceiro parâmetro String), caso o
* valor passado não seja numérico.
* </p>
*
* @param value
* - String analisada
*
* @param messageNullPointer
* - Mensagem utiliada na exceção.
*
* @param messageIllegalArgument
* - Mensagem utiliada na exceção.
*
*
* @throws IllegalArgumentException - Caso a string seja <code>null</code> 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.
* <p>
* Verifica se a <code>String</code> passada por parâmetro não é
* <code>null</code>, não é vazia (<code>StringUtils.EMPTY</code>) e não
* possui apenas espaços em branco.
* </p>
* <p>
* Lança <code>IllegalArgumentException</code>, com a mensagem definida em
* <code>messageNullPointer</code> (segundo parâmetro String), caso o valor
* passado seja <code>null</code>
* </p>
* <p>
* Lança <code>IllegalArgumentException</code>, com a mensagem definida em
* <code>messageIllegalArgument</code> (terceiro parâmetro String), caso o
* valor passado seja vazio.
* </p>
*
* @param value
* - String analisada
*
* @param messageNullPointer
* - Mensagem utiliada na exceção.
*
* @param messageIllegalArgument
* - Mensagem utiliada na exceção.
*
* @throws IllegalArgumentException - Caso a string seja <code>null</code> 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");
}
}

View File

@ -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;
/**
* <p>
* Abstração para o uso de formatadores thread-safe em enumerações.
* </p>
*
* @author <a href=http://gilmatryx.googlepages.com/>Gilmar P.S.L.</a>
*
* @since 0.2
*
* @version 0.2
*/
public abstract class ThreadLocalFormat<T> extends ThreadLocal<T> {
protected final String format;
protected ThreadLocalFormat(String format) {
Objects.checkNotNull(format, "INVALID NULL FORMAT!");
this.format = format;
}
}

View File

@ -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;
/**
* <p>
* Abstração para o uso de formatadores thread-safe com o uso de "localização"
* em enumerações.
* </p>
*
* @author <a href=http://gilmatryx.googlepages.com/>Gilmar P.S.L.</a>
*
* @since 0.2
*
* @version 0.2
*/
public abstract class ThreadLocalLocalizedFormat<T, S> extends ThreadLocalFormat<T> {
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;
}
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
*/
package org.jrimum.utilix.text;

View File

@ -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;
/**
* <p>
* Teste unitário para a classe utilitária de coleções.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @since 0.2
*
* @version 0.2
*/
public class TestCollections {
private static final Object EMPTY_OBJECT = new Object();
private static final Map<Object, Object> NULL_MAP = null;
private static final Collection<Object> NULL_COLLECTION = null;
private static final Map<Object, Object> MAP_COM_ELEMENTO;
private static final Collection<Object> COLLECTION_COM_ELEMENTO;
static {
MAP_COM_ELEMENTO = new HashMap<Object, Object>();
MAP_COM_ELEMENTO.put(EMPTY_OBJECT, EMPTY_OBJECT);
COLLECTION_COM_ELEMENTO = new ArrayList<Object>();
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());
}
}
}

View File

@ -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;
/**
* <p>
* Teste unitário para a classe utilitária de coleções.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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"));
}
}

View File

@ -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;
/**
* <p>
* Teste unitário para a classe utilitária de objetos
* </p>
*
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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")));
}
}

View File

@ -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;
/**
* <p>
* Teste unitário para a classe utilitária de strings.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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));
}
}

6
jrimum-vallia/.gitignore vendored 100644
View File

@ -0,0 +1,6 @@
/bin
/target
.classpath
.DS_Store
.project
.settings

View File

@ -0,0 +1,6 @@
Vallia Changelog
=============================
0.2.3 (2014/02/01) suport bopepo-0.2.3
---------------------------------------

View File

@ -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.

View File

@ -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)

View File

@ -0,0 +1,182 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.rjconsultores</groupId>
<artifactId>jrimum-vallia</artifactId>
<packaging>jar</packaging>
<name>Projeto Vallia</name>
<version>1.0.0</version>
<description>Projeto open source de componentes de software para o domínio de negócios do Brasil.</description>
<url>http://www.jrimum.org/vallia</url>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<organization>
<name>Projeto JRimum</name>
<url>http://www.jrimum.org</url>
</organization>
<issueManagement>
<url>http://github.com/jrimum/vallia/issues</url>
<system>GitHub</system>
</issueManagement>
<scm>
<url>http://github.com/jrimum/vallia</url>
</scm>
<developers>
<developer>
<name>Gilmar P. S. L.</name>
<email>gilmatryx@gmail.com</email>
</developer>
<developer>
<name>Misael Barreto</name>
<email>misaelbarreto@gmail.com</email>
</developer>
<developer>
<name>Rômulo Augusto</name>
<email>romulomail@gmail.com</email>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
<version>1.6</version>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
<artifactId>java15</artifactId>
<version>1.0</version>
</signature>
</configuration>
<executions>
<execution>
<id>animal-sniffer</id>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<descriptors>
<descriptor>src/main/assembly/jrimum-vallia-with-dependencies.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<skipTests>false</skipTests>
<includes>
<include>org/jrimum/vallia/**/*</include>
</includes>
<excludes>
<exclude>org/jrimum/vallia/excludes/**/*</exclude>
<exclude>org/jrimum/vallia/**/*$*</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>attach-javadoc</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<charset>UTF-8</charset>
<docencoding>UTF-8</docencoding>
<docfilessubdirs>true</docfilessubdirs>
<show>private</show>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>br.com.rjconsultores</groupId>
<artifactId>jrimum-utilix</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<id>rj-releases</id>
<url>http://52.5.53.15:8081/nexus/content/repositories/releases/</url>
</repository>
</distributionManagement>
</project>

View File

@ -0,0 +1,22 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>dep</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<useProjectArtifact>true</useProjectArtifact>
<unpack>true</unpack>
<scope>runtime</scope>
<excludes>
<exclude>commons-lang:commons-lang</exclude>
<exclude>log4j:log4j</exclude>
</excludes>
</dependencySet>
</dependencySets>
</assembly>

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @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 <code>códigoDoCadastro</code>.
*/
protected abstract void removeFormatacao();
/**
* Recupera uma instância de um validador para o cadastro de pessoa a partir
* de um identificador.
* <p>
* Primeiro é feita uma pré-validação que consiste em:
* <ul>
* <li>Verificar se o parâmetro não é nulo.</li>
* <li>Verificar se o parâmetro não é vazio.</li>
* <li>Verificar se o parâmetro está em algum formatador válido para
* cadastro de pessoa.</li>
* </ul>
* </p>
*
* @param codigoDoCadastro
* - identificador do cadastro de pessoa.
* @return uma instância de <code>AbstractCPRFValidator</code>.
* @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. <br />
* 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;
}
}

View File

@ -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.
*
* <p>
* O cadastro de pessoa jurídica tem as seguintes características:
* <ul>
* <li>Contém apenas números.</li>
* <li>Possui tamanho 14 sem formatação e 18 com formatação.</li>
* <li>Pode estar no formato ##.###.###/####-XX, onde XX é o dígito verificador.
* </li>
* </ul>
* </p>
* <p>
* A validação consiste em verificar essas características e se o dígito
* verificador é válido.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @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);
}
}

View File

@ -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.
*
* <p>
* O cadastro de pessoa física tem as seguintes características:
* <ul>
* <li>Contém apenas números.</li>
* <li>Possui tamanho 11 sem formatação e 14 com formatação.</li>
* <li>Pode estar no formato ###.###.###-XX, onde XX é o dígito verificador.</li>
* </ul>
* </p>
* <p>
* A validação consiste em verificar essas características e se o dígito
* verificador é válido.
* </p>
*
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @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);
}
}

View File

@ -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;
/**
* <p>
* Define o comportamento de classes que implementam uma lógica de cálculo de
* um dígito verificador.
* </p>
*
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @since 0.2
*
* @version 0.2
*/
public abstract class AbstractDigitoVerificador {
/**
* <p>
* Calcula o dígito verificador de um número de acordo com uma lógica
* específica.
* </p>
*
* @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;
/**
* <p>
* Calcula o dígito verificador de um número de acordo com uma lógica
* específica.
* </p>
* <p>
* Se não sobrescrito o retorno é sempre igual a 0 (zero).
* </p>
*
* @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;
}
}

View File

@ -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;
/**
* <p>
* Lógica de cálculo do dígito verificador do código de barras de um boleto.<br />
* A lógica funciona da seguinte forma:
* </p>
* <p>
* 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:
* </p>
* <p>
* Calcula-se o dígito verificador através da expressão <code>DV = 11 - R</code>
* , onde R é o resultado do cálculo do módulo.<br />
* Observação: O dígito verificador será 1 para os restos (resultado do módulo):
* 0 , 10 ou 1 (zero, dez, um).
* </p>
* <p>
* Obs.: A rotina de módulo utilizada é o módulo 11.
* </p>
*
* @see Modulo
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @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;
}
}

View File

@ -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;
/**
* <p>
* 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.
* </p>
* <p>
* Para fins de validação é preciso saber o seguinte:
* <ul>
* <li>O primerio campo tem tamanho 9 (nove) mais o dígito verificador.</li>
* <li>O segundo campo tem tamanho 10 (dez) mais o dígito verificador.</li>
* <li>O terceiro campo tem tamanho 10 (dez) mais o dígito verificador.</li>
* </ul>
* </p>
* <p>
* Obs1.: Todos os campos listados podem vir com um ponto (.) de separação
* exatamente após o dígito da 5ª posição. <br />
* Exemplo de linha digitável:<br />
* <code>99997.77213 30530.150082 18975.000003 1 10010000035000</code>
* </p>
* <p>
* O cálculo do dígito verificador é descrito através da expressão
* <code>DV = 11 - R</code>, onde R é o resultado do cálculo do módulo.<br />
* Obs1.: O dígito verificador será 0 (zero) se o resto (resultado do módulo)
* for 0 (zero). <br />
* Obs2.: A rotina de módulo utilizada é a módulo 10.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @since 0.2
*
* @version 0.2
*/
public class BoletoLinhaDigitavelDV extends AbstractDigitoVerificador {
/**
*<p>
* Módulo 10 utilizado no cálculo.
* </p>
*/
private static final Modulo modulo10 = new Modulo(TipoDeModulo.MODULO10);
/**
* <p>
* Expressão regular para validação do campo da linha digitável, aceita os
* seguintes formatos:
* </p>
* <ul>
* <li>#########</li>
* <li>#####.####</li>
* <li>##########</li>
* <li>#####.#####</li>
* </ul>
*/
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;
}
}

View File

@ -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;
/**
* <p>
* O cálculo do dígito verificador do CNPJ é realizado em duas etapas e é
* auxiliado pela rotina de módulo 11.
* </p>
* <p>
* Abaixo é demonstrado como esse cálculo é feito:
* </p>
* <h3>Exemplo para um número hipotético 11.222.333/0001-XX:</h3>
* <p>
* 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. <br />
* Para obter o primeiro dígito verificador deve-se seguir a seguinte lógica: <br />
* <br />
* 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,
* <code>DV = 11 - R</code>.
* </p>
* <p>
* 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.
* </p>
* <p>
* Obs.: O limite mínimo e máximo do módulo 11 são 2 e 9, respectivamente.
* </p>
*
* @see Modulo
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @since 0.2
*
* @version 0.2
*/
public class CNPJDV extends AbstractDigitoVerificador {
/**
* <p>
* Liminte mínimo do para cálculo no módulo 11.
*</p>
*/
private static final int LIMITE_MINIMO = 2;
/**
* <p>
* Liminte máximo do para cálculo no módulo 11.
*</p>
*/
private static final int LIMITE_MAXIMO = 9;
/**
* <p>
* Expressão regular para validação dos doze primeiros números do CNPJ sem
* formatação: <tt>"############"</tt>.
* </p>
*/
private static final String REGEX_CNPJ_DV = "\\d{12}";
/**
* <p>
* Expressão regular para validação dos doze primeiros números do CNPJ
* formatado: <tt>"##.###.###/####"</tt>.
* </p>
*/
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));
}
/**
* <p>
* </p>
* @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;
}
/**
* <p>
* Verifica se o número passado está em um formato aceitável para a realização do cálculo,
* ou seja:
* </p>
* <ul>
* <li>Não é null</li>
* <li>Não é vazio</li>
* <li>Apenas números</li>
* <li>Não é somente zeros</li>
* <li>Está no formato ##.###.###/#### ou ############</li>
* </ul>
*
* @param numero - CNPJ para ser validado
* @return <code>true</code> caso o número esteja em um formato válido; <code>false</code>,
* 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;
}
/**
* <p>
* Método auxiliar para o cálculo do dígito verificador.
* </p>
* <p>
* Calcula os dígitos separadamente.
* </p>
*
* @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;
}
}

View File

@ -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;
/**
* <p>
* O cálculo do dígito verificador do CPF é realizado em duas etapas e é
* auxiliado pela rotina de módulo 11.
* </p>
* <p>
* Abaixo é demonstrado como esse cálculo é feito:
* </p>
* <h3>Exemplo para um número hipotético 222.333.666-XX:</h3>
* <p>
* 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. <br />
* Para obter o primeiro dígito verificador deve-se seguir a seguinte lógica: <br />
* <br />
* 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,
* <code>DV = 11 - R</code>.
* </p>
* <p>
* 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.
* </p>
* <p>
* 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.
* </p>
*
* @see Modulo
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @author <a href="http://www.nordestefomento.com.br">Nordeste Fomento
* Mercantil</a>
*
* @since 0.2
*
* @version 0.2
*/
public class CPFDV extends AbstractDigitoVerificador {
/**
* <p>
* Liminte mínimo do para cálculo no módulo 11.
*</p>
*/
private static final int LIMITE_MINIMO = 2;
/**
* <p>
* Expressão regular para validação dos nove primeiros números do CPF sem
* formatação: <tt>"#########"</tt>.
* </p>
*/
private static final String REGEX_CPF_DV = "\\d{9}";
/**
* <p>
* Expressão regular para validação dos nove primeiros números do CPF
* formatado: <tt>"###.###.###"</tt>.
* </p>
*/
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;
}
/**
* <p>
* Verifica se o número passado está em um formato aceitável para a realização do cálculo,
* ou seja:
* </p>
* <ul>
* <li>Não é null</li>
* <li>Não é vazio</li>
* <li>Apenas números</li>
* <li>Não é somente zeros</li>
* <li>Está no formato ##.###.###/#### ou ############</li>
* </ul>
*
* @param numero - CNPJ para ser validado
* @return <code>true</code> caso o número esteja em um formato válido; <code>false</code>,
* 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;
}
/**
* <p>
* Método auxiliar para o cálculo do dígito verificador.
* </p>
* <p>
* Calcula os dígitos separadamente.
* </p>
*
* @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;
}
}

View File

@ -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;
/**
* <p>
* Cálculo para o dígito verificador do código de compensação dos bancos
* supervisionados pelo <a href="http://www.bcb.gov.br/?CHEQUESCOMPE">BACEN</a>
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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;
/**
* <p>
* Mesagem padrão para erro.
* </p>
*/
private static final String MSG = "O código de compensação do banco deve ser um número entre 1 e 999.";
/**
* <p>
* Calcula o dígito verificador para código de compensação passado.
* </p>
*
* @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()));
}
/**
* <p>
* Calcula o dígito verificador para o código de compensação passado.
* </p>
*
* @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);
}
/**
* <p>
* Calcula o dígito verificador para o código de compensação passado.
* </p>
*
* @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;
}
/**
* <p>
* Retorna se um código de compensação passado é válido, ou seja, se está entre os
* valores inteiros de 1 a 999.
* </p>
*
* @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;
}
/**
* <p>
* Retorna se um código de compensação passado é válido.
* </p>
*
* @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);
}
/**
* <p>
* Retorna se um código de compensação passado é válido.
* </p>
*
* @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);
}
}

View File

@ -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.
* <p>
* As rotinas tradicionais são Módulo 10 e Módulo 11.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*
* @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 <code>enum</code>
* da instância.
*
* <p>
* Se por um acaso a instância <code>enum</code> for nula uma
* <code>NullPointerException</code> será lançada. Caso a <code>enum</code>
* contenha um módulo não implementado por essa classe o retorno será
* <tt>-1</tt>
* </p>
*
* @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.
*
* <p>
* Executa o método <code>calculeSomaSequencialMod11</code> e aplica o
* resultado em % 11
* </p>
*
* @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);
}
/**
* <p>
* Executa o cáculo do módulo 11 com os limites definidos.
* </p>
*
* <p>
* Transforma o <code>numero</code> em string e executa o método
* calculeMod11
* </p>
*
* @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.
* <p>
* O módulo 11 funciona da seguinte maneira:
* </p>
* <p>
* 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.
* </p>
* <p>
* Exemplo para o número <tt>654321</tt>:
*
* <pre>
* +---+---+---+---+---+---+
* | 6 | 5 | 4 | 3 | 2 | 1 |
* +---+---+---+---+---+---+
* | | | | | |
* x7 x6 x5 x4 x3 x2
* | | | | | |
* =42 =30 =20 =12 =6 =2
* +---+---+---+---+---+-&gt;
* </pre
*
* </p>
*
* @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.
*
* <p>
* Transforma o <code>numero</code> em string e executa o método
* calculeMod10
* </p>
*
* @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.
*
* <p>
* Executa o método <code>calculeSomaSequencialMod10</code> e aplica o
* resultado em % 10
* </p>
*
* @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.
* <p>
* O módulo 10 funciona da seguinte maneira:
* </p>
* <p>
* 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.
* </p>
* <p>
* Exemplo para o número <tt>123456</tt>:
*
* <pre>
* +---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 |
* +---+---+---+---+---+---+
* | | | | | |
* x1 x2 x1 x2 x1 x2
* | | | | | |
* =1 =4 =3 =8 =5 =[ 3 &lt;= ( 1 + 2 &lt;==12 ) ] = 24
* +---+---+---+---+---+-&gt; = (24 / 10) = 3, resto 3; Então o módulo é igual a 3.
* </pre>
*
* </p>
*
* <p>
* Geralmente os limites para o módulo 10 são mínimo 1 e máximo 2 apenas.
* </p>
*
* @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 <code>limiteMaximo</code> e
* <code>limiteMinimo</code> com os valores padrões de acordo com a
* instância do módulo da classe.
*
* <p>
* Valores padrões: <br />
* <br />
* <code>MODULO10</code>: (limiteMinimo = 1 e limiteMaximo = 2)<br />
*
* <code>MODULO11</code>: (limiteMinimo = 2 e limiteMaximo = 9)<br />
* </p>
*
* @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);
}
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*
* @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();
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
*/
package org.jrimum.vallia.digitoverificador;

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L</a>
*/
package org.jrimum.vallia;

View File

@ -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 <code>AbstractCPRFValidator</code>.
*
*
* @author Gabriel Guimarães
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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);
}
}

View File

@ -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 <code>Validator_CadastroDePessoaJurídica</code>.
*
*
* @author Gabriel Guimarães
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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());
}
}

View File

@ -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 <code>Validator_CadastroDePessoaFísica</code>.
*
*
* @author Gabriel Guimarães
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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());
}
}

View File

@ -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 <code>BoletoCodigoDeBarrasDV</code>.
*
* @author Gabriel Guimarães
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
* @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));
}
}

View File

@ -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 <code>BoletoLinhaDigitavelDV</code>
*
* @author Gabriel Guimarães
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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));
}
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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));
}
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
* @author <a href="mailto:romulomail@gmail.com">Rômulo Augusto</a>
*
* @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));
}
}

View File

@ -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;
/**
*
* <p>
* Testa o calculo dos códigos de compensação dos bancos.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com">Gilmar P.S.L.</a>
* @author <a href="mailto:misaelbarreto@gmail.com">Misael Barreto</a>
*
* @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));
}
}

View File

@ -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));
}
}

View File

@ -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 <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*/
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());
}
}