Monday, January 31, 2011

Super Simple Guide to Setup Andriod

1. Install eclipse helios from website www.eclipse.org.
2. Install java sdk, jre 6 + from www.java.com.. latest one.
3. Download Andriod SDK zip file or exe incase of windows.
4. Step Java Home and Jre Home i think you know this.
5. Start eclipse.
6. Go to Help -> Install New Software and put in http://dl-ssl.google.com/android/eclipse/
7. A Developers Tools will come in the second section and install all the packages.
8. Go to Windows >Preferences>Andriod and now point to the location where Andriod SDK was installed.
9. It should not give any errors and should recognize the sdk or something is wrong with the installation.
10. Now restart eclipse. You will see Andriod Icon below the Tool bar. Click on that Icon that will open up the Emulator and AVD manager.
11. Now In Virtual Devices>New>Target you will see the andriod.
12. Your Andriod setup is complete.
13. In point you will also see avaliable packages. Download Samples.
14. Now in eclipse create new andriod project and select the project from existing resource option and browse to one of the sample projects. Finish.
15. Now Run that project. If everything done properly it will work for you. These are just the gist of steps.

If you like comment on it..Cheers.

Saturday, January 29, 2011

Liferay Http Session

Simplified way to do it...
Create 2 portlets Test1 and Test2 in Eclipse

1.
In first portlet Test1 - view.jsp

<jsp:useBean class="java.lang.String" id="submitURL" scope="request" />

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<portlet:defineObjects />

This is the <b>Test</b> portlet.
<form action="/WEB-INF/html/test2.jsp" method="post">
<input type="submit" button="submit" value="submit" />
</form>


2.
 a
Set the Jsp Portlet Class in portlet.xml
eg.
<portlet-name>Test</portlet-name>
        <display-name>Test</display-name>
        <portlet-class>com.liferay.TestPortlet(this you have to change in your code)</portlet-class>
        <init-param>
            <name>view-jsp</name>

b
Create a new class file of the first portlet

package com.liferay;

import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.PortletSession;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import com.liferay.portal.util.PortalUtil;

public class TestPortlet extends GenericPortlet {

    public void init() throws PortletException {
        editJSP = getInitParameter("edit-jsp");
        viewJSP = getInitParameter("view-jsp");
    }

    public void doView(RenderRequest renderRequest,
            RenderResponse renderResponse) throws IOException, PortletException {

        PortletURL submit = renderResponse.createActionURL();
        submit.setParameter("submit", "submit");
        renderRequest.setAttribute("submitURL", submit.toString());
        include(viewJSP, renderRequest,
                renderResponse);
    }

    public void processAction(ActionRequest actionRequest,
            ActionResponse actionResponse) throws IOException, PortletException {
        System.out.println("hi");
        HttpServletRequest diffReq = PortalUtil.getHttpServletRequest(actionRequest);
        HttpSession hs = diffReq.getSession(true);;
        hs.setAttribute("LIFERAY_SHARED_test","test");
        System.out.println(hs.getId());
        actionResponse.sendRedirect("http://localhost:8082/web/guest/page2");
//        actionResponse.setPortletMode(PortletMode.VIEW);
    }

    protected void include(String path, RenderRequest renderRequest,
            RenderResponse renderResponse) throws IOException, PortletException {
        PortletRequestDispatcher portletRequestDispatcher = getPortletContext()
                .getRequestDispatcher(path);
        if (portletRequestDispatcher == null) {
        } else {
            portletRequestDispatcher.include(renderRequest, renderResponse);
        }
    }
   
    protected String editJSP;
    protected String viewJSP;


}

2.
Now go to Second Portlet-view.jsp

<jsp:useBean id="bean1" class="java.lang.String" scope="request"/>
<%@page import="javax.servlet.http.HttpServletRequest"%>
<%@page import="javax.servlet.http.HttpServletResponse"%>
<%@page import="javax.servlet.http.HttpSession"%>
<%@ page import="com.liferay.portal.util.PortalUtil" %>
<%@page import="java.util.*" %>

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<portlet:defineObjects />

This is the <b>First Portlet</b> portlet.
Hello
<%       
HttpServletRequest convertReq = PortalUtil.getHttpServletRequest(renderRequest);
HttpSession hs = convertReq.getSession();
String sessionid = hs.getId();
HttpSession hs1 =request.getSession();
String sessionid1=hs1.getId();
String name1="";
%>
<%=sessionid %>
<%=sessionid1 %>
<%
if(hs.getAttribute("LIFERAY_SHARED_test")!=null){
name1=hs.getAttribute("LIFERAY_SHARED_test").toString();}
else{
    name1="Empty";
}
%>
wow<%=name1 %>
<%
Enumeration e = hs.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = hs.getAttribute(name).toString();
System.out.println("name is: " + name + " value is: " + value);
}
%>

4. Now in liferay-portlet.xml of both the portlets set <private-session-attributes>false</private-session-attributes>
eg...
    <icon>/icon.png</icon>
        <private-session-attributes>false</private-session-attributes>
        <header-portlet-css>/css/main.css</header-portlet-css>
        <footer-portlet-javascript>/js/main.js</footer-portlet-javascript>
        <css-class-wrapper>Test-portlet</css-class-wrapper>


5. Start Liferay.Deploy both the portlets one on first page and second one on the other page



Liferay Sessions

Liferay Session Sharing Demystified

Liferay’s session sharing mechanism has always been a bit of a mystery. As with most things Liferay, documentation is minimal, and leaves a lot of questions to be answered. I’d like to share with you what I’ve learnt after testing a bunch of scenarios, and hopefully this will be good reference material for all of you developing portlets on Liferay.
My scenarios focus on how Liferay’s sessions behave for different combinations of the private-session-attributes settings; between the portal, portlets (in the same WAR, and across different WARs) and the servlets in these WARs. This also means that only APPLICATION_SCOPE attributes are relevant to the discussion.
Testing was performed on Liferay 4.3.6, and consisted of basic JSR-168 portlets , and basic Servlet Spec servlets. To emulate code running in the portal scope, a simple servlet Filter was configured on the Portal application.

Private Session True

This is the default setting, in which each WAR has its own session. The session within each WAR is private, and nothing is shared between individual WARs. Portlets and Servlet within the same WAR file will be able to share the session, because they are in the same context. So far, this conforms to the Servlet spec.
Liferay provides an additional functionality under this setting. As the official FAQ states, it also allows shared (namespaced) attributes set by the portal to be visible from portlets. Any session attribute with the configured prefix (e.g. LIFERAY_SHARED_) will be copied over and be visible by the portlets, hence granting private portlets read-access to session attributes set by the portal. This is illustrated in diagram 1.
Diagram 1

Private Session False

All portlets under this setting will share the same session, and also share this same session with the portal. This is the easiest way for portlets in individual WAR files to communicate with each other.
However, the downside to this is that servlets in these WAR files will not be able to communicate with the portlets at all. (This is a question often raised in the forums, and one I struggled with for a while to figure out). The most convenient way to think of this is that portlets with this setting use the portal session, and have no access to the WAR session. This is illustrated in diagram 2.
Diagram 2

Mixed Scenarios

Diagram 3 depicts the interaction between a private and non-private portlet in individual WAR files. Portlet A, being non-private, has full communication with the portal, but cannot talk to Servlet A. Portlet B, being private, has full communication with Servlet B, but only has read-only access to Portal shared attributes.
You will notice arrow from Portlet A to Portlet B is dotted because this communication happening indirectly through the portal session. Portlet A is using the portal session, so any shared attributes that it sets will also be copied over to Portlet B, and can be read.
Diagram 3 Diagram 4 expands on diagram 3, and adds another private portlet to WAR B. Both of the portlets in B are private, meaning they are using the WAR session, so they can freely communicate with each other and the servlet. Same as the previous example, they will be able to read shared attributes set by the portal, or by any non-private portlet like Portlet A.
Diagram 4 Diagram 5 is a bit more interesting. Here, Portlet B has been changed to non-private, meaning it will use the portal session. That is why it can now freely communicate with the portal and Portlet A. However, just like anything else using the Portal session, it cannot read the WAR session of B anymore, even though it is in the same WAR! While this may seem a little counter-intuitive, it is consistent with the behaviour we have seen so far.
Diagram 5

Copying shared attributes to a Servlet

Update: Liferay has a built in mechanism for calling servlets from the portal context, giving them access to the portal session.
You may have noticed so far that the servlets cannot directly read the shared attributes of the portal session. But you can get around this by using a private portlet as a proxy. Diagram 6 shows the flow of how a shared attribute x, set by non-private Portlet A, will be stored in the portal session and subsequently copied to private Portlet B. Portlet B, having write access to WAR session B, can set another attribute y to the same value as x, and y can be read by the servlet.
Diagram 6

Overwriting shared attributes from private portlets?

We know that any session attributes set by private portlets cannot be seen by the portal, or by any other non-private portlets. But what happens if the private portlet sets an attribute of the same key as the shared attribute?
Diagram 7 In Diagram 7, the flow is depicted more accurately by showing two sessions – the Portal session and the WAR session of B. I will walk through the numbered scenario as follows:
  1. Non-private Portlet A sets a session attribute LIFERAY_SHARED_foo to “alice” . This is stored in the portal session.
  2. Private Portlet B reads the attribute LIFERAY_SHARED_foo. Since this is a shared attribute, it has read access, and returns the value “apple” .
  3. Private Portlet B2 now sets the same session attribute LIFERAY_SHARED_foo to “bob” . Because it is a private portlet, the value is written to the WAR session.
  4. When Portlet B tries to read the attribute again, it returns the value “bob”. This shows that values in the WAR session override those copied from the portal. If at this point Portlet A were to set the attribute again, Portlet B cannot see the change.
  5. Portlet B2 now removes the session attribute LIFERAY_SHARED_foo
  6. When Portlet B tries to read the attribute again, it returns the value “alice” from the portal session.
This example shows that when private portlets tries to read an attribute, it will first read the attribute from the WAR session. If it can’t be found, it will try to read from any shared attributes copied from the Portal session.

