Apache Cordova Google Analytics Plugin for Android 5

After a year of publishing mobile apps to the Android Marketplace, it seems the whole world is upgrading and if you blink an eye, you will be out of compliance.

So after firing up an emulator running the Android 5.0.1 SDK, all my mobile apps were crashing. I tracked down the error logs and found that there is an issue with the Google Analytics plugin I have been using.

——— beginning of crash
E/AndroidRuntime( 1448): FATAL EXCEPTION: GAThread
E/AndroidRuntime( 1448): java.lang.IllegalArgumentException: Service Intent must be e
xplicit: Intent { act=com.google.android.gms.analytics.service.START (has extras) }
E/AndroidRuntime( 1448): at android.app.ContextImpl.validateServiceIntent(Cont
extImpl.java:1674)
E/AndroidRuntime( 1448): at android.app.ContextImpl.bindServiceCommon(ContextI
mpl.java:1773)
E/AndroidRuntime( 1448): at android.app.ContextImpl.bindService(ContextImpl.ja
va:1751)
E/AndroidRuntime( 1448): at android.content.ContextWrapper.bindService(Context
Wrapper.java:538)
E/AndroidRuntime( 1448): at com.google.analytics.tracking.android.AnalyticsGms
CoreClient.connect(AnalyticsGmsCoreClient.java:82)
E/AndroidRuntime( 1448): at com.google.analytics.tracking.android.GAServicePro
xy.connectToService(GAServiceProxy.java:279)
E/AndroidRuntime( 1448): at com.google.analytics.tracking.android.GAServicePro
xy.createService(GAServiceProxy.java:163)
E/AndroidRuntime( 1448): at com.google.analytics.tracking.android.GAThread.ini
t(GAThread.java:95)
E/AndroidRuntime( 1448): at com.google.analytics.tracking.android.GAThread.run
(GAThread.java:493)

So, there are some major errors. After searching for some answers, the majority of the community alluded that upgrading to Google Analytics Version 3 would fix the issue. The plugin that was crashing the mobile app was using Google Analytics Version 2.

After searching for updates to the existing Google Analytics plugin, I found that it hadn’t been updated in years. There was a fork that tried to accomplish the upgrade to Google Analytics 3, yet it was so hacked with comments and test code that it was unusable without editing the files in the fork itself.

“The solution?”, you ask.

Well, I had to fork the original Google Analytics plugin and upgrade to Google Analytics SDK Version 3 myself.

You can find it here: https://github.com/bengicoder/GAPlugin

I just pointed to this fork, built and ran the mobile project, and now Google Analytics tracking is functional for Android 4 and 5. No crashes and a happy coder.

’nuff said.

Advertisements
Posted in Uncategorized | Leave a comment

Apache Cordova Netbeans Android Google Analytics Plugin

After researching on many different sites and troubleshooting many different errors and show stoppers, I was finally able to piece together a Google Analytics plugin for my Cordova Android Netbeans project.

First, here is the location of the plugin we shall use today.

Cordova Android GAPlugin @ GIT

First I had to add the git location of the plugin to my projects nbproject/plugins.properties file. I made sure to add the org.apache.cordova.network-information, org.apache.cordova.geolocation, com.google.playservices, and finally the com.phonegap.plugins.gaplugin addresses. I also place the GAPlugin address at the bottom of the list in case there are some dependency issues associated with the plugin installations during the build.

001-EditPluginsProperties

I also, manually ran the install of the GAPlugin from the command line. I’m not sure if this makes a difference, yet better safe than sorry.

002-ManualGAPluginInstallViaCLI

Also, edit platforms/android/AndroidManifest.xml and make sure that all the proper permissions are available in order for Google Analytics to make all the outbound calls it needs to.

003-AndroidManifestPermissions

In addition, edit the config.xml file and add the appropriate features associated with the GAPlugin installation.

004-Config-xmlFeatureAdditions

Next, after verifying that the GAPlugin has been installed locate the intrinsic GAPlugin.js script file.

