Pages

Tuesday, May 12, 2015

Handling security errors due to Cross Domain Ajax (JSONP)

Some basic issues that I face while working with iframes include t not limited to the following,

1.       Unable to access iframe – document object

2.t  when I am unable to access iframe’s document object or vice versa, the issue could be due to browser settings or because the url in the child frame belongs to a differennts in ed from different servers whose urls were similar to the following

http://********.xtss.com:8080/JSONP_Consumer/ParentFrame.html  and

http:// ********.xtss.com:8090/JSONP_Store/iframeContent.html

Observe closely. These two urls belong to two different servers. Running on different ports.

To ensure smooth communication between the two webpages, I had used the following trick

document.domain="xtss.com"; //should be subset of domain name in host name

Don’t worry about the dojo code that you will find on the page. Dojo has nothing to do with the trick. Its just that I had used it to write a logic to find and hide a button in the parent window. One can always use native javascript or other libraries like jquery to do that.

Now put the following in ParentFrame.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

<script>

 

document.domain="xtss.com";

 

</script>

 

 

</head>

<body>

       <button id='trg'> Hide target </button>

       <iframe src='http:// ********.xtss.com:8090/JSONP_Store/iframeContent.html'></iframe>

</body>

</html>

 

And put the following code in the iframeContent.html

<html><head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

 

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"

            data-dojo-config="async: true"></script>

           

<script>

 

document.domain="xtss.com";

 

/* function clickme()      {

       console.log('inside click')

       window.parent.document.getElementById('trg').style.display='none';

} */

 

var changeStyles;

require(["dojo/on",

         "dojo/dom",

         "dojo/_base/window",

         "dojo/query",

         "dojo/dom-style",

         'dojo/domReady!'],

              function(on, dom, win, query, domStyle){

                          

                  changeStyles = function(){

                    

                     var targetIDinParentScreen='trg';

                     var pageToRedirectTo='/JSONP_Store/dummyPage.html';

                      var parentDoc = window.parent.document;

                     

                      win.withDoc(parentDoc, function(){

                             var hideTarget = query("#"+targetIdInParentScreen)

                             domStyle.set(hideTarget[0], "display", "none");

                      });

                     

                      window.location.href=pageToRedirectTo;

                  };

              });

             

</script>

 

</head>

<body>

 

 

 

<a id="eventSource" href='javascript:changeStyles()'> click me</a>

 

</body></html>

 

Now when you try to reload a frame with a different url, make sure you donot use sites like “Google.com” as they won’t open inside an iframe. They always check that they are on top and don’t let iframes use them. So for that sake I am creating my own page – a dummyHTML file

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

Dummy Page

</body>

</html>

 

 


Apache Tomcat server runs but does not display home page

<!--[if !mso]><![endif]
Well this particular issue was pestering me for a while now. All my apps on this server were running properly but still when I say http://localhost:8080 it would serve me an error page. Now I know that this error page is being served by the server at least. So, why not the server’s root page?

This led me to search for the root folder of the server. Well that was another mess that I made with my tomcat folder lol. Coming back to the point, I found a neat an good explanation about a fix for this issue in a pretty decent webpage - http://www.coreservlets.com/Apache-Tomcat-Tutorial/tomcat-7-with-eclipse.html .

It said the following,
Copy the ROOT (default) Web app into Eclipse. Eclipse forgets to copy the default apps (ROOT, examples, docs, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps and copy the ROOT folder. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like C:\your-eclipse-workspace-location\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

So my working directories in my local machine were as follows
“Root folder’s” folder path in Tomcat deployed directory – D:\softwares\apache-tomcat-7.0.54\webapps\
My eclipse workspace - D:\EclipseWorkspace\Server8090\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps

Now I copy pasted the folder named “Root” from former to the later and I skipped over writing any existing files.
""

And now my beautiful server’s gorgeous home page is as follows
""

-->

Friday, February 13, 2015

Got Crazy with nested classes :)

This time I tried enclosing 23 levels of sub classes with a combination of static and plain nested subclasses and guess what!!! It worked for me. Guess My demo of nested sub classes in java is world class rofl

Step 1: created a class like the following

package com.oz.core.NestedClasses;

public class OuterClass {

public static class NestedClass {

public class SubNestedClass {
public class Level4 {
public class Level5 {
public class Level6 {
public class Level7 {
public class Level8 {
public class Level9 {
public class Level10 {
public class Level11 {
public class Level12 {
public class Level13 {
public class Level14 {
public class Level15 {
public class Level16 {
public class Level17 {
public class Level18 {
public class Level19 {
public class Level20 {
public class Level21 {
public class Level22 {
public class Level {
Level() {
System.out
.println("Road To Eldorado WHOOO...HOOOO");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}

}

Step 2: instantiated the classes Lol

package com.oz.core.NestedClasses;

import com.oz.core.NestedClasses.OuterClass.NestedClass.SubNestedClass.Level4.Level5;

public class Main {
public static void main(String args[]) {
OuterClass outCls = new OuterClass();
OuterClass.NestedClass nesCls=new OuterClass.NestedClass();
OuterClass.NestedClass.SubNestedClass subNestedClass=
nesCls.new SubNestedClass();
OuterClass.NestedClass.SubNestedClass subNestedClass2=
new OuterClass.NestedClass().new SubNestedClass();

OuterClass.NestedClass.SubNestedClass.Level4 lvl4= subNestedClass2. new Level4();
OuterClass.NestedClass.SubNestedClass.Level4.Level5.Level6.Level7.Level8.Level9.Level10
.Level11.Level12.Level13.Level14.Level15.Level16
.Level17.Level18.Level19.Level20.Level21.Level22
.Level level = lvl4.new Level5().new Level6().new Level7().new Level8().new Level9().new Level10()
.new Level11().new Level12().new Level13().new Level14().new Level15().new Level16().new Level17().new Level18()
.new Level19().new Level20().new Level21().new Level22().new Level();
}
}

Step 3: ran the main program to see the output on the console ☺

Console Output:

Road To Eldorado WHOOO...HOOOO

Wednesday, February 11, 2015

LOL with Arrays in Java

Well I do get crazy when I start experimenting some times. Never dared to do this in real life aparting from pushing my limits when it came to swallowing stuffs and touching electric bulbs. But I really do feel like I get very crazy when it comes to my computers. It does not cost me much ehh... apart from the time I spent on doing it :D

Coming to the point, I grew interest in Nano technology, Astronomy, Relativity, Time Travel, Beyond 3 Diminsions... and there I was, I am not that good in science yet to show you guys the fourth dimension, but how about it in Java ROFL. I went up till 23 dimensions LOL. 23-Dimensional array.

I wrote down the following class

package com.oz.core.Arrays;

public class ArrayExperiments {

public static void main(String args[]) {
int[] intArray = new int[10];
int[][] int2dArray = new int[10][10];
int[][][] int3dArray = new int[10][10][10];
int [][][][] int4dArray=new int [10][10][10][10] ;
int [][][][][] int5dArray=new int [10][10][10][10][10] ;
int [][][][][][] int6dArray=new int [10][10][10][10][10][10] ;
int [][][][][][][] int7dArray=new int [10][10][10][10][10][10][10] ;
int [][][][][][][][] int8dArray=new int [10][10][10][10][10][10][10][10] ;
int [][][][][][][][][] int9dArray=new int [10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][] int10dArray=new int [10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][] int11dArray=new int [10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][] int12dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][] int13dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][] int14dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][] int15dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][][] int16dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][][][] int17dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][][][][] int18dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][][][][][] int19dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][][][][][][] int20dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][][][][][][][] int21dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][][][][][][][][] int22dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;
int [][][][][][][][][][][][][][][][][][][][][][][] int23dArray=new int [10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10][10] ;



int5dArray[1][2][3][4][5]=999 ;
int6dArray[1][2][3][4][5][6]=1999 ;
int7dArray[1][2][3][4][5][6][7]=2999 ;

System.out.printf("%d + %d + %d = "+
int5dArray[1][2][3][4][5]+
int6dArray[1][2][3][4][5][6]+
int7dArray[1][2][3][4][5][6][7],
int5dArray[1][2][3][4][5],
int6dArray[1][2][3][4][5][6],
int7dArray[1][2][3][4][5][6][7]);

}

}

And I ran it eagerly to see what happens. LOL the following happened. I did it again, but this time the crashed the JVM and not the LOTUS DOMINO SERVER rofl

JVMDUMP006I Processing dump event "systhrow", detail "java/lang/OutOfMemoryError" - please wait.
JVMDUMP032I JVM requested Heap dump using 'C:\Accurev_work\Ozinisle\heapdump.20150211.175635.9948.0001.phd' in response to an event
JVMDUMP010I Heap dump written to C:\Accurev_work\Ozinisle\heapdump.20150211.175635.9948.0001.phd
JVMDUMP032I JVM requested Java dump using 'C:\Accurev_work\Ozinisle\javacore.20150211.175635.9948.0002.txt' in response to an event
JVMDUMP010I Java dump written to C:\Accurev_work\Ozinisle\javacore.20150211.175635.9948.0002.txt
JVMDUMP032I JVM requested Snap dump using 'C:\Accurev_work\Ozinisle\Snap.20150211.175635.9948.0003.trc' in response to an event
JVMDUMP006I Processing dump event "systhrow", detail "java/lang/OutOfMemoryError" - please wait.
JVMDUMP010I Snap dump written to C:\Accurev_work\Ozinisle\Snap.20150211.175635.9948.0003.trc
JVMDUMP013I Processed dump event "systhrow", detail "java/lang/OutOfMemoryError".
JVMDUMP032I JVM requested Heap dump using 'C:\Accurev_work\Ozinisle\heapdump.20150211.175705.9948.0004.phd' in response to an event
JVMDUMP010I Heap dump written to C:\Accurev_work\Ozinisle\heapdump.20150211.175705.9948.0004.phd
JVMDUMP032I JVM requested Java dump using 'C:\Accurev_work\Ozinisle\javacore.20150211.175705.9948.0005.txt' in response to an event
JVMDUMP010I Java dump written to C:\Accurev_work\Ozinisle\javacore.20150211.175705.9948.0005.txt
JVMDUMP032I JVM requested Snap dump using 'C:\Accurev_work\Ozinisle\Snap.20150211.175705.9948.0006.trc' in response to an event
JVMDUMP010I Snap dump written to C:\Accurev_work\Ozinisle\Snap.20150211.175705.9948.0006.trc
JVMDUMP013I Processed dump event "systhrow", detail "java/lang/OutOfMemoryError".
Exception in thread "main" java.lang.OutOfMemoryError
Exception in thread "Attach API wait loop" at com.oz.core.Arrays.ArrayExperiments.main(ArrayExperiments.java:14)
java.lang.OutOfMemoryError
at com.ibm.tools.attach.javaSE.TargetDirectory.getTargetDirectoryPath(TargetDirectory.java:66)
at com.ibm.tools.attach.javaSE.AttachHandler.connectToAttacher(AttachHandler.java:274)
at com.ibm.tools.attach.javaSE.AttachHandler$WaitLoop.checkReplyAndCreateAttachment(AttachHandler.java:371)
at com.ibm.tools.attach.javaSE.AttachHandler$WaitLoop.waitForNotification(AttachHandler.java:366)
at com.ibm.tools.attach.javaSE.AttachHandler$WaitLoop.run(AttachHandler.java:396)

And this time let me be @%$*&$! Less greedy

package com.oz.core.Arrays;

public class ArrayExperiments {

public static void main(String args[]) {
int[] intArray = new int[10];
int[][] int2dArray = new int[10][10];
int[][][] int3dArray = new int[10][10][10];
int [][][][] int4dArray=new int [10][10][10][10] ;
int [][][][][] int5dArray=new int [10][10][10][10][10] ;



int2dArray[1][2]=999 ;
int3dArray[1][2][3]=1999 ;
int4dArray[1][2][3][4]=2999 ;

System.out.printf("%d + %d + %d = "+
int2dArray[1][2]+
int3dArray[1][2][3]+
int4dArray[1][2][3][4],
int2dArray[1][2],
int3dArray[1][2][3],
int4dArray[1][2][3][4]);

}

}

And this gave a decent out put

999 + 1999 + 2999 = 99919992999

Wait what!!!! Lol rofl

A day for Enumeration perhaps

I had written a post about how to implement a Switch Case using String in past. I had to do a similar thing now and felt like it time I dig more about Enum Classes and objects.

I understand that an object definition using the Enum keyword is similar to a class definition and can be put in its own file. And that the Enum objects by default will extend java.lang.Enum implicitly

An enum type is a special kind of Java class used to define collections of constants, methods etc. It can hold if statements, switch statements, fields, methods, iterations etc. Following is a simple example of my test with an Enum Object and its results

Enum Object definition

package com.oz.core;

public enum Level {
      HIGH(3), // calls constructor with value 3
      MEDIUM(2), // calls constructor with value 2
      LOW(1) // calls constructor with value 1
      ; // semicolon needed when fields / methods follow

