Showing posts with label Java Code. Show all posts
Showing posts with label Java Code. Show all posts

Wednesday, January 23, 2008

Trust All Certificates

Need to establish an Https connection and don't care about validating the server's unsigned certificate? Don't want to mess with importing the server's certificate into a local keystore? This won't show you how to ignore those SSLHandshakeExceptions due to unsigned certs, but it will show you how to get rid of them all together!

Step 1:


Implement the X509TrustManager Interface as follows.

public class TrustEverythingTrustManager implements X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }

public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
}


Step 2:


Implement the HostnameVerifier Interface as follows.

public class VerifyEverythingHostnameVerifier implements HostnameVerifier {

public boolean verify(String string, SSLSession sslSession) {
return true;
}
}


Step 3:


Initialize an SSLContext with your TrustEverythingTrustManager and set the context as the default SSL socket factory on the HttpsURLConnection class.

TrustManager[] trustManager = new TrustManager[] {new TrustEverythingTrustManager()};

// Let us create the factory where we can set some parameters for the connection
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
// do nothing
}catch (KeyManagementException e) {
// do nothing
}

HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());


Step 4:


Open the connection and set your VerifyEverythingHostnameVerifier as the HostnameVerifier.

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new VerifyEverythingHostnameVerifier());



Thats it. Done and Done!

Monday, September 17, 2007

Determine Local IP Addresses

Here's a quick how-to for determining the IP Addresses your local machine has.

NOTE: This version (i've edited the post a couple of times now), will return all IPs associated with any network interface on the machine. Also, it's been tested on Windows and several flavors of linux.



public ArrayList getIPs() throws SocketException {
ArrayList ips = new ArrayList();
Enumeration m = NetworkInterface.getNetworkInterfaces();
while(m.hasMoreElements()) {
NetworkInterface ni = m.nextElement();
Enumeration addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
String ip = address.getHostAddress();

// filter out Inet6 Addr Entries
if (ip.indexOf(":") == -1) {
ips.add(ip);
}
}
}

return ips;
}

Thursday, September 13, 2007

Generic toString()

Do you ever want a descriptive toString() of a class you just created, but don't feel like taking the time to write it? Here's a generic toString() that uses the java.lang.reflect package and will work in any class.

Note:
This isn't the end-all generic toString() method. It does the bare minimum of printing out each field and its value with the added ability to handle null values and arrays.



@Override
public String toString() {
Field[] fields = getClass().getDeclaredFields();
AccessibleObject.setAccessible(fields,true);

StringBuffer sb = new StringBuffer();
sb.append("Class: " + this.getClass().getName() + "\n");

for (Field field : fields) {
Object value = null;
try {
value = field.get(this);
} catch (IllegalAccessException e) {continue;}

sb.append("\tField \"" + field.getName() + "\"\n");

Class fieldType = field.getType();
sb.append("\t\tType: ");

if (fieldType.isArray()) {
Class subType = fieldType.getComponentType();
int length = Array.getLength(value);
sb.append(subType.getName() + "[" + length + "]" + "\n");

for (int i = 0; i < length; i ++) {
Object obj = Array.get(value,i);
sb.append("\t\tValue " + i + ": " + obj + "\n");
}
} else {
sb.append(fieldType.getName() + "\n");
sb.append("\t\tValue: ");
sb.append((value == null) ? "NULL" : value.toString());
sb.append("\n");
}
}
return sb.toString();
}



Example Output

Class: GenericToString
- Field "myint"
Type: int
Value: 9
- Field "myDouble"
Type: java.lang.Double
Value: 999.095
- Field "myString"
Type: java.lang.String
Value: My String
- Field "myNullObject"
Type: java.lang.Object
Value: NULL
- Field "myStringArray"
Type: java.lang.String[2]
Value 0: one
Value 1: two
- Field "myintArray"
Type: int[3]
Value 0: 1
Value 1: 2
Value 2: 3
- Field "myHashMap"
Type: java.util.HashMap
Value: {val3=3, val1=val1, val2=val2}

Monday, August 13, 2007

Inject a String with Spring 2.0.6 and Maven2

Here's a real quick how-to for injecting a simple String value with Spring 2.0.6.

Configuration File


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="proxyHost" class="java.lang.String">
<constructor-arg>
<value>10.9.5.120</value>
</constructor-arg>
</bean>
</beans>


Java Code

public class stringInjectionExample {
private static final String SPRING_FILE = "sip.xml";
private static final String PROXY_HOST_BEAN_NAME = "proxyHost";

public void init() {
Resource resource = new ClassPathResource(SPRING_FILE);
BeanFactory factory = new XmlBeanFactory(resource);
String proxyHost = (String) factory.getBean(PROXY_HOST_BEAN_NAME);

System.out.println("Using ProxyHost: " + proxyHost);
}
}


Output

Using ProxyHost: 10.9.5.120


pom.xml

...

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>

<repositories>
<repository>
<id>Ibiblio</id>
<name>Maven2 Ibiblio Repository</name>
<url>http://mirrors.ibiblio.org/pub/mirrors/maven2</url>
<layout>default</layout>
</repository>
</repositories>

...

Saturday, July 21, 2007

Unit Testing Private Methods

So I've always thought that when it comes to writing unit tests against private methods, you have two options; use reflection, or break encapsulation. However, I just read an article that discusses this very topic in a good amount of detail. It points out 4 options for testing private methods.

If you're just interested in a summary of those 4 options, keep reading. Otherwise, here is the article I came across.

1. Don't Test Private Methods

  • If you're testing the class's non-private methods, then the private methods are being tested indirectly. You can maintain a high confidence level in your code w/o unit testing those private methods.

  • Feeling the need to test private methods may indicate that those methods should be moved into their own class. There they would become non-private (easily tested) and become reusable as well.


  • 2. Break Encapsulation
  • Changing the method from private to package-access is probably the quickest and easiest solution to testing private methods.

  • Seeing a private methods tells you something. When it's package-access, it doesn't speak so loudly.


  • 3. Use Reflection
  • Using reflection (java.lang.reflect), you can bypass encapsulation and gain access to the private method you'd like to test.

  • Your tests are more verbose. You've got to gain access to the private method before you can test it.


  • 4. Use an Inner Class
  • An inner class inside the class you're testing will have access to the private methods.

  • Your production class contains more than production code.


  • My $.02
    I really don't like the idea of using a nested test class, but I'd love to hear arguments promoting this option. Also, I don't like sacrificing encapsulation for the sake of testing. If you want to test the private method, do it right and use reflection. Other than that, I'm sure indirectly testing private methods has its time and place, but how often is determined by how you write your code.