005-GAPluginJSFileLocation

Copy that bad boy over to your project’s Site Root in the location of your choice. I just popped it in the default Site Root/js directory.

006-GAPluginJSFileCopyToSiteRoot

Now that the files are in place, we need to load the GAPlugin.js file into our page. Since I will be calling the GAPlugin.js code from my own js/index.js file, I need to make sure that GAPlugin.js is loaded first. So, here is the order I put it in.

007-IndexHTMLJSScriptFileOrderWithPlugin

Now, let’s look at app.initialize();

I took the basic index.js code that my initial NetBeans Cordova HTML5 project cam with and added the Google Analytics code to the onDeviceReady routine. I added plenty of logging so I could tell from the Android emulator logs that the code is working and completing successfully with error.


var gaPlugin;

var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {

console.info("CALLING Gooble Analytics");
gaPlugin = window.plugins.gaPlugin;
console.log("CALLING INIT")
gaPlugin.init(successHandler, errorHandler, "UA-********-*", 1);
gaPlugin.trackPage( nativePluginResultHandler, nativePluginErrorHandler, "index.html");
gaPlugin.trackEvent( nativePluginResultHandler, nativePluginErrorHandler, "Button", "Click", "event only", 1);
gaPlugin.exit(nativePluginResultHandler, nativePluginErrorHandler);
}

};

function successHandler()
{
console.log("INIT SUCCESS");
}

function errorHandler()
{
console.log("INIT FAILED");
}

function nativePluginResultHandler()
{
console.log("TRACKING SUCCESS");
}

function nativePluginErrorHandler()
{
console.log("TRACKING FAILED");
}

Clean, Build, and Run the Cordova project. Verify that all the plugins have been installed and are available in the final deployment otherwise there will some Class Not Found errors.

Upon deployment the logs pumped out the info I was looking for.


D/CordovaLog( 2727): file:///android_asset/www/js/index.js: Line 41 : CALLING Go
oble Analytics
I/Web Console( 2727): CALLING Gooble Analytics at file:///android_asset/www/js/i
ndex.js:41
D/CordovaLog( 2727): file:///android_asset/www/js/index.js: Line 43 : CALLING IN
IT
I/Web Console( 2727): CALLING INIT at file:///android_asset/www/js/index.js:43
I/Choreographer( 2727): Skipped 68 frames! The application may be doing too muc
h work on its main thread.
D/CordovaLog( 2727): file:///android_asset/www/js/index.js: Line 66 : INIT SUCCE
SS
I/Web Console( 2727): INIT SUCCESS at file:///android_asset/www/js/index.js:66
D/CordovaLog( 2727): file:///android_asset/www/js/index.js: Line 76 : TRACKING S
UCCESS
I/Web Console( 2727): TRACKING SUCCESS at file:///android_asset/www/js/index.js:
76
D/CordovaLog( 2727): file:///android_asset/www/js/index.js: Line 76 : TRACKING S
UCCESS
I/Web Console( 2727): TRACKING SUCCESS at file:///android_asset/www/js/index.js:
76
D/CordovaLog( 2727): file:///android_asset/www/js/index.js: Line 76 : TRACKING S
UCCESS
I/Web Console( 2727): TRACKING SUCCESS at file:///android_asset/www/js/index.js:
76

Seeing that there were plenty of success messages. I immediately surfed over to Google Analytics and lo and behold I was amazed to see that my my mobile app in the android emulator had indeed been tracked as can be seen in my Google Analytics Real-Time DashBoard.

008-GoogleAnalyticsRealTimeUser

Well, it took a couple of days to get this far and I believe those are the steps involved. I blogged about it quickly so I wouldn’t forget the finer points. After all, i will probably have to set up a new environment in the near future and instead of scanning through other blogs, GIT documentation, and stackoverflow.com I have put all that research into 1 place.

Now, time to figure out how to get the sinister Cordova Android AdMob/AdSense plugin working, LOL.