      private final int levelCode;

      Level(int levelCode) {
            this.levelCode = levelCode;
      }

      public int getLevelCode() {
            return this.levelCode;
      }
}

Implementation class definintion

package com.oz.core;

public class EnumerationSample {

      public static void main(String args[]) {

            EnumerationSample self = new EnumerationSample();
            self.caseWithStringArgs("medium");
            self.caseWithStringArgs("high");
            self.caseWithStringArgs("critical");
           
            Level level = Level.valueOf("LOW");
            System.out.println("level="+level);
            System.out.println("level.compareTo(Level.valueOf(\"HIGH\"))="+level.compareTo(Level.valueOf("HIGH")));
            System.out.println("level.compareTo(Level.valueOf(\"LOW\"))="+level.compareTo(Level.valueOf("LOW")));
            System.out.println("level.compareTo(level.HIGH)="+level.compareTo(level.HIGH));
            System.out.println("level.compareTo(level.LOW)="+level.compareTo(level.LOW));
            System.out.println("level.getLevelCode()="+level.getLevelCode());
            System.out.println("level.hashCode()="+level.hashCode());
            System.out.println("level.name()="+level.name());
            System.out.println("level.ordinal()="+level.ordinal());
            System.out.println("level.toString()="+level.toString());
            System.out.println("level.equals(Level.LOW)="+level.equals(Level.LOW));
            System.out.println("level.equals(Level.MEDIUM)="+level.equals(Level.MEDIUM));
            System.out.println("level.equals(Level.valueOf(\"LOW\"))="+level.equals(Level.valueOf("LOW")));
            System.out.println("level.equals(Level.valueOf(\"MEDIUM\"))="+level.equals(Level.valueOf("MEDIUM")));
            System.out.println("level.getClass()="+level.getClass());
            System.out.println("level.getDeclaringClass()="+level.getDeclaringClass());
           
            for (Level lvl : level.values())    {
                  System.out.println("lvl="+lvl);
            }
           
            /*System.out.println("level="+Level.valueOf(arg0, arg1));
            System.out.println("level="+level.notify());
            System.out.println("level="+level.notifyAll());
            System.out.println("level="+level.wait());
            System.out.println("level="+level.wait(arg0, arg1));*/           
           
      }
     