Summary

I am not a core Liferay developer, so I’m not sure what the underlying implementation really is. However, my observations are consistent with the following summary:
  • Non-private portlets read and write to the Portal session.
  • Private portlets write to their own WAR session.
  • Private portlets try to read from their own WAR session first, then looks up any shared attributes copied from the Portal session.
  • Servlets only have access to the WAR session, and cannot directly access the Portal session. In order to read shared session attributes, servlets need a private portlet in the same WAR file to copy it for them. Or you can configure your servlet to use the portal session by using Liferay's PortalDelegateServlet mechanism.
I hope this has helped you in your understanding of Liferay’s session sharing mechanism. If you are a core Liferay developer, please let me know if I have made any mistakes, or if you have anything else to add. I’d be keen to know if this is still relevant to Liferay 4.4.x

Friday, January 28, 2011

Cannot find the tag library descriptor for "http://java.sun.com/jsp/jstl/core--Jstl Error in eclipse

If jstl error 
Download from http://jakarta.apache.org/site/downloads/downloads_taglibs-standard-1.0.cgi
and include standard.jar and jstl.jar in build path and lib folder

Steps to Install Mysql on Windows

Download 
mysql-5.0.22-win32.exe and Install as standard.
mysql-administrator-1.1.9-win

http://dev.mysql.com/downloads/mysql/
http://techtracer.com/2008/06/09/3-easy-steps-to-install-mysql-on-windows-xp/
start mysql client from desktop>Start> program files>mysql


mysql>
 create database employees;
 show databases;
 USE employees;
CREATE TABLE employee_data
(
emp_id int unsigned not null auto_increment primary key,

f_name varchar(20),
l_name varchar(20),
title varchar(30),
age int,
yos int,
salary int,
perks int,
email varchar(60)
);

Also can use mysql Administrator to check the creation of table and database.

Ajax Mysql Php Example

<html>
<head>
   
<script src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript">
</script>

    <script type="text/javascript">
      function register(){
    //    window.open("/welcome.html",'welcome','width=300,height=200,menubar=yes,status=yes,location=yes,toolbar=yes,scrollbars=yes');

        $.ajax({
            type: "POST",
            url: "/ReturnData.php",
            data:     "username=" + document.getElementById("username").value + 
                    "&email=" + document.getElementById("email").value,
            success: function(html){
                $("#response").html(html);
            }
        });
        }
    </script>
  </head>



<body>
    <form action="" method="post">
            <p>
                <label for="name">Name:</label><br />
                <input type="text" name="username" id="username" size="25" />
            </p>
            <p>
                <label for="email">Email:</label><br />
                <input type="text" name="email" id="email" size="25" />
            </p>
            <p>
                <input type="button" name="submit" id="submit" value="Subscribe" onclick="register()"/>
            </p>
            <ul id="mylist">
                <li><a rel="3" href="/#dave">Dave's email address</a></li>
                <li><a rel="4" href="/#erik">Erik's email address</a></li>
            </ul>

<p id="info">&nbsp;</p> 
    <div id="response">

    </div>
</form>
</body>
</html>


<?php
                $db_host = 'localhost';
                $db_user = 'root';
                $db_pass = 'root';
                $db_name = 'db';

        $Username = $_POST['username'];
        $Email    = $_POST['email'];
      
        $connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error());
        $connection = $connect;

        mysql_select_db( $db_name, $connect ) or die( mysql_error() );

         echo $Username;
        $qInsertUser = mysql_query(" INSERT INTO test
                                     VALUES ('$Username','$Email')
                                  ");
        $qGetDetails = mysql_query("SELECT * FROM test");
    
    
         $num=mysql_numrows($qGetDetails);
         echo $num;
         echo "hi";
        $i=0;
        while ($row=mysql_fetch_array($qGetDetails)) {
        echo "<br>".$row['name'];
        }
    ?>

Ajax Json Php Example

Ajax Json Php example
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$('document').ready(function() 
{ 
    $('#mylist a').click(function ()
    {
        var id = $(this).attr('rel');

        $.getJSON('/return.php', {'id' : id}, parseInfo);
    });
});

function parseInfo(data)
{
    $('#info').html(data.name +', '+ data.email);
}
</script> 
</head>
<body>
<ul id="mylist">
   <li><a rel="3" href="#">Dave's email address</a></li>
    <li><a rel="4" href="#">Erik's email address</a></li> 
</ul>

<p id="info">&nbsp;</p> 
</body>
</html>

 
<?php

// see if we have a GET variable 'id' set
$id = (isset($_GET['id']) && !empty($_GET['id'])) ? $_GET['id'] : 0;

// pretend this is a query to a database to fetch the wanted users.
$users[3] = array('name' => 'Dave', 'email' => 'dave@adeepersilence.be');
$users[4] = array('name' => 'Erik', 'email' => 'erik@bauffman.be');

// only if an ID was given and the key exists in the array, we continue
if(!empty($id) && key_exists($id, $users))
{
    // echo (not return) the wanted record from the users array
    echo json_encode($users[$id]);
}

?>

Php Ajax Mysql Example

<html>
<head>
   
<script src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript">
</script>

    <script type="text/javascript">
      function register(){
        alert("hi" +document.getElementById("username").value); 
        $.ajax({
            type: "POST",
            url: "/submit_data.php",
            data:     "username=" + document.getElementById("username").value + 
                    "&email=" + document.getElementById("email").value,
            success: function(html){
                $("#response").html(html);
            }
        });
    
        }
    </script>
  </head>



<body>
    <form action="" method="post">
            <p>
                <label for="name">Name:</label><br />
                <input type="text" name="username" id="username" size="25" />
            </p>
            <p>
                <label for="email">Email:</label><br />
                <input type="text" name="email" id="email" size="25" />
            </p>
            <p>
                <input type="button" name="submit" id="submit" value="Subscribe" onclick="register()"/>
            </p>
<div id="response">
        <!-- Our message will be echoed out here -->
    </div>
</form>
</body>
</html>


<?php
                $db_host = 'localhost';
                $db_user = 'root';
                $db_pass = 'root';
                $db_name = 'db';

        $Username = $_POST['username'];
        $Email    = $_POST['email'];
      
        $connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error());
        $connection = $connect;

        mysql_select_db( $db_name, $connect ) or die( mysql_error() );

     
        $qInsertUser = mysql_query(" INSERT INTO test
                                     VALUES ('$Username','$Email')
                                  ");

       if ($qInsertUser){
           echo "You are now subscribed to our newsletter. Thank you!";
        } else {
            echo "Error!";
        }

    ?>

Good link for php and apache2

Upload file example php

Test.html
<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>
 
----------------
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>
 
Upload.php
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Change the root directory in apache2 other than htdocs


In htttpd.conf file in Apache installation folder change the below C:/ProgramFiles/Apache2 repoint to the folderr where you want to place files
DocumentRoot "C:/phpfiles/php"
Directory "C:/phpfiles/php"


or under sites-enabled  folder change DocumentRoot and Directory in 000-default

Install Php on Windows


Steps:
1.  http://www.php.net/downloads.php download the zip file unzip at C:/php
Download and install apache2 http://httpd.apache.org/download.cgi
httpd-2.2.17-win32-x86-no_ssl.msi

2 Go C:/Program Files/Apache2. In httpd.conf of Apache Software Foundation/conf add the following code


LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
3.
# configure the path to php.ini which is present at location C:/php find
PHPIniDir "C:/php"
4. In C:\Apache Software Foundation\Apache2.2\htdocs place the file
test.php

echo "Hello World";
?>
Now start apache2 by clicking on exe in bin folder.

If you want to change the path to other than htdocs go to sites-enabled folder 000-default  in C:/Program File/Apache2....
and change the DocumentRoot to folder you want.

5. http://localhost:8080/test.php should generate the hello world.
Reference

Install Mysql http://harshal-techapps.blogspot.com/2011/01/steps-to-install-mysql-on-windows.html
To configure with Mysql

1. Uncomment the line extension=php_mysql.dll in php.ini which is present in C:/php
2. Set this path extension_dir = "C:\php\ext" in php.ini
3. To change the upload file location
;upload_tmp_dir =
4. Uncomment session.save_path = "C:\WINDOWS\temp"
5. Copy the php.ini to C:\Windows
6.Next we must add the PHP directory to the Windows PATH. To do this, click: Start > My Computer > Properties > Advanced > Environment Variables. Under the second list (System Variables), there will be a variable called "Path". Select it and click "Edit". Add ";C:\php" to the very end of the string and click "OK".
7. In mysql follow the steps below:
use test;
create table name ()
select * from name;
8. Place the attached file at location : C:\Apache Software Foundation\Apache2.2\htdocs
9. Restart the computer and all the servers.
11. Should display
ID: 1
Name: John
Hello
Links for linux

Java NameSpace with XML


 import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class NameSpaceXMLExample {
   
    public static final void main(String[] args) {
       
       String xmlFile="/home/localadmin/test2.xml";
       
        try {
            NameSpaceXMLExample xmlTester = new NameSpaceXMLExample(xmlFile);
        }
        catch (Exception e) {
            System.out.println( e.getClass().getName() +": "+ e.getMessage() );
        }
    }
   
    public NameSpaceXMLExample(String xmlFile) throws ParserConfigurationException, SAXException, IOException {


        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        System.out.println("DocumentBuilderFactory: "+ factory.getClass().getName());
       
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
       
        // Specify our own schema - this overrides the schemaLocation in the xml file
        //factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:./test.xsd");
       
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler( new SimpleErrorHandler() );


        Document document = builder.parse(xmlFile);
        String customerMakeAndModel ="";
        try{
            NodeList nodes = document.getElementsByTagName("ns0:Test");
                Element line = (Element) nodes.item(0);
                                //String data = getCharacterDataFromElement(line);
                                if (getCharacterDataFromElement(line) != null) {
                                    customerMakeAndModel=getCharacterDataFromElement(line);
                                    System.out.println(customerMakeAndModel);
                                } else {
                                    customerMakeAndModel="";
                                }
        }catch(Exception e){
            customerMakeAndModel="";
        }   
       
        Node rootNode  = document.getFirstChild();
   //     System.out.println("Root node: "+ rootNode.getNodeName()  );
    }

public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
    }
    return "";
}
}

XML file
 ;ltns0:ABC xmlns:ns0="http://ABC/1.0">
 ;lttns0:Test<ABC;&gt

 ;lt/ns0:ABC>

Java NameSpace with XML


 import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;


public class NameSpaceXMLExample {
  
    public static final void main(String[] args) {
      
       String xmlFile="/home/localadmin/test2.xml";
      
        try {
            NameSpaceXMLExample xmlTester = new NameSpaceXMLExample(xmlFile);
        }
        catch (Exception e) {
            System.out.println( e.getClass().getName() +": "+ e.getMessage() );
        }
    }
  
    public NameSpaceXMLExample(String xmlFile) throws ParserConfigurationException, SAXException, IOException {


        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        System.out.println("DocumentBuilderFactory: "+ factory.getClass().getName());
      
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
      
        // Specify our own schema - this overrides the schemaLocation in the xml file
        //factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:./test.xsd");
      
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler( new SimpleErrorHandler() );


        Document document = builder.parse(xmlFile);
        Node rootNode  = document.getFirstChild();
        System.out.println("Root node: "+ rootNode.getNodeName()  );
    }





  
}

Read from a file in java

    public static String readFile(){
        System.out.println("Reading Dummy file");
        StringBuilder contents = new StringBuilder();
        File aFile = new File("/home/localadmin/test.xml");
        try {
              BufferedReader input =  new BufferedReader(new FileReader(aFile));
              try {
                String line = null;
                while (( line = input.readLine()) != null){
                  contents.append(line);
                  contents.append(System.getProperty("line.separator"));
                }
              }
              finally {
                input.close();
              }
            }
            catch (IOException ex){
              ex.printStackTrace();
            }
           
    return contents.toString();


    }

Thursday, January 27, 2011

Java And Tibco Practical Example

Tibco Standard Class example

package com.tibco;
/*
 * Copyright 2001-2006 TIBCO Software Inc.
 * All rights reserved.
 * For more information, please contact:
 * TIBCO Software Inc., Palo Alto, California, USA
 *
 * $Id: tibjmsQueueRequestor.java 21731 2006-05-01 21:41:34Z $
 *
 */

/*
 * This is a simple sample of basic QueueRequestor.
 *
 * This sample publishes specified message(s) on a specified
 * queue and quits.
 *
 * Notice that specified queue should exist in your configuration
 * or your queues configuration file should allow
 * creation of the specified queue.
 *
 * This sample can send into dynamic queues thus it is
 * using the QueueSession.createQueue() method
 * to obtain the Queue object.
 *
 * Usage:  java tibjmsQueueRequestor  [options]
 *                                  <message-text1>
 *                                  ...
 *                                  <message-textN>
 *
 *
 *    where options are:
 *
 *      -server     Server URL.
 *                  If not specified this sample assumes a
 *                  serverUrl of "tcp://localhost:7222"
 *
 *      -user       User name. Default is null.
 *      -password   User password. Default is null.
 *      -queue      Queue name. Default is "queue.sample"
 *
 *
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.codec.DecoderException;


public class TibjmsQueueCompositeForMDN
{
    /*
    String      serverUrl       = null;
    String      userName        = null;
    String      password        = null;

    String      queueName       = "queue.sample";

    Vector      data            = new Vector();
    Calendar calendar = Calendar.getInstance();
    Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance()
            .getTime().getTime());

    String TimeStamp = currentTimestamp.toString();
   
   
   

   
    static public String getContents(String args) {
        StringBuilder contents = new StringBuilder();
        try {
            BufferedReader input = new BufferedReader(new FileReader(args));
            try {
                String line = null;
                while ((line = input.readLine()) != null) {
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }

            } finally {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return contents.toString();
    }

    public TibjmsQueueCompositeForMDN(String[] args) {

        parseArgs(args);

        /* print parameters
        System.out.println("\n------------------------------------------------------------------------");
        System.out.println("------------------------------------------------------------------------");
        System.out.println("Server....................... "+(serverUrl!=null?serverUrl:"localhost"));
        System.out.println("User......................... "+(userName!=null?userName:"(null)"));
        System.out.println("Queue........................ "+queueName);
        System.out.println("------------------------------------------------------------------------\n");
       
       

        try
        {
            TibjmsUtilities.initSSLParams(serverUrl,args);
        }
        catch (JMSSecurityException e)
        {
            System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode());
            e.printStackTrace();
            System.exit(0);
        }

        if (queueName == null)
        {
            System.err.println("Error: must specify queue name");
            usage();
        }

        if (data.size() == 0)
        {
            System.err.println("Error: must specify at least one message text");
            usage();
        }

        System.err.println("Publishing into queue: '"+queueName+"'\n");

        try
        {
            QueueConnectionFactory factory = new com.tibco.tibjms.TibjmsQueueConnectionFactory(serverUrl);

            QueueConnection connection = factory.createQueueConnection(userName,password);

            QueueSession session = connection.createQueueSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);

            /*
             * Use createQueue() to enable sending into dynamic queues.
            
            javax.jms.Queue queue = session.createQueue(queueName);

            javax.jms.TemporaryQueue tempqueue = session.createTemporaryQueue();

            QueueSender sender = session.createSender(queue);

            QueueReceiver receiver = session.createReceiver(tempqueue);
            System.out.println(tempqueue.getQueueName());

            connection.start();
            sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            /* publish messages
            for (int i=0; i<data.size(); i++)
            {
                javax.jms.TextMessage message = session.createTextMessage();
                String text = (String) data.elementAt(i);
                  //    message.setJMSReplyTo(getMDNResponseTempQueue);
                message.setJMSReplyTo(tempqueue);
                message.setText(getContents(text));
                sender.send(message);
                System.out.println("Sent Message:"+message.toString());
                File sentXmlFile = new File(text);
            //    System.err.println("Sent message: " + message);
                //logger.info(message.toString());
                if(sentXmlFile!=null)
            //    WriteFileToDisk.writeDisk(sentXmlFile,getContents(text),storeLocation);
                com.sax.parser.SaxXmlParser.logSentFile(sentXmlFile);
            }
            javax.jms.Message replymsg=null;
            replymsg = receiver.receive(20000);
            System.out.println("Received Reply: "+replymsg);
            receiver.close();
            session.close();
            tempqueue.delete();
            connection.close();
        }
        catch(JMSException e)
        {
            e.printStackTrace();
            System.exit(0);
        }
        catch(Exception e1){}
    }
*/
   
    static public String getContents(String args) {
        StringBuilder contents = new StringBuilder();
        try {
            BufferedReader input = new BufferedReader(new FileReader(args));
            try {
                String line = null;
                while ((line = input.readLine()) != null) {
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }

            } finally {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return contents.toString();
    }

    public static void main(String args[])
    {
        //TibjmsQueueCompositeForMDN t = new TibjmsQueueCompositeForMDN(args);
        String url = args[0];
        String strXMLFilename = args[1];
        System.out.println("Sent File\n"+getContents(strXMLFilename).toString());
        File input = new File(strXMLFilename);
        PostMethod post = new PostMethod(url);
        try{
        post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
        }catch(IOException e){
            e.printStackTrace();
        }
        Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance()
                .getTime().getTime());

        String TimeStamp = currentTimestamp.toString();
       
       
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.addRequestHeader("Service", "OGO");
        post.addRequestHeader("Method", "dfg");
        post.addRequestHeader("Version", "1.1");
        post.addRequestHeader("Culture", "en-US");
        post.addRequestHeader("TimeStamp", TimeStamp);
        post.addRequestHeader("SystemUsername", "DemoUsername");
        post.addRequestHeader("SystemPassword", "DemoPassword");
        post.addRequestHeader("LineOfBusiness", "IRO");
        post.addRequestHeader("Application", "ADB");
        post.addRequestHeader("Client", "ABC");
        post.addRequestHeader("Channel", "WEB");
        post.addRequestHeader("QueueName","sfsdf.fsdfs.PolicyAdministration.ProcessEnrollments.Request");
       
       
        HttpClient httpclient = new HttpClient();
        try{
            int result = httpclient.executeMethod(post);
               System.out.println("Response status code: " + result);
               System.out.println("Resquest Header: " + result);
               Header[] ha = post.getRequestHeaders();
               for(int i=0;i<ha.length;i++){
                   System.out.println(ha[i]);
               }
              
            System.out.println("Response body: "+post.getResponseBodyAsString());
            System.out.println("Response body: "+post.getStatusText());
        } catch(Exception e){
            e.printStackTrace();
        }finally {
            post.releaseConnection();
        }
    }
/*
    void usage()
    {
        System.err.println("\nUsage: java tibjmsQueueRequestor [options]");
        System.err.println("                                <message-text1 ... message-textN>");
        System.err.println("");
        System.err.println("   where options are:");
        System.err.println("");
        System.err.println(" -server    <server URL> - EMS server URL, default is local server");
        System.err.println(" -user      <user name>  - user name, default is null");
        System.err.println(" -password  <password>   - password, default is null");
        System.err.println(" -queue     <queue-name> - queue name, default is \"queue.sample\"");
        System.err.println(" -help-ssl               - help on ssl parameters\n");
        System.exit(0);
    }

    void parseArgs(String[] args)
    {
        int i=0;

        while(i < args.length)
        {
            if (args[i].compareTo("-server")==0)
            {
                if ((i+1) >= args.length) usage();
                serverUrl = args[i+1];
                i += 2;
            }
            else
            if (args[i].compareTo("-queue")==0)
            {
                if ((i+1) >= args.length) usage();
                queueName = args[i+1];
                i += 2;
            }
            else
            if (args[i].compareTo("-user")==0)
            {
                if ((i+1) >= args.length) usage();
                userName = args[i+1];
                i += 2;
            }
            else
            if (args[i].compareTo("-password")==0)
            {
                if ((i+1) >= args.length) usage();
                password = args[i+1];
                i += 2;
            }
            else
            if (args[i].compareTo("-help")==0)
            {
                usage();
            }
            else
            if (args[i].compareTo("-help-ssl")==0)
            {
                TibjmsUtilities.sslUsage();
            }
            else
            if(args[i].startsWith("-ssl"))
            {
                i += 2;
            }
            else
            {
                data.addElement(args[i]);
                i++;
            }
        }
    }
*/
}

TibcoUtilities.java

package com.tibco;


/*
 * This sample uses JNDI to retrieve administered objects.
 *
 * Optionally all parameters hardcoded in this sample can be
 * read from the jndi.properties file.
 *
 * This file also contains an SSL parameter helper class to enable
 * an SSL connection to a TIBCO Enterprise Message Service server.
 *
 */

import javax.jms.*;
import javax.naming.*;
import java.util.Hashtable;
import java.util.Vector;
import java.security.*;


public class TibjmsUtilities
{
    static Context jndiContext = null;

    static final String  providerContextFactory =
                            "com.tibco.tibjms.naming.TibjmsInitialContextFactory";

    static final String  defaultProtocol = "tibjmsnaming";

    static final String  defaultProviderURL =
                            defaultProtocol + "://localhost:7222";

    public static void initJNDI(String providerURL) throws NamingException
    {
        initJNDI(providerURL,null,null);
    }

    public static void initJNDI(String providerURL, String userName, String password) throws NamingException
    {
        if (jndiContext != null)
            return;

        if (providerURL == null || (providerURL.length() == 0))
            providerURL = defaultProviderURL;

        try
        {
                Hashtable env = new Hashtable();
                env.put(Context.INITIAL_CONTEXT_FACTORY,providerContextFactory);
                env.put(Context.PROVIDER_URL,providerURL);

                if (userName != null) {

                    env.put(Context.SECURITY_PRINCIPAL,userName);

                    if (password != null)
                        env.put(Context.SECURITY_CREDENTIALS,password);
                }

                jndiContext = new InitialContext(env);
        }
        catch (NamingException e)
        {
                System.out.println("Failed to create JNDI InitialContext with provider URL set to "+
                                providerURL+", error = "+e.toString());
                throw e;
        }
    }

    public static Object lookup(String objectName) throws NamingException
    {
        if (objectName == null)
            throw new IllegalArgumentException("null object name not legal");

        if (objectName.length() == 0)
            throw new IllegalArgumentException("empty object name not legal");

        /*
         * check if not initialized, then initialize
         * with default parameters
         */
        initJNDI(null);

        /*
         * do the lookup
         */
        return jndiContext.lookup(objectName);
    }


    /**
     * This method creates a java.Security.SecureRandom object seeded with
     * the current time.  It allows the samples that use SSL to initialize
     * the SSL environment much faster than if they had to generate a truly
     * random seed.
     *
     * NOTE: THIS SHOULD NOT BE USED IN A PRODUCTION ENVIRONMENT AS IT IS
     *       NOT SECURE.
     */
     public static SecureRandom createUnsecureRandom()
             throws JMSSecurityException {

        try {
             SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
             sr.setSeed(System.currentTimeMillis());

            return sr;

        } catch(NoSuchAlgorithmException e) {
          JMSSecurityException jmse =
                new JMSSecurityException("Error creating SecureRandom object: " + e.getMessage());
          jmse.setLinkedException(e);
          throw jmse;
        }
    }


    public static void initSSLParams(String serverUrl,String[] args) throws JMSSecurityException{
        if (serverUrl != null && serverUrl.indexOf("ssl://") >= 0) {
           SSLParams ssl = new SSLParams(args);

           ssl.init();
        }
    }

    public static void sslUsage()
    {
        System.err.println("\nSSL options:");
        System.err.println("");
        System.err.println(" -ssl_vendor               <name>      - SSL vendor: 'j2se' or 'entrust6'");
        System.err.println(" -ssl_trace                            - trace SSL initialization");
        System.err.println(" -ssl_vendor_trace                     - trace SSL handshake and related");
        System.err.println(" -ssl_trusted[n]           <file-name> - file with trusted certificates,");
        System.err.println("                                         this parameter may repeat if more");
        System.err.println("                                         than one file required");
        System.err.println(" -ssl_verify_hostname                  - do not verify certificate name.");
        System.err.println("                                         (this disabled by default)");
        System.err.println(" -ssl_expected_hostname    <string>    - expected name in the certificate");
        System.err.println(" -ssl_custom                           - use custom verifier (it shows names");
        System.err.println("                                         always approves them).");
        System.err.println(" -ssl_identity             <file-name> - client identity file");
        System.err.println(" -ssl_issuer[n]            <file-name> - client issuer file");
        System.err.println(" -ssl_private_key          <file-name> - client key file (optional)");
        System.err.println(" -ssl_password             <string>    - password to decrypt client identity");
        System.err.println("                                         or key file");
        System.err.println(" -ssl_ciphers              <suite-name(s)> - cipher suite names, colon separated");
        System.exit(0);
    }

private static class SSLParams implements com.tibco.tibjms.TibjmsSSLHostNameVerifier {
        String          ssl_vendor                  = null;
        boolean         ssl_trace                   = false;
        boolean         ssl_debug_trace             = false;
        boolean         ssl_verify_hostname         = false;
        String          ssl_expected_hostname       = null;
        Vector          ssl_trusted                 = null;
        Vector          ssl_issuers                 = null;
        String          ssl_identity                = null;
        String          ssl_private_key             = null;
        String          ssl_password                = null;
        boolean         ssl_custom                  = false;
        String            ssl_ciphers             = null;