Posted in Analytics, Android, Cordova, Google, Mobile, NetBeans | Tagged , , , , , , , , , | Leave a comment

Java Coding Standards and Best Programming Practices

  1. Naming Conventions and Standards

    Note:

    The terms Pascal Casing and Camel Casing are used throughout this document.

    Pascal Casing – First character of all words are Upper Case and other characters are lower case. Example: BackColor

    Camel Casing – First character of all words, except the first word are Upper Case and other characters are lower case.
    Example: backColor

    1. Class Names – Use Pascal casing for Class names. Class names should be nouns and preferably whole words. Use of abbreviations should be discouraged unless the abbreviations are more commonly used than their full forms (like HTML, PDF etc).

    public class HelloWorld

    {

    ...
    }

    2. Method Names – Use Camel casing for Method names. Methods should be verbs and describe what the method achieves in business logic.

    public void sayHello(String userName)

    {

    ...
    }

    3. Variables – Use Camel casing for variables.

    int totalCount = 0;

    void sayHello(String userName)
    {
    String fullMessage = "Hello " + userName;

    ...

    }

    4. Interfaces – Use Pascal casing for Interfaces (e.g: interface InterestCalculator;)

    5. Constants – The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores. E.g: int MIN_WIDTH = 1;

    6. Do not use Hungarian notation to name variables. In earlier days most of the programmers liked it – having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:

    string m_sName;
    int nAge;

    However, in java coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.

    7. Variable names should be short yet meaningful. The usage of one letter variables must be avoided except for throwaway variables (e.g: inside a loop or counter).
    Good:

    String addressLine1;
    int baseSalary;

    for(int i = 0; i < count; i++ )

    {
    ...

    }

    If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.

    Not Good:

    int sal;
    String clr;

    8. Do not use underscores (_) for local variable names.

    9. Do not use variable names that resemble keywords.

    10. Prefix boolean variables, properties and methods with “is” or similar prefixes. Ex: private boolean isFinished; private boolean hasPrevInterest;

    11. Package names should follow the standard pattern

    com….
    Eg: com.coolcodings.search.funkytown.reporting;

    12. File name should match with class name with the same case (Pascal casing). For example, for the class HelloWorld, the file name should be HelloWorld.java.

DukeJuggle

      1. Indentation and Spacing

        1. Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.

        2. Curly braces ( {} ) should start in the same line and end in the same indentation level as the conditional clause.

        3. Use one blank line to separate logical groups of code.

        Good:
        String SayHello ( String userName) {
        StringBuilder fullMessage = new StringBuilder();
        fullMessage.append(“Hello “);

        If (username != null) {
        fullMessage .append(username);
        } else {
        // Append generic user label
        fullMessage.append(“Generic User”);
        }

        // return full message
        return fullMessage;

        }

        4. There should be one and only one single blank line between each method inside the class.

        5. Use a single space before and after each operator and brackets.

        Good:
        if ( isShowResult)
        {

        for ( int i = 0; i < 10; i++ )
        {

        //
        }

        }
        Not Good:
        if(showResult==true)

        {
        for(int i = 0;i<10;i++)

        {
        //

        }
        }

        6. Keep private member variables, properties and methods in the top of the file and public members in the bottom.

