Pages

Friday, May 30, 2014

Switch Case using String in Java

Switch case in Java using string values is a little tricky. The concept seems so simple when we think of a logic, only to surprise you later that it is not so simple and it seems like an impossible stuff. It has happened to me multiple times during different time periods with fairly distant gaps that I tend to forget this experience only to be stuck with it again and remember that this has happened to me before like a De-ja-vu.

 

I knew that that switch statements accepts integers, characters and enum types as input parameters. My exploration and try outs with enumeration helped me come up with an idea to use string values in Switch-case statement in a slight indirect way.

 

Following was my attempt and I am happy that I did it J

 

public class EnumTest {

 

       public static void main(String args[]) {

 

              String testName = "PERSON_B";

 

              NameConst name = NameConst.valueOf(testName.toUpperCase());

 

              switch (name) {

              case PERSON_A:

                     System.out.println("Big Brother");

                     break;

 

              case PERSON_B:

                     System.out.println("Small Brother");

                     break;

 

              default: // do nothing or your default logic

 

              }

       }

 

}

 

enum NameConst {

       PERSON_A("Person_A"), PERSON_B("PERSON_B");

 

       private String nameValue;

 

       private NameConst(String nameValue) {

              this.nameValue = nameValue;

       }

}

 

I obtained the following output in my console and am more than happy to see this work J

 

>>Small Brother

 

 

Wednesday, May 28, 2014

XML String to JSON conversion in javascript

 

I found this nice simple jquery plugin that helps convert xml string into JSON object directly converts xml string into json object in javascript. Following is a simple html file that I used to test my way through with this plugin. So my motive is to get a message box in the browser saying “Hello World” through the following file. Hope I don’t have to speak much about this file as its very plain and simple

 

----------------------------------------------------------------------------------------------------------------------------

<html>

                <head>

                                <script type='text/javascript' src='jquery.js'></script>

                                <script type='text/javascript' src='jquery.xml2json.js'></script>                               

                                <script type='text/javascript'>

                                                function xmlToJsonTest()             {

                                                                var xml = '<xml><message>Hello world</message></xml>';

                                                                var json = $.xml2json(xml);

                                                                alert(json.message);

                                                }

                                </script>

                </head>

 

                <body onload='xmlToJsonTest()'>XML To JSON Test</body>

 

</html>

----------------------------------------------------------------------------------------------------------------------------

 

You can find this xml to json convertor jquery plugin in http://www.fyneworks.com/jquery/xml-to-json/ .

 

You can go through the site for examples and if you would like to skip the hard part here is the direct download link for the same site for the plugin http://jquery-xml2json-plugin.googlecode.com/svn/trunk/jquery.xml2json.js

 

Hope this helps

 

 

Tuesday, May 27, 2014

Long Awaited - HTML Table with Fixed/Static Headers

It is like a dream come true for me :P. I had strived a lot in the past to create a html table with fixed/static headers and all I was able to do was a close stuff with complex javascript codes manipulating the HTML DOM etc. The challenge was the <th> tag never seemed to respond to my CSS alterations ever. It would stay inert and make me look like an idiot lol. There were times when I got fed up with the great internet explorer as the same code that would work perfectly with other modern browsers would fail with IE. At last with lots of moral support and moral push, I crossed the confidence/patience threshold required to make CSS work for the <th> tags lol.

 

Following is a simple mockup that helped me produce my test table with a fixed header. My research ended up with usage of expression tags in CSS for most scenarios and none worked for me.

I made some tweaks to what I obtained and the key was “DO NOT USE DOCTYPE TAGS IN YOUR HTML FILE” and “top: expression(( document.getElementById ( "tableContainingDivID").scrollTop-1)+"px");”

 

I used the following in the styles in my html file

 

