Wednesday, November 30, 2011

Invalid set of fields set for XMLGregorianCalendar

Exception in thread "main" java.lang.IllegalStateException: com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl#getXMLSchemaType() :Invalid set of fields set for XMLGregorianCalendar
 at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.getXMLSchemaType(XMLGregorianCalendarImpl.java:1928)
 at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.toXMLFormat(XMLGregorianCalendarImpl.java:1764)
 at javax.xml.datatype.XMLGregorianCalendar.toString(XMLGregorianCalendar.java:866)


I was getting the above exception when I try to run the following code...

XMLGregorianCalendar tmStamp = new XMLGregorianCalendarImpl();
        tmStamp.setYear(2011);
        tmStamp.setMonth(Calendar.NOVEMBER);
        tmStamp.setDay(30);
        tmStamp.setHour(10);
        tmStamp.setMinute(59); 
        System.out.println(tmStamp.toString());


Solution:
Set the seconds as well
tmStamp.setSeconds(30);

Setting the seconds is mandatory when you set hours and minutes.

JAXB and JDK1.6

Use JDK 1.6 to convert from Java to XML


http://www.javabeat.net/articles/14-java-60-features-part-2-pluggable-annotation-proce-3.html

Thursday, November 24, 2011

Building Java Web Services with NetBeans 7.0

Create web services using Netbeans 7.0


Here is a complete tutorial with screenshots and very well explained.

http://www.theserverside.com/tip/Building-Java-Web-services-with-NetBeans-7

How to create a sample Web Service using JDeveloper

Thanks to Hussain for creating this tutorial. I am just extending his learning with some additions of mine.

The Sample WebService will return Credit Rating of the customer if the customer Id is Valid else it will give response as Invalid Customer Id

1) Open JDeveloper, Create New Application and Project as shown below

2) Create a Java Class, Right Click on Project->New->General->JavaClass

3) Enter Class Name as CreditRating and Package name as com.ws

4) Write a Method called getCreditRating inside the class CreditRating class.
the method should accept customer id and return a CreditRating of the customer.

5) Compile your Project, After Successful Compilation, Right Click your Project->Business Tier-> Web Services-> Java Web Service

6)Enter WebService Name and Select the CreditRating Class as Component to Publish and click Next


7) Once You Successfully generate the Java Web Service, You need to deploy it and Test the working of the Web Service
8) Right Click on MyWebService1 and Select Run. You'll see a URL in the Log window as shown below.











Method getCreditRating: The following parameter types do not have an XML Schema mapping and/or seralizer specified:

I was getting the following error message when trying to create web service from this URL

Error Message:
Method getCreditRating: The following parameter types do not have an XML Schema mapping and/or seralizer specified:

java.lang.Object


Solution :
The java.io.Serializable marker is not consulted when determining whether a Java object can be transmitted in a web service invocation. Instead, each parameter and return value of a web service method must conform to one of the 3 rules below:

1. It is a Java primitive (int, long, byte etc.), Java primitive wrapper (java.lang.Integer etc.), or a java.lang.String.
2. It is a Java bean with a zero-argument constructor, and a pair of "get" and "set" methods for each property to be exposed. Each property must itself conform to one of these 3 rules.
3. It is an array of a type that meets either rule 1 or rule 2.

Tuesday, November 22, 2011

How to make hover effects work in Internet Explorer

Thanks to http://www.bernzilla.com/item.php?id=762 for the post. :)

I spent about an hour this morning trying to figure out how in the world to get IE7 to apply my :hover styling to a non-anchor (<a>) element. Amazingly enough, numerous searches on Google turned up absolutely nothing. I found one forum post that looked promising, but it was one of those depressing forum posts that states the exact same problem you're having, but doesn't have any replies.

What made things more frustrating was that there are blog posts galore touting IE7's addition of support for :hover on all elements, yet no matter what I tried I couldn't get it to work!

Eventually, I recalled reading something on the IEBlog about how a web page's DOCTYPE would dictate the CSS support in IE7. The gist of it is, if you want support for :hover on all elements and not just the <a> tag, make sure you're using a strict DOCTYPE so IE7 doesn't kick in to quirks mode.

Whereas the following HTML resulted in my hover effects working in Firefox but not IE7


...simply adding the HTML 4.01 Strict DOCTYPE to the top of the HTML document made IE7 obey my :hover rules as well:

WORKING CODE


Internet Explorer 7 and later, in standards-compliant mode (strict !DOCTYPE), can apply the :hover pseudo-class to any element, not merely links.


How to highlight table rows on mouseOver

Please note that if you are using IE, don't forget to add the DOCTYPE to your HTML document


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

For more details, you can refer to this link or this link

Put this inside your <HEAD> section


Put this into your <BODY> section





Table example 1

Name Age Position Income Gender
John 37 Managing director 90.000 Male
Susan 34 Partner 90.000 Female
David 29 Head of production 70.000 Male

Sunday, November 20, 2011

More about regular expressions in Javascript

Aah !! Regular expressions

I have got confused most of the times, I need to escape special characters when specifying a regular expression.

Let us take an example of simple date format
dd/mm/yyyy

There are two ways, you can specify your regular expression

// Please note that your regular expression literal object must be surrounded
// between forward slashes as is done below.

// Since forward slash (/) has a special meaning in regular expressions
// it need to be escaped by a backslash (\)
var regex = /^\d{2}\/\d{2}\/\d{4}$/
regex.test("01/04/1975");

/*  / -- Used to signify that a regex literal follows.
 *  ^ - Starts with
 * \d{2} - 2 digits (date)
 * \/  - Escaping the forward slash
 * \d{2} - 2 digits (Month)
 * \/ - Escaping the forward slash
 * \d{4} - 4 digits (Year)
 * $ - end of string.
 * / - specifies the end of regex literal.
 */

// Things become more complex when you want to specify 
// regular expression in a String

// Please note the difference between the regex literal and the string regex
// Here we have to escape the backslash as well. 
// So the  number of backslashes are doubled.

var regex = new RegExp("^\\d{2}\\/\\d{2}\\/\\d{4}");


/*  
 *  ^ - Starts with
 * \\d{2} - 2 digits (date)
 * \\/  - Escaping the forward slash
 * \\d{2} - 2 digits (Month)
 * \\/ - Escaping the forward slash
 * \\d{4} - 4 digits (Year)
 * $ - end of regex.
 */


Please note that you have to escape all those characters which have a special meaning in Regular expressions.
Just place a backslash before that character. (2 backslashes if you are specifying regex as a string literal)
List of characters that need to be escaped are :

[, ], ., ?, *, +, /, \, {, }, |, (, )

Related Post : http://javakafunda.blogspot.com/2011/06/10-java-regular-expression-examples-you.html

Saturday, November 19, 2011

Weblogic specific issue abt custom Tags

Dear Friends,

I was facing an issue specifically on weblogic and the same JSP was working fine on Oracle Application Server.
I thought it is worth sharing with all.

ERROR MESSAGE :
The method setTabindex (String) in the type NumericNewTextTag is not applicable for the arguments (int)

After seeing the error message, the obvious thought that came to my mind was, that we are passing an int and it is expecting a String.

Then I thought, why and how it is getting compiled on Oracle AS?
Is JSP to Servlet compilation, vendor specific?
What abt the theory that Java says? write once, run anywhere? Doesn't this theory apply here?


You'll get the answers to all these questions at the end of this post.

Problematic code



Code with Problem resolved.



Key Points
===========

On Oracle this custom tag gets translated to somewhat like the following.

// Please note that whatever is the return type 
// of the expression is wrapped into String and then sent to setTabIndex method.
// So even if the developer sends a primitive int, oracle will convert it
// to String before sending it to method.
// Hence no compilation problem on Oracle server.
__jsp_taghandler_33.setTabindex(OracleJspRuntime.toStr(Integer.toString(tabIndex));

Note that, the oracle server converts the argument passed by the user to a String explicitly, which is not the case with weblogic.
So, if you are using a request-time expression value in the attribute of a custom-tag, Make sure that return type of the expression is a String.

Here are the answers to the questions:

Why and how it is getting compiled on Oracle AS?
The above explanation clearly explains that.
Is JSP to Servlet translation, vendor specific?
Yes, JSP to servlet translation varies across vendors.
What abt the theory that Java says? write once, run anywhere? Doesn't this theory apply here?
This theory still works. Because, it was the mistake on developer's end, not to comply with the syntax of JSP, which luckily worked on Oracle.

JSP always say, you must pass a String to an custom-tag's attribute.


Some questions are still boggling my mind?

  1. Is it good that Oracle converts every passed expression to String before passing to the setTabindex method? What should be the ideal translation that is expected from a container?
  2. how abt the literals that are passed like tabindex="1", how that were working on weblogic? Why those didn't create an issue? Did weblogic converted them to String before passing it to method?

Friday, November 11, 2011

Generating dynamic elements in struts !!

Thanks to http://www.techtamasha.com/generate-dynamic-ids-for-struts-html-tags/



Do you use struts tags to generate html content?
If yes, then sooner or later you'll come across a scenario where you would generate html elements in an array
I faced a similar predicament recently. I had no other option but to use scriptlets to generate id's for the html elements



However, I soon found out using scriptlets within the struts html tags isn't really straight forward.

Here's the code I tried in my first attempt:

<%int i=0;%>
//iteration logic here
<html:text property="example[<%=i%>]" styleid="example<%=i%>"/>


Well, if you write the code as shown above, the html code generated would be :

<input type="text" name="example[<%=i%>]" id = "example<%=i%>">

and not

<input type="text" name="example[0]" id="example0">

To get the expected result, i.e. for the scriptlet to work inside the struts html tag, write as below:

<html:text property='<%="example["+i+"]"%>'
        styleid='<%="example"+i%>'/>


Please note that the name of the elements should be like this if you want them to read in Action Class via Action Form.
example[0], example[1], example[2], example[3]......and so on...

What do one needs to retrieve these values in Action Class


STRUTS : java.lang.IllegalAccessException

STRUTS : java.lang.IllegalAccessException: Class org.apache.struts.util.RequestUtils can not access a member of class view.myAction with modifiers "

PROBLEM

SOLUTION

Cannot find bean org.apache.struts.taglib.html.BEAN in any scope

I was getting the following exception when I tried to execute an Action Class...
Everything in struts-config.xml, web.xml, the TLDs in place seem to be perfect.
But still I got the following exception.


500 Internal Server Error (Click for full stack trace)
javax.servlet.jsp.JspException: Cannot find bean org.apache.struts.taglib.html.BEAN in any scope



Solution

The mistake I was doing was that I had used <html:text> tag without using <html:form> in the JSP file.

Always remember that you should have <html:text tag inside <html:form

Best Practices to improve Performance in JSP

This topic illustrates the performance improvement best practices in JSP with the following sections:

Overview of JSP

Use jspInit() method as cache

Optimization techniques in _jspService() method

Optimization techiques in jspDestroy() method

Optimization techniques in page directive

Choosing right include mechanism

Choosing right session scope in useBean action

Choosing the custom tags versus non custom tags

Cache the static and dynamic data

Choosing the right session mechanism

Control session

Disable JSP auto reloading

Control Thread pool

Key Points

Thursday, November 10, 2011

How to expand collapse (toggle) div layer using jQuery

Thanks to http://designgala.com/how-to-expand-collapse-toggle-div-layer-using-jquery

In almost all of my projects, I have been using jQuery to toggle the layer. So, I thought of sharing how easy it is to expand div layer and collapse panel using jQuery. When user clicks on the header, the content gets displayed by sliding down and when you again click on the header, the content collapses.

Step 1: Include jQuery Library in head section of your html file.


Step 2:


Step 3:


Step 4:

Thats it!! Expandible-Collapsible panel is ready.

What? You want to see a demo.......This post is the demo in itself :)

Caution: When using this in blogger


Because the blogger already has a div with class content which is the parent of all the divs in the page. Hence You need to rename the content class to some other suitable name, before you try to use it with blogger.



How to execute a DOS command from a different working directory using java?

At many times we require to execute a DOS command from within a specific directory.
How do we do that? Here is a utility class that I have written for this purpose.
You don't even need to look into the functions to use this.
Simply add the class to your code and call the executeCommand function.

Util.executeCommand("dir", "D:\\Yogesh");

Click to see more

Thursday, November 3, 2011

Change set getter....

Tool for Fetching the files changed in an activity from clearcase.

/**
** Author : Yogesh Gandhi 
**/

package changeset;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;



public class myFrame extends JFrame {

    JLabel lblViewName  = new JLabel("View Name");
    JLabel lblActivityName  = new JLabel("Activity Name");
    JLabel lblDataVOB  = new JLabel("Datavob");
    JTextField  txtViewName = new JTextField("yogesh_bankmed_cod_payout", 30);
    JTextField  txtActivityName = new JTextField("P_1783_312227_LastPageIssue_InitiateCalculationScreen", 30);
    JTextField  txtDataVOB = new JTextField("pay_datavob", 30);
    JButton jbutton = new JButton("Get Change List");
 public myFrame(String title) {
        super(title);
        jbutton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String filePath="C:\\temp.txt";
                String viewName = txtViewName.getText();
                String activityName = txtActivityName.getText();
                String datavob = txtDataVOB.getText();
                String command = "cleartool lsactivity -l " +
                                 viewName + "@\\" +
                                 datavob + " activity \"" +
                                 activityName+"\"";
                String steps[]= new String[3];
                steps[0]="cmd.exe";
                steps[1]="/C";
                steps[2]=command ;
                Process proc=null;
                Process proc2=null;
                try
                {
                    proc=Runtime.getRuntime().exec(steps, null, new File("M:\\"+viewName));//, envp);
                    InputStream stdin = proc.getInputStream();
                    InputStreamReader isr = new InputStreamReader(stdin);
                    BufferedReader br = new BufferedReader(isr);
                    String line = null;
                    StringBuffer bf = new StringBuffer("");
                    Set files = new HashSet();
                    while ( (line = br.readLine()) != null)
                    {
                        if(line.indexOf("@@")!=-1)
                        {
                            line = line.substring(0, line.indexOf("@@"));
                            files.add(line + "\r\n");
                        }
                        else
                        {
                            bf.append(line+"\r\n");
                        }
                    }
                    int exitVal = proc.waitFor();
                    if(proc!=null)
                    {
                        proc.exitValue();
                    }
                    write2File(bf.toString(), files, filePath);
                    proc2 = Runtime.getRuntime().exec("notepad.exe "+filePath);

                    System.out.println("Process exitValue: " + exitVal);

                }
                catch(Exception ee)
                {
                    if(proc!=null)
                    {
                        proc.destroy();
                    }
                    JOptionPane.showMessageDialog(null, ee.getMessage());
                    ee.printStackTrace();;
                }
                finally
                {
                    if(proc!=null)
                    {
                        proc.destroy();
                    }
                    System.exit(0);
                }

            }
        });

        getContentPane().setLayout(new FlowLayout());
  getContentPane().add(lblViewName);
        getContentPane().add(txtViewName);
        getContentPane().add(lblActivityName);
        getContentPane().add(txtActivityName);
        getContentPane().add(lblDataVOB);
        getContentPane().add(txtDataVOB);
        getContentPane().add(jbutton);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
  this.setSize(350, 300);
  setVisible(true);
 }

    private void write2File(String content, Set set, String filePath) throws Exception
    {
        FileWriter writer = new FileWriter(new File(filePath));
        writer.write(content);
        Iterator it = set.iterator();
        while(it.hasNext())
        {
            writer.write(it.next().toString());
        }
        writer.flush();
        writer.close();
    }
    /**
     *
     * @param args
     */
    public static void main(String[] args)
    {
  new myFrame("Developed by Yogesh Gandhi");
    }
}