Thursday, October 18, 2012

Java test Web credentials

    public static boolean testCredentials(final String aURL, final String auth) {
        try {
            URL url = new URL(aURL);
            String encodedLoginCreds = new Base64().encodeAsString(auth.getBytes());
            if (aURL.toLowerCase().startsWith("https")) {
                try {
                    HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();

                    TrustManager[] trustAllCerts = new TrustManager[]{new BusinessIntelligenceX509TrustManager()};

                    SSLContext sc;
                    try {
                        sc = SSLContext.getInstance("SSL");
                    } catch (NoSuchAlgorithmException noSuchAlgorithmException) {
                        return false;
                    }

                    HostnameVerifier hv = new BusinessIntelligenceHostnameVerifier();
                    try {
                        sc.init(null, trustAllCerts, new java.security.SecureRandom());
                    } catch (KeyManagementException keyManagementException) {
                        return false;
                    }

                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    HttpsURLConnection.setDefaultHostnameVerifier(hv);

                    httpsConnection.setDoInput(true);
                    httpsConnection.setRequestProperty("Authorization", "Basic " + encodedLoginCreds);

                    httpsConnection.setRequestMethod("GET");
                    httpsConnection.connect();

                    int code = httpsConnection.getResponseCode();
                    System.out.println("https: " + code);
                    if (code == 200)  return true;
                } catch (IOException ioe) {
                    System.out.println("ioe: " + ioe.getMessage());
                }
            } else if (aURL.toLowerCase().startsWith("http")) {
                try {
                    HttpURLConnection plainConnection = (HttpURLConnection) url.openConnection();
                    plainConnection.setRequestProperty("Authorization", "Basic " + encodedLoginCreds);
                    plainConnection.setRequestMethod("GET");
                    plainConnection.connect();

                    int code = plainConnection.getResponseCode();
                    System.out.println("plain: " + code);
                    if (code == 200)  return true;
                } catch (IOException ioe) {
                    System.out.println("ioe: " + ioe.getMessage());
                }
            }
        } catch (MalformedURLException mue) {
            System.out.println("mue: " + mue.getMessage());
        }
        return false;
    }

public class BusinessIntelligenceHostnameVerifier implements HostnameVerifier {

    @Override
    public boolean verify(String arg0, SSLSession arg1) {
        return true;
    }
}

public class BusinessIntelligenceX509TrustManager implements X509TrustManager {

    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
       return null;
    }

    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        // no-op
    }

    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        // no-op
    }
}

Tuesday, March 31, 2009

Extreme Guessing Programming

I had to deal with some bad code recently and my colleague just found a name for what I was seeing. He named it Extreme Guessing Programming and boy is he right...

Stay tuned for some examples...

Sunday, November 30, 2008

JSP get Browser name

private void getBrowserData(HttpServletRequest request)
{
String ag = request.getHeader("User-Agent");
ag = ag.toLowerCase();
if (ag.contains("msie")) browser = "IE";
else if (ag.contains("opera")) browser = "Opera";
else if (ag.contains("chrome")) browser = "Chrome";
else if (ag.contains("firefox")) browser = "Firefox";
else if (ag.contains("safari") && ag.contains("version")) browser = "Safari";
}

Here is the output for request.getHeader("User-Agent") for these browsers above.

Firefox: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4
Chrome: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.4.154.25 Safari/525.19
IE: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0; .NET CLR 2.0.50727)
Opera: Opera/9.62 (Windows NT 5.1; U; en-GB) Presto/2.1.1
Safari: Mozilla/5.0 (Windows; U; Windows NT 5.1; de-DE) AppleWebKit/525.26.2 (KHTML, like Gecko) Version/3.2 Safari/525.26.13

As you can see, some browsers share certain data. For example Mozilla as the first word. Chrome has Safari in there as well. Its beyond the scope of this post to go into WHY this happens so I just showed how to get around it.

This is exactly what the above method getBrowserData(HttpServletRequest request) does. The last else if for Safari is sure that Chrome is covered and is not the browser in question so it knows its Safari, but in case some OTHER browsers also have Safari in their User-Agent data this will cause problems. For example, Orca browser shows this data:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051214 Firefox/1.5
which is clearly identical to Firefox User-Agent data...

Wednesday, October 8, 2008

Javolution

This can best be described with the following sentence: If you use Java use Javolution!

Go to their API and read it... pick anything you can use and then use it!

Saturday, October 4, 2008

To Enum or not to Enum? ENUM!!!

Using public static final as enum has many problems, such as:

  • Not typesafe - Since a type is just an int you can pass in any other int value where a particular type is required, or add two types together (which makes no sense). This is particularly noticeable in C programs where you will find strange constants being used in un-related place and yet it seems to work, simply because the required constant and the provided constant share the same int value.
  • No namespace - You must prefix constants of an int enum with a string to avoid collisions with other int enum types.
  • Brittleness - Because such enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values may be uninformative - With int as enum (as in public static final int), if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is. In Java enums you get full type information along with value.

public enum FruitCategory { SWEET, CITRUS }

public enum Fruit {
APPLE
{ FruitCategory getCategory() {return FruitCategory.SWEET;} },
BANANA
{ FruitCategory getCategory() {return FruitCategory.SWEET;} },
ORANGE
{ FruitCategory getCategory() {return FruitCategory.CITRUS;} },

abstract FruitCategory getCategory();
}

Tuesday, September 30, 2008

Java Tricks

I've started reading some very interesting programming books and I found that, even though the content was awesome and I learned a lot more from these books than from years of programming hands-on experience, it was hard to go back and find a particular solution when needed. So I decided to compile my own list of Tricks and Tips so that I can easily find them when I need them the most.

Almost all of the tricks and tips here are extracted from one of the books listed on the left, but I will not specify which tip came from which book. I will also not copy/paste their content but rather create my own descriptions and titles. Furthermore, the tricks and tips in this list are just a tiny subset of everything found in these books. Thus, if you really want to learn something, you should consider purchasing these books at some point and maybe compiling a list of your own. I purchased all of them and I would have been sorry if i didn't.


This Blog is a part of the Tricks Series: