Skip to content

Instantly share code, notes, and snippets.

@paulo-raca
Created August 11, 2016 13:39
Show Gist options
  • Save paulo-raca/e61c4f4d72bbea0597e44f8de7f38c54 to your computer and use it in GitHub Desktop.
Save paulo-raca/e61c4f4d72bbea0597e44f8de7f38c54 to your computer and use it in GitHub Desktop.
CPF e CNPJ
public abstract class CNP {
private final int digits;
private final int[] weight;
public static final CNP CNPJ = new CNP(6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2) {
public String format(String cnp) {
cnp = normalize(cnp);
return cnp.substring(0, 2) + "." + cnp.substring(2, 5) + "." + cnp.substring(5, 8) + "/" + cnp.substring(8, 12) + "-" + cnp.substring(12);
};
};
public static final CNP CPF = new CNP(11, 10, 9, 8, 7, 6, 5, 4, 3, 2) {
public String format(String cnp) {
cnp = normalize(cnp);
return cnp.substring(0, 3) + "." + cnp.substring(3, 6) + "." + cnp.substring(6, 9) + "-" + cnp.substring(9);
};
};
private CNP(int... weight) {
this.digits = weight.length + 1;
this.weight = weight;
}
private int calculateNextDigit(String str) {
int sum = 0;
for (int i=0; i<str.length(); i++) {
int digito = Integer.parseInt(str.substring(i,i+1));
sum += digito*weight[weight.length-str.length()+i];
}
sum = 11 - sum % 11;
return sum > 9 ? 0 : sum;
}
public String addDigits(String cnpPrefix) {
cnpPrefix = normalize(cnpPrefix);
if (cnpPrefix.length()!=digits-2) {
throw new IllegalArgumentException("Expected number with " + (digits-2) + " digits, got " + cnpPrefix);
}
Integer digit1 = calculateNextDigit(cnpPrefix);
Integer digit2 = calculateNextDigit(cnpPrefix + digit1);
return cnpPrefix + digit1 + digit2;
}
public boolean isValid(String cnp) {
if ((cnp==null) || (cnp.length()!=digits)) {
return false;
}
return cnp.equals(addDigits(cnp.substring(0, digits-2)));
}
public String normalize(String cnp) {
return cnp.replaceAll("[./- ]", "");
}
public abstract String format(String cnp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment