password policy with regular expression

Password policy to match minimum 8 characters password with alphabets in combination with numbers or special characters

package regexp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Helper for password policy
 * 
 * @author ntallapa
 */
public class PwdPolicyVerifier {

	private Pattern pattern;
	private Matcher matcher;

	/**
	 * password policy to match 8 characters with alphabets in combination with numbers or special characters
	 *
	 * (?=.*[a-zA-Z]) means one or more alphabets, it can be small or CAPS
	 * (?=.*[0-9@#$%]) means one or more numerals or special characters
	 * {8,} means password length should be minimum 8
	 */
	private String pwd_policy = "((?=.*[a-zA-Z])(?=.*[0-9@#$%]).{8,})";

	public PwdPolicyVerifier() {
		pattern = Pattern.compile(pwd_policy);
	}

	/**
	 * Verify the validity of the given client password
	 * @param password
	 * @return boolean if test string passed the password policy or not
	 */
	public boolean verify(String password) {
		matcher = pattern.matcher(password);
		if (matcher.matches()) {
			System.out.println(password + " matched the regexp");
		} else {
			System.out.println(password + " didnt match the regexp");
		}
		return matcher.matches();

	}

	// some test cases
	public static void main(String[] args) {
		PwdPolicyVerifier pv = new PwdPolicyVerifier();
		pv.verify("welcome1");
		pv.verify("welcomeA");
		pv.verify("Welcome@");
		pv.verify("12341234");
		pv.verify("####$$$$");
		pv.verify("Welcome@12");
		pv.verify("WELCOME12");
	}
}

Output:

welcome1 matched the regexp
welcomeA didnt match the regexp
Welcome@ matched the regexp
12341234 didnt match the regexp
####$$$$ didnt match the regexp
Welcome@12 matched the regexp
WELCOME12 matched the regexp

Why would one need try-finally block combination

If we dont wanna handle the exception and instead propogate it up the hierarchy then we go for try-finally combination

how does polymorphism works within the constructors

First of all it is not good practice to call any instance methods inside the constructor, if we cannot avoid then do as little as possible.

What happens:

Assume we call a over-ridden method within the constructor and if that method manipulates data that has not been initialized (because constructor is not yet completed) yet then it will lead to disaster.

The only safe methods inside the constructor to call are final methods in base class.

How does DriverManager identify the type of driver loaded into JVM

Typical JDBC code to connect to the database is:

New Changes in JDK7

JDK7 is packaged with these new changes
– Small language changes
– NIO-2 Enhanced NIO
– invokedynamic
– other features

Small language Changes:

  • Now integer can accept binary format (along with octal and hexadecimal values)
<pre>int i = 0b10110
  • Switch statement can accept string variables. Since String object in Java is considered immutable, java community has come up with this concept

usage:

public int useSwitch(String strCase) {
switch(strCase) {
case "A":
return 1;
case "B":
return 2;
...
default:
return 10;
}
}
  • Inferring types with <>: while using generics RHS of stmt can be replaced with just <>

usage:

</pre>
List<String> list = new ArrayList<>();
<pre>

Note: No need to explicitly mentioned type on the RHS

  • Easy rethrow (replace multiple catch blocks with single catch block)

usage:

try {
// Reflective operations calling Class.forName,
// Class.newInstance, Class.getMethod,
// Method.invoke, etc.
...
} catch(final FileNotFoundException |
SQLException |
ClassNotFoundException) {
log(e);
throw e;
}

// try with resources
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(ds)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}

NIO-2 Enhanced NIO
NIO-2 (Enhanced Asynchronous NIO)

invokedynamic
Dynamic linking of method by the JVM is introduced

Other Features:
Fork joins (for recursive functionalities) – Multi process environment

different ways of getting a new object in Java

For now I can think of getting a new object in 4 different ways

  • ‘new’ operator
  • reflection
  • deserialization
  • cloning

Using new operator

MyClass mc = new MyClass();

– Here MyClass.java availability will be checked at compile time.
– This is the most common way of creating objects in day-2-day activities of java programmer

using Class.forName(“<fully-qualified-class-name>”)

Class c = Class.forName("com.techforum.MyClass");
c.newInstance();

– Here code will compile without any issues, ie, with/without presence of MyClass.java in the classpath. But at runtime if the class is not found then it will throw run time exception. For this reason we are forced to handle ClassNotFoundException, it is an compile time exception, while loading a class at runtime

Using clone method

MyClass mc = new MyClass();
MyClass mcClone = mc.clone();

– Here we should make sure MyClass.java is implementing Cloneable interface in order to clone its object.

Deserialization

ObjectInputStream ois = new ObjectInputStream(is);
// Here is 'is' is stream representing the flat file
// that is generated while serializing the object
MyClass object = (MyClass) ois.readObject();

– Here we should make sure we are implementing Serializable interface if we wanna serialize/deserialize object

Can we propagate exceptions in threads?

Prior to Java1.5 we cannot because the run() method in Runnable interface is written such that there is no return value as well as return exceptions in the method signature and hence the overridden method cannot propagate exceptions.

In Java1.5 SUN has released java.util.concurrent package in which alternative to Runnable i.e, Callable is introduced which can return any type and throw any subtype of Exception.

So,
– Using Runnable interface, one cannot propagate the exception and cannot return any value (return type is ‘void’), hence we should go for try-catch block to handle the exception
– Using Callable interface, we can propagate exception( or return a value) to the parent thread where we invoked the callable thread.

Sample code demonstrating the usage is uploaded in GITHub
https://github.com/ntallapa/TechForumWorkspace

When to use ArrayList and LinkedList in java

These two data structures(DS) operate exactly opposite in terms of read and write operations.

ArrayList: this is build from a basic array

read operation complexity: O(1)
This is always constant because we query for an element based on index and hence there is no search involved to reach to the required element.

write operation: O(n)
Any modifications will lead to the shift of elements in an array completely, it first creates new array with new size inserts elements prior to the position of element to be inserted, then inserts the current element and inserts remaining elements after it.
Ex: If we wanna add element at 1st position then we need to shift all elements 1 position to the right and then insert element at first position

Linked List: This is build from double linked list

read operation: O(n):
Since the traversal of this data structure is based on links we need to traverse from starting position till the point we encounter the element that we are searching for, since in BIG-O notation time complexity is worst case scenario, if the element we are looking for is at last position then read operation complexity will be proportional to the length of the DS, hence O(n)

write operation: O(1):
Just by changing the links we would be able to insert the element at any position at any place in the DS which consumes same time