java

Java – Credit Card Validation using Luhn Algorithm

I found code for credit card validation using Luhn algorithm on http://de.wikipedia.org/wiki/Luhn-Algorithmus#Java.
Thank you Wikipedia for it.
I modified code which can accept input as string & updated related changes.

public static boolean validateCardNumber(String ccNumber)
{
   int sum = 0;
   int length = ccNumber.length();
   for (int i = 0; i < length; i++) {

	   // get digits in reverse order
	   int digit = Integer.parseInt(""+ccNumber.charAt(length - i - 1));

	   // every 2nd number multiply with 2
	   if (i % 2 == 1) {
		   digit *= 2;
	   }
	   sum += digit > 9 ? digit - 9 : digit;
   }
   return sum % 10 == 0;
}
......
//it will print 'true' for below fake test card.
System.out.println(validateCardNumber("4444444444444448"));
......

Note: I hope that updated code will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Happy coding 🙂

Java Authenticator on a per connection basis.

You can perform authentication on per connection basis like below,


String userpass = username + ":" + password;
String basicAuth = "Basic " + org.apache.commons.codec.binary.Base64.encodeBase64String(userpass.getBytes("UTF-8"));
connection.setRequestProperty ("Authorization", basicAuth);

Happy Coding 🙂