      String caseWithStringArgs(String arg)     {
           
            String evaluatedString = "Not in list";
            try   {
                  Level level = Level.valueOf(arg.toUpperCase());
                 
                  switch (level) {
                  case HIGH:
                        evaluatedString = "case statement for High";
                        break;

                  case MEDIUM:
                        evaluatedString = "case statement for Medium";
                        break;

                  case LOW:
                        evaluatedString = "case statement for Low";
                        break;

                  default:
                        break;
                  }
            } catch     (IllegalArgumentException exp)      {
                 
            } finally   {
                  System.out.println(evaluatedString);
                  return evaluatedString;
            }          
      }
}

Following are the set of obtained console statements

case statement for Medium
case statement for High
Not in list
level=LOW
level.compareTo(Level.valueOf("HIGH"))=2  //HIGH=3, LOW=1, so HIGH-LOW=2
level.compareTo(Level.valueOf("LOW"))=0   //LOW=1, LOW=1, so LOW-LOW=2
level.compareTo(level.HIGH)=2             //HIGH=3, LOW=1, so HIGH-LOW=2
level.compareTo(level.LOW)=0              //LOW=1, LOW=1, so LOW-LOW=2
level.getLevelCode()=1                    //LOW=1
level.hashCode()=650651336
level.name()=LOW                          //name
level.ordinal()=2                         //ordinal = 2 - returns its position in its enum declaration
level.toString()=LOW
level.equals(Level.LOW)=true
level.equals(Level.MEDIUM)=false
level.equals(Level.valueOf("LOW"))=true
level.equals(Level.valueOf("MEDIUM"))=false
level.getClass()=class com.oz.core.Level
level.getDeclaringClass()=class com.oz.core.Level     //Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass().
lvl=HIGH          //printed because of the iteration statement with in enum
lvl=MEDIUM        //printed because of the iteration statement with in enum
lvl=LOW           //printed because of the iteration statement with in enum


Hope this helps

Saturday, November 15, 2014

Extjs best practises

 

 

 

 

