Tuesday, October 16, 2012

Making https connection from Android client if your CA provider is not trusted by Android

Android does not recognize all the SSL certificate issuers. If your certificate happens to be issues by one of them or you have a self signed certificate and you want your android application to talk to the server,  the code can be a bit tricky.  Android requires a special version of the keystore.  Here are 5 steps you need to perform to make it work.

1) Download the correct version of bouncycastle. For clients running API level 8, version 1.46 works fine. It can be downloaded from  http://ftp.uasw.edu/pub/security/bouncycastle/release1.46/bcmail-jdk13-146.jar

2) Extract the certificate from the server using the following command:

echo | openssl s_client -connect server.name.com:443 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem

3) Run the following command to create the keystore

keytool -importcert -v -trustcacerts -file mycert.pem  \
-alias server.name.com -keystore mykeystore.bks \
-provider org.bouncycastle.jce.provider.BouncyCastleProvider \
-providerpath /path/to/your/Download/bcprov-jdk15on-146.jar  \
-storetype BKS -storepass mypass

4) Copy the file to the Android resource directory under the name res/raw/mykeystore.bks

5) Add the following code snippet in your application and have it executed before you make the https url connection.
    public void setDefaultSSL () {
        Context con = getApplicationContext() ;
        TrustManagerFactory tmf;
        try {
            tmf = TrustManagerFactory.getInstance("X509");
            KeyStore ks = KeyStore.getInstance("BKS");
            InputStream in = con.getResources().openRawResource(R.raw.mykeystore);
            ks.load(in, "mypass".toCharArray());
            in.close();
            tmf.init(ks);
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            Log.d("HTTPS", "Setting custom trust store");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Once you have invoked the above code segment, you can make url connection as you normally do and you should be fine.  Here is a code snippet to do that. One point to note in this code below is that the keepAlive header. Without this, you may experience intermittent issues where the response from the call is empty.

    private String getServerContent(String url_str ) throws Exception {
        System.setProperty("http.keepAlive", "false");
        URL url = new URL(url_str);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url
                .openConnection();
        urlConnection.setDoInput(true);
        InputStream ins = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                ins, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        ins.close();
        urlConnection.disconnect();
       
        return sb.toString();

    }
 

Tuesday, September 4, 2012

Weblogic disabling freemark debug messages

Recently we migrated our applications to Oracle weblogic server (OAS 11g) and we noticed that the application log file is filled with debug messages from freemark like the one below:
<Notice> <Stdout> <<BEA-000000> <DEBUG   13467   [freemark] ():
I searched for options to turn off freemark using the logger option and it did not work.  The reason could be that the application is not using and logging configuration (no log4j or jdk logging) and oracle diagnostic logging is picking up the logs.

We also have stdout redirecting to the log file.  We have the logger configuration set to debug level as it is the development environment.  However, I do not want the freemarker logging to fill up the log file.  The solution I ended up implementing was to create a log filter to disable the freemarker log messages.   I am not sure if this is the best way or not, but this is the only way I could turn off the freemarker debug message and leave the rest of the debug messages on.

Here is the log filter configuration.  The create a log filter click on the domain name on the weblogic console and go to Configuration->LogFilters
Here is the log file configuration that I used in the development environment. (For production environment, I would recommend setting the log levels to Warning so the log files are not clogged up with debug messages)

Thursday, November 10, 2011

Cross Platform Mobile Application Development Framework Comparision Chart






Corona

Corona lets developers use integrated Lua, layered on top of
Objective-C, to build graphically rich applications that are also lightweight
in size and quick in development time.


Phone Gap (Adobe)


The mobile framework allows web developers to natively target all
smartphone with a single codebase (JavaScript, HTML and CSS) by enabling a
Foreign Function Interface (FFI) to an embedded WebView or Webkit on the
device.


Rhomobile

(Motorola Solutions company)


Rhodes is a framework for building native applications that can run
on a variety of smartphones. Rhodes uses a Model View Controller pattern.
Views are written in HTML


Titanium Mobile


Appcelerator Titanium Mobile is a web based application framework
solutions allowing web developers to apply existing skills to create native
applications for iPhone and Android using the familiar JavaScript syntax.
Developers will also have to learn the extensive Titanium API. Wikipedia
notes that the term cross-compiler is misleading as the titanium engine
interprets the code during run time.




Tuesday, October 11, 2011

Using PHPMailer and Gmail to send email

If you are developing applications using PHP and you need to send email you can use the PHPMailer() class in PHP. Using a publicly available SMTP server to send the email is much easier than trying to setup your own email server. The following code snippet shows the various settings for the mailer.
The code assumes that you have PHP 5.x version and you have class.phpmailer.php file in the include directory.
Google uses ssl for the smtp connection. In order for this example to work with google smtp server, you need to enable ssl in your php.ini file by adding a line that says extension=php_openssl.dll

If you are not sure of the exact location of the php.ini file and you are using xampp, you can find the location of the php.ini file by navigating to http://localhost/xampp/phpinfo.php on your browser and look for the text "Loaded Configuration File". Once you find the file, edit it and look for the text "extension=php_openssl.dll". If the text is not found in your file, add a new line at the end of the file with the above text.
IsSMTP();
$mail->SMTPDebug = 1; // 1 tells it to display SMTP errors and messages, 0 turns off all errors and messages, 2 prints messages only.

$mail->Host = "ssl://smtp.gmail.com"; // specify main and backup server
$mail->Port = 465; // set the port to use
$mail->SMTPAuth = true; // turn on SMTP authentication

$mail->Username = 'user@gmail.com'; // replace this with your email acct
$mail->Password = 'userPassword'; // replace this with your password

$mail->From = 'jmeslie@gmail.com';
$mail->FromName = 'Jean Meslie';
$mail->AddAddress('receipient@yahoo.com', 'Receiver');
$mail->AddReplyTo('user@gmail.com'); // Adds a “Reply-to' address. Un-comment this to use it.
$mail->Subject = 'test message';
$mail->Body = 'message body goes here. This message was sent at '. time();

if ($mail->Send() == true) {
echo 'The message has been sent at '. time();
}
else {
echo 'The email message has NOT been sent for some reason. Please try again later.';
echo 'Mailer error: ' . $mail->ErrorInfo;
}
?>

Monday, October 3, 2011

Recreate GRANTS to user in oracle without dba privilege

If you want to get list of grants made to tables and you want to recreate the user permissions in a different environment, the easy way to generate a script is to use the dbms_metadata.get_granted_ddl function as described here. However, if you do not have DBA privilege on the database you will not be able to use that method. Here is a simple sql that you can use to generate a script that will work in most common situations. This just relies on the TABLE_PRIVILEGES table.
select replace('GRANT ' || decode(select_priv,'Y','SELECT','') || decode(insert_priv,'A',',INSERT','') || decode(delete_priv,'Y',',DELETE','') || decode(update_priv,'Y',',UPDATE','') || decode(references_priv,'Y',',REFERENCES','') || decode(alter_priv,'Y',',ALTER','') ||' ON '|| owner || '.' || table_name || ' TO ' || GRANTEE ||';','GRANT ,','GRANT ') from TABLE_PRIVILEGES where owner= 'OWNER' order by table_name, grantee;

Tuesday, September 27, 2011

window.onload being used in multiple places within the same application included

Recently one of my team members ran into an issue where we had used
the window.onload to dynamically set some values in a cookie object.
Our application handles multiple javascript files and we had used
window.onload in another jsp also for another reason.

So,when multiple jsp files are trying to add different functions to the window.onload event, only the last function was executing. We developed a workaround by adding the function that chains the onload event functions. Below snippet gives an example of how we solved it.

-
function addLoadEvent(functionName) {
var firstonload = window.onload;

if (typeof window.onload != 'function') {
window.onload =
functionName;
}
else {
window.onload = function() {
if (
firstonload ) {
firstonload();
}
functionName();
}
}
}


and the actual function definition is in the original jsp and this
function is called from there. So the first time window.onload may
not be a function so we are setting it, On subsequent assignments,
window.onload exists, so whatever it holds will be wrapped up with the
new function. the list grows like that...

Tuesday, June 7, 2011

Struts2 navigate away from error pages

Struts 2 provides a nice workflow interceptor that makes sure there are no validation errors before allowing the interceptor chain to continue.

This will also prevent the user from navigating away to a different method in the same action. Sometimes that is not the desired behavior we like. For example, if the user is editing an item and there is a validation error and the user does not want to fix the validation error, however they choose to navigate to a different page on the same action, the workflow interceptor will prevent the user and put them back to the edit page.

If the desired behavior is to let them proceed to to another page, you can exclude those methods in the interceptor configuration similar to the following example.
<interceptor-ref name="defaultLoginStack" >
         <param name="validation.excludeMethods">doInput,doList</param>
         <param name="workflow.excludeMethods">doInput,doList</param>
</interceptor-ref>
In the above example, if the user tries to access the doList or doInput methods the validation will be skipped and the workflow will allow to continue even if the previous page had errors.