Duke_Int_Float_Char

  1. Good Programming practices

    1. Avoid passing data between screens using “Get” parameter. Use POST method wherever possible.

    2. Avoid writing very long methods. A method should typically have 1~40 lines of code. If a method has more than 40 lines of code, you must consider re factoring into separate methods.

    3. Method name should tell what it does. Do not use misleading names. If the method name is obvious, there is no need of documentation explaining what the method does.

    Good:
    void savePhoneNumber ( String phoneNumber )
    {

    // Check for valid phone number format, then save phone number.
    }

    Not Good:

    // This method will save the phone number.
    void saveNumber ( string aNumber )
    {

    // Save the phone number.
    }

    4. A method should do only ‘one job’. Do not combine more than one job in a single method, even if those jobs are very small.

    Good:

    // Save the address.
    // saveEmailAddress ( emailAddress);

    // Send an email to the supervisor to inform that the address is updated.
    // sendEmail ( emailAddress );

    Not Good:

    // Save address and send an email to the supervisor to inform that
    // the address is updated.

    // updateEmailAndNotify( address, email );

    void updateEmailAndNotify ( String address, String email )
    {
    // Job 1.

    // Save the address.
    // ...

    // Job 2.

    // Send an email to inform the supervisor that the address is changed.

    // ...

    }

    5. Always watch for unexpected values. For example, if you are using a parameter with 2 possible values, never assume that if one is not matching then the only possibility is the other value.

    Good:

    If ( memberType == eMemberTypes.Registered )

    {
    // Registered user… do something…

    }
    else if ( memberType == eMemberTypes.Guest )

    {
    // Guest user... do something…
    }
    else
    {

    // Un expected user type. Throw an exception

    throw new Exception (“Unexpected value “ + memberType.toString());
    // If we introduce a new user type in future, we can easily find
    // the problem here.
    }

    Not Good:

    If ( memberType == eMemberTypes.Registered )

    {
    // Registered user… do something…

    }
    else

    {
    // Guest user... do something…

    // If we introduce another user type in future, this code will

    // fail and will not be noticed.
    }

    6. Do not hardcode numbers. Use constants instead. Declare constant in the top of the file and use it in your code.

    However, using constants are also not recommended. You should use the constants in a config file or database so that you can change it later. Declare them as constants only if you are sure this value will never need to be changed.

    7. Do not hardcode strings. Use resource files.

    if(string.Compare(name,“john”,false) == 0)
    {

    //… name equals to john
    }

    10. Use String.isEmpty() instead of “” whenever possible.

    11. Avoid using member variables. Declare local variables wherever necessary and pass it to other methods instead of sharing a member variable between methods. If you share a member variable between methods, it will be difficult to track which method changed the value and when.

    12. Use enum wherever required. Explicitly assign values starting with None = 0 .

    Good:
    enum MailType {

    None=0,
    Html = 1,

    PlainText =2,
    Attachment =3

    }

    void SendMail (String message, MailType mailType) {

    switch ( mailType ) {

    case MailType.Html: // Do something break;

    case MailType.PlainText: // Do something break;

    case MailType.Attachment: // Do something break;

    default:

    // Do something break;
    }
    }

    Not Good:

    void sendMail (String message, String mailType)
    {

    switch ( mailType )
    {

    case "Html":

    // Do something break;
    case "PlainText":

    // Do something break;
    case "Attachment":

    // Do something break;
    default:

    // Do something break;
    }
    }

    12. Do not make the member variables public or protected. Keep them private and expose public/protected Properties.

    13. The event handler should not contain the code to perform the required action. Rather call another method from the event handler.

    14. Do not programmatically click a button to execute the same action you have written in the button click event. Rather, call the same method which is called by the button click event handler.

    15. Never hardcode a path or drive name in code. Get the application path programmatically and use relative path.

    16. Never assume that your code will run from drive “C:”. You may never know, some users may run it from network or from a “Z:”.

    17. If a wrong value found in the configuration file, application should throw an error or give a message and also should tell the user what are the correct values.

    18. Error messages should help the user to solve the problem if it is of an expected origin. Never give error messages like “Error in Application”, “There is an error” etc. Instead give specific messages like “Failed to update database. Please make sure the login id and password are correct.”

    19. When displaying error messages, in addition to telling what is wrong, the message should also tell what the user should do to solve the problem. Instead of message like “Failed to update database.”, suggest what should the user do: “Failed to update database. Please make sure the login id and password are correct.”

    20. Show short and friendly message to the user. But log the actual error with all possible information. This will help a lot in diagnosing problems.

    21. Whenever possible, do not have more than one class in a single file.

    22. Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate for refactoring. Split them logically into two or more classes.

    23. Avoid public methods and properties, unless they really need to be accessed from outside the class.

    24. Avoid passing too many parameters to a method. If you have more than 4~5 parameters, it is a good candidate to define a class or structure.

    25. If you have a method returning a collection, return an empty collection instead of null, if you have no data to return. For example, if you have a method returning an ArrayList, always return a valid ArrayList. If you have no items to return, then return a valid ArrayList with 0 items. This will make it easy for the calling application to just check for the “count” rather than doing an additional check for “null”.

    26. Logically organize all your files within appropriate folders. Use 2 level folder hierarchies. You can have up to 10 folders in the root folder and each folder can have up to 5 sub folders. If you have too many folders than cannot be accommodated with the above mentioned 2 level hierarchy, you may need re factoring into multiple packagesd.

    27. A good logging class needs to be create, which can be configured to log errors, warning or traces. If you configure to log errors, it should only log errors. But if you configure to log traces, it should record all (errors, warnings and trace). The log class should be written such a way that in future you can change it easily to log to Windows Event Log, SQL Server, or Email to administrator or to a File etc without any change in any other part of the application. Use the log class extensively throughout the code to record errors, warning and even trace messages that can help you trouble shoot a problem.

    28. Declare variables as close as possible to where it is first used. Use one variable declaration per line. Do not declare all variables at the top of the function.

    29. Use StringBuilder class instead of String when you have to manipulate string objects in a loop.

    Consider the following example:

    public String composeMessage (String[] lines)

    {
    String message = “”;

    for (int i = 0; i < lines.Length; i++)

    {
    message += lines [i];

    }

    return message;
    }

    In the above example, it may look like we are just appending to the string object ‘message’. But what is happening in reality is, the string object is discarded in each iteration and recreated and appending the line to it.

    If your loop has several iterations, then it is a good idea to use StringBuilder class instead of String object.

    See the example where the String object is replaced with StringBuilder.

    public String composeMessage (String[] lines)

    {
    StringBuilder message = new StringBuilder();

    for (int i = 0; i < lines.Length; i++)

    {
    message.append( lines[i] );

    }

    return message.toString();
    }

    30. Use Conditional operator (?:) instead of if else condition for assigning a value based on a given criteria where applicable
    Eg: allNumberTabs = fragments.Contains('A') ? "1" : "0";

    31. Whenever possible, use non synchronized data structures instead of their synchronized alternatives. E.g : Use StringBuilder instead of StringBuffer if there is no need for synchronization.

    32. Do not comment out code as the code is being refactored. Rather, delete the code to reduce confusion for later maintenance. The old code can always be retrieved from Source Control.

  1. Architecture

    1. Never access database from the UI pages. Always have a data layer class which performs all the database related tasks. This will help you support or migrate to another database back end easily.

    2. Use try-catch in your data layer to catch all database exceptions. This exception handler should record all exceptions from the database. The details recorded should include the name of the command being executed, stored proc name, parameters, connection string used etc. After recording the exception, it could be re thrown so that another layer in the application can catch it and take appropriate action.
    3. Always use caution when using database resources and pools. Make sure the connections are released and assigned to null after proper code execution.
    4. When architecting systems, make sure that there are no single point of failures for the sake of scaling applications.
    5. Whenever possible, include code reviews and usage of profiling tools in the project lifecycle so that quality is assured and there is less time spent in fixing the issues after the code is shipped.

  1. Comments

    Good and meaningful comments make code more maintainable.

    1. Summary information needs to be added after a method is defined (hitting /* on top of the method will automatically generate most part of it).

    2. Comments should be in the same level as the code (use the same level of indentation).
    3. Use // or /** for comments. Rather than using comments on every line, try to summarize what you are doing in a block so it is easier for maintenance.

    4. If you have to use some complex or weird logic for any reason, document it very well with sufficient comments.

    5. If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value.

    TODO Statements

    Utilize TODO statements in your JAVA code whenever you create code that is temporary (e.g. placeholders for unavailable features) or requires some attention at a future date. TODO statements show up in the most s IDEs and alerts other developers visiting the code that something requires TLC. Not doing so greatly increases the odds of missing things and creating bugs.

Duke-Throw-shirt-268x300

  1. Exception Handling

    1. Never do a catch exception and do nothing’. If the exception is hidden, one will never know if the exception happened or not. Do not use this as a handy method to ignore non-significant errors. You should always try to avoid exceptions by checking all the error conditions programmatically. In any case, catching an exception and doing nothing is not allowed. In the worst case, you should log the exception and proceed.

    2. In case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, method and class name etc.

    3. Always catch only the specific exception, not generic exception.

    Good:

    void SeadFromFile (string fileName)
    {

    try
    {

    //read from file.
    }

    catch (FileIOException ex)
    {

    // log error.

    // re-throw exception depending on your case. throw;
    }

    }

    Not Good:
    void ReadFromFile ( string fileName )

    try
    {

    // read from file.
    }

    catch (Exception ex)
    {

    // Catching general exception is bad... we will never know whether

    // it was a file error or some other error.
    // Here you are hiding an exception.

    // In this case no one will ever know that an exception happened.

    system.out.println(“An exception Occurred!”);
    }

    }

    4. There is no need to catch the general exception in all your methods. Leave it open and let the application crash. This will help you find most of the errors during development cycle. You can have an application level (thread level) error handler where you can handle all general exceptions. In case of an ‘unexpected general error’, this error handler should catch the exception and should log the error in addition to giving a friendly message to the user before closing the application, or allowing the user to ‘ignore and proceed’.

    5. When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved.

    Good:

    catch

    {
    // do whatever you want to handle the exception

    throw;
    }

    Not Good:

    catch (Exception ex)

    {
    // do whatever you want to handle the exception

    throw ex;

    }

    6. Do not write try-catch in all your methods. Use it only if there is a possibility that a specific exception may occur and it cannot be prevented by any other means. For example, if you want to insert a record if it does not already exists in database, you should try to select record using the key. Some developers try to insert a record without checking if it already exists. If an exception occurs, they will assume that the record already exists. This is strictly not allowed. You should always explicitly check for errors rather than waiting for exceptions to occur. On the other hand, you should always use exception handlers while you communicate with external systems like network, hardware devices etc. Such systems are subject to failure anytime and error checking is not usually reliable. In those cases, you should use exception handlers and try to recover from error.

    7. Do not write very large try-catch blocks. If required, write separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error message to the user.

    8. Write your own custom exception classes if required in your application. Avoid defining generic exception from Exception class and use more appropriate inbuilt exception classes (if not custom), where ever possible like ArgumentException for invalid parameters etc.

Posted in Best Practices, Java, Software Programming | Tagged , , , , , | Leave a comment

Java Web Application Security – XSS Combat Part 2

OWASP_Project_Header

A previous post from last year introduced a grand project that I was about to begin. After much analysis and searching I found a great solution that would secure my Java (JEE) application against XSS and SQLi attacks.

OWASP – The Open Web Application Security Project offers the Enterprise Security API
in order to aid me in my endeavor to make my application more robust and immune to the constant hacker threats that exist out there in cyberspace.

First, download the appropriate download for your web application architecture. Here we will show the example in Java.

002-esapi-dist-files

Here we have downloaded the esapi-2.0.1-dist zip archive. The built esapi-2.0.1.jar is ready to be placed in our own web application. Also, grab the basic properties files that are needed in order to get basic ESAPI security service running within your app.
I grabbed mine in the src\test\resources\esapi directory.

003-esapiPropertiesFileLocation

Copy the ESAPI.properties and validation.properties files as shown above. These should be placed in your java web application classpath.

After placing the jar and properties files in their respective locations of your web app, reload your web application and similar logging should be visible during the deployment process.

004-ESAPI-Init-Logging

Notice, that right out of the box the esapi-2.0.1.jar is attempting to initialize the two properties files that we place in our java app classpath. It seems that ESAPI is smart enough to attempt to locate the properties files in different locations on your computer.

Not found in ‘org.owasp.esapi.resources’ directory or file not readable: C:\Program Files\Apache Software Foundation\Tomcat\apache-tomcat-7.0.39-GA-8104\bin\ESAPI.properties
Not found in SystemResource Directory/resourceDirectory: .esapi\ESAPI.properties
Not found in ‘user.home’ (C:\Users\u0105457) directory: C:\Users\u0105457\esapi\ESAPI.properties
Loading ESAPI.properties via file I/O failed. Exception was: java.io.FileNotFoundException
Attempting to load ESAPI.properties via the classpath.
SUCCESSFULLY LOADED ESAPI.properties via the CLASSPATH from ‘/ (root)’ using current thread context class loader!

ESAPI looks in the server bin path, the SystemResource directory, the user home directory, and finally ESAPI.properties was loaded via the classpath. One out of four ain’t bad right?
The same search happens for the validation.properties file as well.

Now that ESAPI is setup, we can start using it in order to secure our application.
Begin by brushing up on the ESAPI javadocs.

In following posts, we shall dive into configuring ESAPI.properties and validation.properties to suit our needs.

Also, we shall get acclimated with the most useful methods to use in our fight against XSS.

See you then…

Posted in ESAPI, Java, OWASP, Security, SQL Injection, XSS | Tagged , , , , , , , , | Leave a comment

How to pump even more memory into your Apache Tomcat Web Server

Normally, I have been fine with my Apache Tomcat Web Server running at a mere half a gig which is shown on the Tomcat’s Server Status screen.

JVM

Free memory: 288.40 MB Total memory: 486.50 MB Max memory: 486.50 MB

Recently, my web applications have been so crazy that I needed to allocate even more memory to my Tomcat.
How to do it?

Edit your $TOMCAT_HOME\bin\catalina.bat and add the line “set CATALINA_OPTS=-Xmx1g” at the top of the file or wherever appropriate as such:
TomcatEditCatalinaDotBatWith1GMem

Now, check out the Tomcat Server Status page and look at the difference. Drum roll please………………………………………

TomcatServerStatusWith1GMem

That’s more like it. Time to run 20, 50, even 100 apps from a single Tomcat Web Server instance.
Screw all your other Windows or Linux apps, give it all to Tomcat for he keeps you safe at night.

You shall never be afraid of the boogy man again.

Posted in Apache, Server Technology, Tomcat, Tomcat, Tomcat | Tagged , , , , , | Leave a comment

Combating XSS in a Java Web Application

Recently, out Java Web App went through a Veracode security scan. Since the application is used by over 25,000 users world wide, I do see it as important that this scan took place. Although, I have placed some anti-XSS (Cross site scripting) code into the app over time due to other security professionals evaluating our software, Veracode brought to light over 300 vulnerabilities in the software that I was quite aware of.

Therefore, I am now obliged to address these vulnerabilities and provide our software a passing score of at least 70 in the eyes of Veracode.

Over the next few weeks, I will be submitting detailed code and instructions on how to do this.

Let the hackers beware, for javaclaus draws near.

Posted in Java, Security, SQL Injection, XSS | Tagged , , , , , | Leave a comment

Earth Day on the Hudson

As the weather warms up and the flowers erupt from the earth in new and refreshed life. My walk to work is both cheery and uplifting. As the wind wisks past me and molds my hair back into a pompadour, I carry on towards my office letting not even nature’s morning wrath hold me back from a productive day.

“The Hudson seems a bit greener than usual.”, I hear an onlooker say.

Gazing over to the river I can verify his claim. THe river possesses a translucent greenish hue as it flows past Manhatten and Hoboken in tandem. The boats steam by one after another both up and down the mighty behemoth of a river.

As I push forward to enter my building I take one final breath of the river air to guide me through this day.

Posted in Uncategorized | Leave a comment