                                                            1.use MVC

2.use xtype

3.define custom xtypes

4.use compressor - give minified files to client

5.use SenchaArchitect or cmd

6.travese dom using up/down etc - dont give ID and dont get by ID to elements

7.use icons instead of "text+icons"

8.inject images using css

9.use theming

10.avoid using deprecated commands and use new commands like using Ext.launch method

instead of Ext.onReady

11.dont declare deep tree... use layouts precisely... try to keep things with in 2 or 3

levels

12.Reuse the components

13. Try to do population and manipulation in afterRenderer than in beforeRenederer

14.Always handle exceptions, especially failure cases of a Ajax call

 

Wednesday, November 12, 2014

While trying samples with Ext.tab.Panel, as usual I though about the next step of using nested panels and load an external html file into a panel.
And I tried a few simple straight forward stuffs and for some reason it kept failing. Eventually I came up with an answer as usual. Guess I dont want to be stuck with this silly issue every again. And hence this post. Following is a part of my practise project which is necessary for the nested tab implementation

I have the following in code in the head section of my "index.html" file

 <!-- STYLES -->
    <link rel="stylesheet" type="text/css" href="\ext-4.2.1.883/resources/css/ext-all.css">
    <!-- LIBS -->
    <script type="text/javascript" src="\ext-4.2.1.883/ext-all-debug.js"></script>
    <!-- APP -->
    <script type="text/javascript" src="./app.js"></script>

The contents of my "external.html" file are as follows
<div id='karthick'>
My Custom text from an external HTMl
</div>

And the following in my "app.js" file

 Ext.require('Ext.tab.*'); Ext.application({ name: "Tab Panel example", launch : function() { var tabs = Ext.create('Ext.tab.Panel', { width : 450, height: 400, renderTo: document.body, activeTab : 0, id:'parentTab', items : [{ title:'Home', itemId : 'tab1', xtype: 'container', loader: { url: 'external.htm', autoLoad: true }, closable : true }, { title:'Away', itemId : 'tab2', closable : true, items:[{ xtype:'tabpanel', items : [{ title: 'Nested Tab 1', itemId : 'nested tab1', closable : true, html:'nested tab1' },{ title: 'Nested Tab 2', itemId : 'nested tab2', closable : true, html:'nested tab2', disabled:true }] }] }] }); } });

So the end result is as follows
The highlights in this example are
1. You are using a nested tabbed table created through Ext-js 4.2
2. It implements some inbuilt properties like
- closable:true
- and disable:true
3. You have included an external html file's content into your page


Note: this example wont work if you are trying this example in a local stand alone machine. Use a server like tomcat or IIS, because, the inclusion of content from an other html file includes AJAX requests in the back end by Ext-JS which would definitely fail in local or conclusively it requires a server to operate

Nested Tab example in Ext-Js

While trying samples with Ext.tab.Panel, as usual I though about the next step of using nested panels.
And I tried a few simple straight forward stuffs and for some reason it kept failing. Eventually I came up with an answer as usual. Guess I dont want to be stuck with this silly issue every again. And hence this post. Following is a part of my practise project which is necessary for the nested tab implementation

You can safely omit external.htm file for now

I have the following in code in the head section of my "index.html" file

 <!-- STYLES -->
    <link rel="stylesheet" type="text/css" href="\ext-4.2.1.883/resources/css/ext-all.css">
 
    <!-- LIBS -->
    <script type="text/javascript" src="\ext-4.2.1.883/ext-all-debug.js"></script>
 