        public SSLParams(String[] args) {
            int     trusted_pi      = 0;
            String  trusted_suffix  = "";
            int     issuer_pi      = 0;
            String  issuer_suffix  = "";

            int i=0;
            while(i < args.length)
            {
                if (args[i].compareTo("-ssl_vendor")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_vendor = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_trace")==0)
                {
                    ssl_trace = true;
                    i += 1;
                }
                else
                if (args[i].compareTo("-ssl_debug_trace")==0)
                {
                    ssl_debug_trace = true;
                    i += 1;
                }
                else
                if (args[i].compareTo("-ssl_expected_hostname")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_expected_hostname = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_verify_hostname")==0)
                {
                    ssl_verify_hostname = true;
                    i += 1;
                }
                else
                if (args[i].compareTo("-ssl_custom")==0)
                {
                    ssl_custom = true;
                    i += 1;
                }
                else
                if (args[i].compareTo("-ssl_ciphers")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_ciphers = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_identity")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_identity = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_private_key")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_private_key = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_password")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_password = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_trusted"+trusted_suffix)==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    String cert = args[i+1];
                    if (cert == null) continue;
                    if (ssl_trusted == null)
                        ssl_trusted = new Vector();
                    ssl_trusted.addElement(cert);
                    trusted_pi++;
                    trusted_suffix = String.valueOf(trusted_pi);
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_issuer"+issuer_suffix)==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    String cert = args[i+1];
                    if (cert == null) continue;
                    if (ssl_issuers == null)
                        ssl_issuers = new Vector();
                    ssl_issuers.addElement(cert);
                    issuer_pi++;
                    issuer_suffix = String.valueOf(issuer_pi);
                    i += 2;
                }
                else
                {
                    i++;
                }
            }
        }

        public void init() throws JMSSecurityException {
            if (ssl_trace)
                com.tibco.tibjms.TibjmsSSL.setClientTracer(System.err);

            if (ssl_debug_trace)
                com.tibco.tibjms.TibjmsSSL.setDebugTraceEnabled(true);

            if (ssl_vendor != null)
                com.tibco.tibjms.TibjmsSSL.setVendor(ssl_vendor);

            if (ssl_expected_hostname != null)
                com.tibco.tibjms.TibjmsSSL.setExpectedHostName(ssl_expected_hostname);

            if (ssl_custom)
                com.tibco.tibjms.TibjmsSSL.setHostNameVerifier(this);

            if (!ssl_verify_hostname)
                com.tibco.tibjms.TibjmsSSL.setVerifyHostName(false);

            if (ssl_trusted != null) {
                for (int i=0; i<ssl_trusted.size(); i++) {
                    String certfile = (String)ssl_trusted.elementAt(i);
                    com.tibco.tibjms.TibjmsSSL.addTrustedCerts(certfile);
                }
            }
            else {
                com.tibco.tibjms.TibjmsSSL.setVerifyHost(false);
            }

            if (ssl_issuers != null) {
                for (int i=0; i<ssl_issuers.size(); i++) {
                    String certfile = (String)ssl_issuers.elementAt(i);
                    com.tibco.tibjms.TibjmsSSL.addIssuerCerts(certfile);
                }
            }
            if (ssl_identity != null)
                com.tibco.tibjms.TibjmsSSL.setIdentity(
                        ssl_identity,ssl_private_key,ssl_password.toCharArray());

            if (ssl_ciphers != null)
                com.tibco.tibjms.TibjmsSSL.setCipherSuites(ssl_ciphers);

            /*
             * Install our own random number generator which is fast but not secure!
             */
            com.tibco.tibjms.TibjmsSSL.setSecureRandom(createUnsecureRandom());
        }

        public void verifyHostName(String connectedHostName,
                                   String expectedHostName,
                                   String certificateCN,
                                   java.security.cert.X509Certificate server_certificate)
                    throws JMSSecurityException
        {
            System.err.println("HostNameVerifier: "+
                    "    connected = ["+connectedHostName+"]\n"+
                    "    expected  = ["+expectedHostName+"]\n"+
                    "    certCN    = ["+certificateCN+"]");

            return;
        }
    }
}



In the lib folder or class path add the jar files

commons-codec-1.4.jar
jms.jar
slf4j-api-1.4.2.jar
slf4j-simple-1.4.2.jar
tibcrypt.jar
tibemsd_sec.jar
tibjms.jar
tibjmsadmin.jar
tibjmsapps.jar
tibrvjms.jar



Pass the arguments to the class file from the command prompt