.ozinisleFixedheader {position: relative;height: 17px !important;font-size: 11px !important;font-weight: bold;background: #eee;border: 1px solid #e3e3e3;border-collapse: collapse; vertical-align: bottom;padding: 2px 10px;color: #666;font-family: Arial, Verdana, Helvetica, sans-serif;top: expression(( document.getElementById ( "myTableContainerDivId").scrollTop-1)+"px");text-align: left;letter-spacing: nowrap:nowrap;}

/*following stuffs are to give a decent look and feel for my test table – and has nothing to do with the topic of interest here*/

.tableclass {display: block;border: 1px solid #ccc;border-collapse: collapse;width: 100%;border-left: 1px;border-bottom: 1px;border-right: 1px;}

table.tableclass {background-color: white;width: 100%;overflow-x: hidden;overflow-y: auto;}

table.tableclass tr:nth-child(even) {background: #f1f1f1}

table.tableclass tr:nth-child(odd) {background: #fff}

table.tableclass td {background: none}

.tableclass tbody td {height: 26px;}

.tableclass tbody {border: 1px solid #ccc;border-collapse: collapse;font-size: 11px;overflow: auto;}

 

Then I used a div tag with the following specifications

<div id= myTableContainerDivId ' style='width: 600px; height: 115px; padding-bottom: 4px; border: 1px solid #c2c2c2; overflow: auto;'></div>

 

Then I added a table with style class set to ‘tableclass’ like the following inside the div tag described above

<table class=’tableclass’></table>

 

Then use a thead>tr>th tag to define your headers with style class “ozinisleFixedheader” which might look somewhat like

<thead ><tr><th class="ozinisleFixedheader">header</th></tr></thead>

 

Then define your tbody tag and put in some junk contents, enough to enable you to scroll down. My junk content looks somewhat like the following

<tbody><tr><td>content</td ></tr></tbody>

 

And of course you can use <colgroup> tags to set width to your tables.

 

Tada… that’s how my table was with fixed header was built. Happy enough to party out that I got this one long awaited working prototype. At least I don’t have to pay now for this stuff J

 

Friday, May 16, 2014

Split function in Java

For ages I thought String.split() would work with any sort of delimiters in java. Un fortunately it has tough time working with delimiters as multiple string especially the one which i encountered "$|$"

 

It was confusing and irritating me for a while. God bless me, I am surrounded by sound techies. They introduced Mr.StringTokenizer to me. And so as a test attempt as always I wrote a split command in java using the same.

 

The good thing about this method is it does not depend on Regex. I believe it works well for most cases :)

 

public String[] split(String sourceString, String delimiter) {

 

  String returnArray[]=null;

  StringTokenizer strTknVrXML= new StringTokenizer(sourceString,delimiter);

 

  int tknItr=0;

  returnArray=new String[strTknVrXML.countTokens()];

 

  while (strTknVrXML.hasMoreElements()) {

    returnArray[tknItr++]=strTknVrXML.nextElement().toString();

  }

 

  return returnArray;

}

 

Hope this helps some one :)

 

 

Thursday, May 8, 2014

Opening existing projects in eclipse

This has proved to be an head ache many times to me. So I am documenting the same. Hope this helps me or others in future

Open Eclipse
Click on File -> Import

Now you will see a text box labelled "Select an import source"

Type "Existing" into it

This will result in eclipse to display all options avaliable with the word "Existing" in them

Look for the category named "General" -> under which there will be an option named "Existing Projects into workspace"

Choose it and choose your project.

Your project should have a proper folder structure as desired by the eclipse. If not the project wont be imported. You may have to look for the missing files/folders and put them in place


By default when you click on File -> Import, the set of options being displayed may not necessarily be from the begining. SO try scrolling up first with in the "Import" window

 

HttpWatch

HttpWatch is one nice tool that helps understand my network transcations especially in ie. In someways its better than a firebug lite for ie. I had an oppertunity to work with the software and it seems pretty nice.

Following is a shameless copy paste from www.httpwatch.com website. Atleast I want to keep certain things in one place so that I dont have to switch between sites now and then for simple answers

------------------------------------------------------------------

HttpWatch is an HTTP sniffer for IE, Firefox, iPhone & iPad that provides new insights into how your website loads and performs.

Change the way that you develop, debug and tune websites today!


 - Easily monitor HTTPS, HTTP and SPDY  without using proxies or changing network settings
 - Automatically detects potential configuration, performance and security related issues on your web erver
 - Supports IE/Firefox on Windows and iOS app for iPhone / iPad
 - Can be automated using most programming languages, e.g. C#, Ruby, Javascript, Ruby…
 - Real-time page and request level time charts
 - Provides millisecond accurate timings
 - Users and customers can send you log

------------------------------------------------------------------

One top side about this app that I have experienced personally is that it does not refresh of intervine with the websites operations that it is monitoring. I happened to work with an application which was a bit dumb and was developed to work with IE alone with lots of iframes. So the application has been strictly designed in a way that would prevent an attempt of page refresh by any means from an user. As a fail safe measure the application would log you out if you succeed in refreshing the page. So it was almost impossible for me to turn on the "Start Debugging" button in the Fire bug lite.

In case of HTTP watch all I have to do is press "Shift+F2" and click on "Record" button and I can keep watching what type of transactions are taking place, what actions are being called and what responses are being sent out in a simple chart like fashion.

 

Code change in eclipse not reflecting in IE - HttpWatch

Issue - "Code not reflecting properly on the browser - weblogic server"
 or  "Latest code not reflecting on the browser - weblogic server"
Clear Stage and temporary

Possible fix
----------------


1. If "Http watch" is installed in your machine, start you app on IE and press "Shift+F2" to start it. Go to tools menu and clear cache

2. Try clearing the browser cache in traditional methods Ctrl+shift+delete and clear cookies and temp files

3. Check the "AutoDeploy" directory and remove any existing war files corresponding to your application
In my case the AutoDeploy directory was in "D:\Oracle\Middleware\user_projects\domains\base_domain\autodeploy"

4. On the web logic server locate the following path. (relative to the oracle directory)
D:\Oracle\Middleware\user_projects\domains\base_domain\servers\AdminServer

 It contains the "stage" and "tmp" folders

Delete the contents inside the folder

5. Delete the Meta folder of your project in eclipse
In my case it was
D:\WorkSpace\iCADMay14\.metadata

For some reason this did not recreate it self so i created a new folder named ".metadata" in its place

6. Stopped the weblogic server and deleted the server cache in the following location
ORACLE_HOME/user_projects/domains/your_domain/servers/your_server/cache (optional)

In my case it was,
D:\Oracle\Middleware\user_projects\domains\base_domain\servers\AdminServer\cache

7. Take a look at the url on the browser and make sure it points to your project

In my case the url of the app on the browser said
http://server:port/appName/jsp/myJsp.jsp

 

So I had to make the changes in my property files
in my case it was present at "D:\PropFiles\icad.properties"

I went in and changed the line that said "APP_URL=****" as "APP_URL =http://hostname:7001/appName" and it worked

Now I face new environment related issues. At least its better that to be stuck like a fool in a place that didn't belong to be :)

 

 

Properties in Build.xml

Following is a part of the build config file of my app

  <property name="app.name"      value="ApplicationName"/>  <!-- rename to suit your project name-->
  <property name="app.version"   value="1.0"/>
  <property name="build.home"    value="build"/>
  <property name="catalina.home" value="D:\Oracle\Middleware\wlserver_12.1"/> <!-- UPDATE THIS! -->
  <property name="deploy.home"   value="D:\Oracle\Middleware\wlserver_12.1\${app.name}"/>
  <property name="dist.home"     value="D:\Oracle\Middleware\user_projects\domains\base_domain\autodeploy"/>
  <property name="src.home"      value="src"/>
  <property name="struts.home"   value="./web/WEB-INF/lib"/>

the property that says "property name="dist.home"  needs to be mapped to the auto deploy directory of you domain.

Unless this is done, the application cannot be opened on the browser as the weblogic server wont have any

handle/reference to the war files deployed any were else apart form the autodeploy directory


On the contrary if you are using a JBoss server, your auto deploy directory configuration can be some thing like

thie following

<!-- ===================== Property Definitions =========================== -->

<!--

  Each of the following properties are used in the build script.
  Values for these properties are set by the first place they are 
  defined, from the following list:
  * Definitions on the "ant" command line (ant -Dcatalina.home=xyz compile)
  * Definitions from a "build.properties" file in the top level
    source directory
  * Definitions from a "build.properties" file in the developer's
    home directory
  * Default definitions in this build.xml file

  You will note below that property values can be composed based on the
  contents of previously defined properties.  This is a powerful technique
  that helps you minimize the number of changes required when your development
  environment is modified.  Note that property composition is allowed within
  "build.properties" files as well as in the "build.xml" script.

-->

  <property file="build.properties"/>
  <property file="${user.home}/build.properties"/>


<!-- ==================== File and Directory Names ======================== -->

<!--

  These properties generally define file and directory names (or paths) that
  affect where the build process stores its outputs.

  app.name             Base name of this application, used to
                       construct filenames and directories.
                       Defaults to "myapp".

  app.version          Version identifier for this application.

  build.home           The directory into which the "prepare" and
                       "compile" targets will generate their output.
                       Defaults to "build".

  catalina.home        The directory in which you have installed
                       a binary distribution of Tomcat 4.  This will
                       be used by the "deploy" target.

  deploy.home          The name of the directory into which the
                       deployment hierarchy will be created, and into
                       which the build directory will be copied.
                       Defaults to "${catalina.home}/webapps/${app.name}".

  dist.home            The name of the base directory in which
                       distribution files are created.
                       Defaults to "dist".

-->

   <property name="app.name"      value="ApplicationName"/>  <!-- rename to suit your project name-->
   <property name="app.version"   value="1.0"/>
   <property name="build.home"    value="build"/>
   <property name="catalina.home" value="D:\jboss-4.2.2.GA\jboss-4.2.2.GA\jboss-4.2.2.GA"/> <!-- UPDATE

THIS! -->
   <property name="deploy.home"   value="D:\Oracle\Middleware\user_projects\domains\base_domain

\autodeploy\${app.name}"/>
   <property name="dist.home"     value="D:\Oracle\Middleware\user_projects\domains\base_domain

\autodeploy"/>
   <property name="src.home"      value="src"/>
   <property name="struts.home"   value="./web/WEB-INF/lib"/>

 

 

Thursday, February 13, 2014

Sort NotesDocumentCollection

Shamelessly copy pasted from http://blog.tjitjing.com/index.php/2006/05/how-to-sort-notesdocumentcollection-in.html. Nice code. Hope it gets reused many times

This Lotusscript function sorts a document collection on one or multiple fields.
I have previously used several other algorithms that use a view to sort the collection, these however have the drawback that they become very inefficient (i.e. slow) as the number of documents in the view used for sorting grows. The solution presented below does not have this problem.
It has been developed and tested in Lotus Notes 6.5.3 but should work in all ND6 (release 6) and possibly earlier Lotus Notes releases too (if you test this successfully or unsuccessfully write a comment to this post and everyone will know).
Example of use:
Dim fieldnames(0 To 2) As String
fieldnames(0) = "SKU"
fieldnames(1) = "OrderDate"
fieldnames(2) = "Client"
Set collection = SortCollection (collection, fieldnames)
Function to sort DocumentCollection:
Function SortCollection(coll As NotesDocumentCollection, fieldnames() As String) As NotesDocumentCollection
' ------------------------------------------------
' --- You may use and/or change this code freely
' --- provided you keep this message
' ---
' --- Description:
' --- Sorts and returns a NotesDocumentCollection
' --- Fieldnames parameter is an array of strings
' --- with the field names to be sorted on
' ---
' --- By Max Flodén 2005 - http://www.tjitjing.com
' ------------------------------------------------
Dim session As New NotesSession
Dim db As NotesDatabase
Dim collSorted As NotesDocumentCollection
Dim doc As NotesDocument
Dim i As Integer, n As Integer
Dim arrFieldValueLength() As Long
Dim arrSort, strSort As String
Dim viewname As String, fakesearchstring As String
viewname = "$All" 'This could be any existing view in database with first column sorted
fakesearchstring = "zzzzzzz" 'This search string must NOT match anything in view
Set db = session.CurrentDatabase
' ---
' --- 1) Build array to be sorted
' ---
'Fill array with fieldvalues and docid and get max field length
Redim arrSort(0 To coll.Count -1, 0 To Ubound(fieldnames) + 1)
Redim arrFieldValueLength(0 To Ubound(fieldnames) + 1)
For i = 0 To coll.Count - 1
Set doc = coll.GetNthDocument(i + 1)
For n = 0 To Ubound(fieldnames) + 1
If n = Ubound(fieldnames) + 1 Then
arrSort(i,n) = doc.UniversalID
arrFieldValueLength(n) = 32
Else
arrSort(i,n) = "" & doc.GetItemValue(fieldnames(n))(0)
' Check length of field value
If Len(arrSort(i,n)) > arrFieldValueLength(n) Then
arrFieldValueLength(n) = Len(arrSort(i,n))
End If
End If
Next n
Next i
'Merge fields into list that can be used for sorting using @Sort function
For i = 0 To coll.Count - 1
If Not strSort = "" Then strSort = strSort & ":"
strSort = strSort & """"
For n = Lbound(fieldnames) To Ubound(fieldnames) + 1
strSort = strSort & Left(arrSort(i,n) & Space(arrFieldValueLength(n)), arrFieldValueLength(n))
Next n
strSort = strSort & """"
Next i
' ---
' --- 2) Sort array
' ---
arrSort = Evaluate("@Sort(" & strSort & ")")
' ---
' --- 3) Use sorted array to sort collection
' ---
Set collSorted = coll.Parent.GetView(viewname).GetAllDocumentsByKey(fakesearchstring)
For i = 0 To Ubound(arrSort)
Set doc = db.GetDocumentByUNID(Right(arrSort(i), 32))
Call collSorted.AddDocument(doc)
Next i
' ---
' --- 4) Return collection
' ---
Set SortCollection = collSorted
End Function

(This article is previously published and has been moved to this blog)

[Update: Instead of using Evaluate and @Sort in section 2 in the code you can of course use any of your favourite sort routines. Or search the Net for one, there are many out there.]

Tuesday, December 10, 2013

"Command Not Handled Exception" after removing "XPageDebugToolbar_v3.0.1" custom control from XPages

It would have happened to me again. I mean the long trial and error and the wage wait process to find errors in XPages. For some reason, my XPage would not open up if I remove the XPageDebugToolbar_v3.0.1 custom control from my XPage. And again it worked if I added it back again.

I was like 0.o why would this happen. Has the Debug toolbar author found a way to mess up XPages if they dont need them anymore :P. 

Fortunately I remember that one of my dynamic view controls used a managed bean in which I had declared an object reference to the debug tool bar

private static final DebugToolbar dBar = DebugToolbar.get();

to the answer was to put "//" before the line of code and make it

//private static final DebugToolbar dBar = DebugToolbar.get();

Yeah. Comment-ing the code fixed the issue. Wierd. Guess it would have been better it does not error out and surprice like this.