    <!-- APP -->
    <script type="text/javascript" src="./app.js"></script>

And the following in my "app.js" file

Ext.require('Ext.tab.*');

Ext.application({
name: "Tab Panel example",
launch : function() {
var tabs = Ext.create('Ext.tab.Panel', {
width : 450,
height: 400,
renderTo: document.body,
activeTab : 1,
id:'parentTab',
items : [{
title:'Home',
itemId : 'tab1',
html: 'First tab content',
closable : true
}, {
title:'Away',
itemId : 'tab2',
closable : true,
items:[{
xtype:'tabpanel',
items : [{
title: 'Nested Tab 1',
itemId : 'nested tab1',
closable : true,
html:'nested tab1'
},{
title: 'Nested Tab 2',
itemId : 'nested tab2',
closable : true,
html:'nested tab2',
disabled:true
}]
}]
}]
});

}
});

The end result that I obtained is as follows. 


:)

Wednesday, November 5, 2014

File Upload using Servlets


Create a simple Dynamic Web project in the eclipse IDE. I have installed Apache Tomcat 7.0.10 and following is my folder stucture. You can safely skip the HelloWorld.java and LogFilter.java files from this folder structure as they don't have any thing to do with this post.

My motive is to give a simple explanation/illustration on how a file upload control can be implemented in java programs using servlets.

Step 1. create a FileUploadTest.html file in your WebContent folder. I tried putting the same under a sub folder of the WebContent folder. But it never worked. It was not able to communicate with the corresponding servlet.
The code contents of this HTML file are as follows
test




Step 2: Create a servlet class with the following contents in it

package com.practise.karthik.servlet;

// Import required java libraries
import java.io.*;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class UploadServlet extends HttpServlet {
 
   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath =
             getServletContext().getInitParameter("file-upload");
   }
   public void doPost(HttpServletRequest request,
               HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){
         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<p>No file uploaded</p>");
         out.println("</body>");
         out.println("</html>");
         return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);
      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head>");
      out.println("<body>");
      while ( i.hasNext () )
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath +
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath +
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {
     
        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   }
}

Step 3: Add the following to your web.xml
 <servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.practise.karthik.servlet.UploadServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>


Set 4 : Now you would need a couple of jar files that would help you with the file upload functionality

commons-fileupload.x.x.jar file - You can download it fromhttp://commons.apache.org/fileupload/.
commons-io-x.x.jar file - You can download it from http://commons.apache.org/io/.

Step 5: Download these files and add them to the lib folder under the WEB-INF folder and add it to the project's build path


Step 6: Now stop your Apache Tomcat Server if its already running. 
 - Right click on the html file mentioned in step 1, 
 - click on "Run as" and 
 - click on "Run on server" option
 - choose your installed Tomcat server ( hope you had already added the server to your Servers view in the eclipse) and
 - finish

This helped me get to the following screen



Choose your file and click on the "Upload File" button. You should receive a confirmation screen with the name of the file that you just uploaded as follows


This helped me upload my file to my server space configured in the web.xml and I am able to find the uploaded file as follows

Friday, October 17, 2014

replacing newline with characters in java

I had a string named “remarks” with the following value in it

 

10/17/2014 07:14 AM test1

test1

test1

test1

10/17/2014 07:14 AM dfgdfg

 

I tried to replace all line feeds in this string with a particular character set in java and so I tried the following

 

String re = remarks1.replaceAll("\n","$#$”);

System.out.println(re);

 

This kept giving me illegal arguments exception.

 

So I tried

String re = remarks1.replaceAll("\\n","$#$");

System.out.println(re);

 

Now I felt weird. This is not normal behavior as most of my searches said this should work. Hence I felt a little irritated and I tried a different string instead of “$#$”. It was a stupid attempt though. But to my astonishment it worked fine

 

Curse compiler. Stupid same and its issue with “$” characters

 

Following worked at last

 

String re = remarks1.replaceAll("\\n","@#@");

System.out.println(re);

 

The output was

10/17/2014 07:14 AM test1@#@test1@#@test1@#@test1@#@10/17/2014 07:14 AM dfgdfg@#@

 

At ease 0.0  grrr