I recently had to do a project in PHP and being from Java background one notices enumerable similarities. Obviously the whole knowledge about object-oriented programming and the procedural constructs like assignments, statements, conditions, loop etc are totally transferable. However the key difference I noticed was in the function calls. In Java all the arguments are passed by value, even for the objects, ie we pass the copy of the address for the object. But in PHP we are allowed to pass arguments by value or reference. Thus we have a simple function
function writeName($name) { echo $name; }
it passes the $name argument as value. However, by just prefixing $name with an ampersand we pass the argument by reference to give
function writeName(&$name) { echo $name; }
The other clever thing about PHP function is that we can return a value by reference too. Take the example from Joomla! library:
function &getLanguage()
{
static $instance;
if (!is_object($instance))
{
//get the debug configuration setting
$conf =& JFactory::getConfig();
$debug = $conf->getValue('config.debug_lang');
$instance = JFactory::_createLanguage();
$instance->setDebug($debug);
}
return $instance;
}
Preceding the getLanguage() function by an ampersand indicates that the function will return a value by reference, thus the return is a pointer to $instance.
The another line which will puzzle Java programmers above is
$conf =& JFactory::getConfig();
=& the syntax simply means that $conf is being assigned reference to the object created by getConfig() method of JFactory class. :: notation indicates that we are invoking a class method rather than an instance method. The normal Java dot notation of object.method() for invoking an instance method is changed in PHP to object->method()
Armed with the knowledge in this article a Java programmer is ready to do a PHP project. The only other thing to bear in mind is that the class constructor is defined by function __construct(). Obviously one will have to come to grips with various PHP functions but this should be no different from understanding a new Java API.
Sunday, May 23, 2010
Friday, April 23, 2010
Selectors in Cascading Style Sheets
The indispensable tool in every web developers portfolio is Cascading Style Sheets (CSS). Once HTML has been used to organize the contents, the presentational brilliance stems from using CSS rules. Syntactically the rules have a selector followed by a declaration containing various properties separated by semicolons:
p {color:blue; font-weight:normal;}
This simple tag selector rule colours all the contents of
tags in the HTML document. Also noted that the property-value combination is defined by separating the property from its value with a colon. Instead of p we could have used any of the html elements like h1, h2 etc. To apply the rule to a group of elements we simply use a selector with comma separated the elements. For example, if we want to override the h3, h4, h5 and h6 header elements default definition of the browser, we can just use group selector:
h3, h4, h5, h6 {color:black; font-size:1.2em;)
The commonest way of formatting content is to use the class selector in conjunction with <div> block element or <span> inline element.
.myClass {color:black; font-size:1.2em;) class selector has a period prefix. Currently it will apply to any tag which has attribute definition of class="myClass". For example, if we have the following in our document:
<p class="myClass">...</p>
<div class="myClass">...</div>
then the .myClass selector will apply the declaration formatting to both these elements. To just restrict the formatting to
element, we change the selector to p.myClass in our rule.
Along with class, id is another attribute which can be placed on most elements. Indeed, javascript uses id to get the elements. So if we have <p id="myID"> then the hash prefixed selector for this element becomes:
#myID {color:black; font-size:1.2em;)
We also have pseudo-classes and pseudo-elements available as selectors. The anchor pseudo-classes are used to invariably define link interaction with a:link, a:visited, a:hover and a:active selectors. We know that these stages happen with links. Similarly, the first line of a paragraph or a first letter of the paragraph doesn't have a tag but it is easily identifiable pseudo-element so we can have a selectors like:
p:first-letter {color: blue;font-size:1.5em;}
or
p:first-line {color: blue;font-size:1.5em;}
Similarly there are pseudo-elements after and before for auto-generated content. To prefix a paragraph with a class="intro" with 'Thought of the day!' auto-generated content, we have the selector syntax:
p.intro:before {content: "Thought of the day!" }
or to give the text after the paragraph:
p.intro:after {content: "Thought of the day!" }
To style tags within tags we have descendant selector. For example, to highlight emphasis within a paragraph we may use the selector:
h1 strong { color: red; }
Here sub-element <strong> within element <h1> is coloured red. Similarly if we wanted to select the ordered lists which are direct children of body element the syntax is body > ol for the rule. Note the angle bracket is used for the child selector. Or to get to an adjacent sibling we use the plus ('+') sign instead of the angle bracket.
We can also select on the attributes. These selectors allow us to select element which have a certain property. For example to select all the images with title attribute we will have a selector img[title]. Or to just select text boxes in a form we can have the attribute selector
input[type="text"]
There are some further refinements to these selector but the knowledge is acquired by experimentation. The aspects covered are more than adequate.
For a good source for understanding the selectors visit here.
CSS: The Missing Manual
is a very useful resource which you should have in your collection.
p {color:blue; font-weight:normal;}
This simple tag selector rule colours all the contents of
tags in the HTML document. Also noted that the property-value combination is defined by separating the property from its value with a colon. Instead of p we could have used any of the html elements like h1, h2 etc. To apply the rule to a group of elements we simply use a selector with comma separated the elements. For example, if we want to override the h3, h4, h5 and h6 header elements default definition of the browser, we can just use group selector:
h3, h4, h5, h6 {color:black; font-size:1.2em;)
The commonest way of formatting content is to use the class selector in conjunction with <div> block element or <span> inline element.
.myClass {color:black; font-size:1.2em;) class selector has a period prefix. Currently it will apply to any tag which has attribute definition of class="myClass". For example, if we have the following in our document:
<p class="myClass">...</p>
<div class="myClass">...</div>
then the .myClass selector will apply the declaration formatting to both these elements. To just restrict the formatting to
element, we change the selector to p.myClass in our rule.
Along with class, id is another attribute which can be placed on most elements. Indeed, javascript uses id to get the elements. So if we have <p id="myID"> then the hash prefixed selector for this element becomes:
#myID {color:black; font-size:1.2em;)
We also have pseudo-classes and pseudo-elements available as selectors. The anchor pseudo-classes are used to invariably define link interaction with a:link, a:visited, a:hover and a:active selectors. We know that these stages happen with links. Similarly, the first line of a paragraph or a first letter of the paragraph doesn't have a tag but it is easily identifiable pseudo-element so we can have a selectors like:
p:first-letter {color: blue;font-size:1.5em;}
or
p:first-line {color: blue;font-size:1.5em;}
Similarly there are pseudo-elements after and before for auto-generated content. To prefix a paragraph with a class="intro" with 'Thought of the day!' auto-generated content, we have the selector syntax:
p.intro:before {content: "Thought of the day!" }
or to give the text after the paragraph:
p.intro:after {content: "Thought of the day!" }
To style tags within tags we have descendant selector. For example, to highlight emphasis within a paragraph we may use the selector:
h1 strong { color: red; }
Here sub-element <strong> within element <h1> is coloured red. Similarly if we wanted to select the ordered lists which are direct children of body element the syntax is body > ol for the rule. Note the angle bracket is used for the child selector. Or to get to an adjacent sibling we use the plus ('+') sign instead of the angle bracket.
We can also select on the attributes. These selectors allow us to select element which have a certain property. For example to select all the images with title attribute we will have a selector img[title]. Or to just select text boxes in a form we can have the attribute selector
input[type="text"]
There are some further refinements to these selector but the knowledge is acquired by experimentation. The aspects covered are more than adequate.
For a good source for understanding the selectors visit here.
CSS: The Missing Manual
Wednesday, April 14, 2010
Delight of w3schools
Like countless other people I have used the tutorials at w3schools to become familiar with various technologies at different stages in my life. It is impossible to be not familiar with this site for anyone who has taken delight in learning new things. I recall learning about ASP, XPath etc on this site a number of years ago. Indeed a career in IT is impossible without constantly updating ones skill base so a comprehensive training resource is a real boon. The site invariably appears in the top searches whenever 'Ajax tutorial' or 'jquery tutorial' type terms are used in google so cannot escape the radar of any technology aficionado. For last couple of years I had been hearing good things about jquey so decided to take the plunge and become familiar with the framework yesterday. Needless to say that w3schools gave me a couple of hours of real pleasure. There tutorial seem basic but they get to the heart of the matter. Their examples were lucid and their jquery engine for practising is great. So here is a public thanks for being so useful. W3schools, you rock!
Wednesday, March 31, 2010
The brave new world
The pressure on IT has always been there to deliver. I recall the 80s when the business-IT alignment was on everybody's lips, the 90s when the IT-facilitated business process re-engineering and kaizan were talk of the town and the new economic order was proclaimed by the web-based companies at the turn of the century. IT was always deemed indispensable in these initiatives but adjudged to be slow to meet the business needs. The bursting of the dotcom bubble and the y2k experience tarnished the IT image but did not abet the pressure on IT to facilitate inter-organisational processes in a globalised world. IT's role was still at the heart of 'making it happen'. One assumed that the ERP systems had taken care of all the transactional needs at the operational level and the datawarehouses and business intelligence tools had enamoured the business executives by adding value to strategy formulation. Now comes the frightening reminder that all is not well in the wake of global financial meltdown.
"Capital expenditure priorities are shifted into IT from other high-payback projects" just to perform necessary ERP changes, claims one executive. Whilst another bemoans: "Change to ERP paralyzes the entire organization in moving forward in other areas that can bring more value."
An Accenture partner sees rising tide of operational flexibility on daily basis and proclaims "strategy, as we knew it, is dead." A paradigm shift in IT's execution is expected and demanded in this new world order. Yet the top priority for 2009 was "modernizing key legacy applications" and the SOA, the pre-requisite for flexibility, seemed fatally wounded.
It is a challenge to all the IT professionals to acquire a mindset attuned with business imperatives and successfully deploy disruptive technologies to make a quantum change. The decade ahead of us is full of potential and we must not fail.
"Capital expenditure priorities are shifted into IT from other high-payback projects" just to perform necessary ERP changes, claims one executive. Whilst another bemoans: "Change to ERP paralyzes the entire organization in moving forward in other areas that can bring more value."
An Accenture partner sees rising tide of operational flexibility on daily basis and proclaims "strategy, as we knew it, is dead." A paradigm shift in IT's execution is expected and demanded in this new world order. Yet the top priority for 2009 was "modernizing key legacy applications" and the SOA, the pre-requisite for flexibility, seemed fatally wounded.
It is a challenge to all the IT professionals to acquire a mindset attuned with business imperatives and successfully deploy disruptive technologies to make a quantum change. The decade ahead of us is full of potential and we must not fail.
Tuesday, March 30, 2010
SOAP with Attachment API for Java (SAAJ) example
SAAJ is an indispensable tool for manipulating SOAP messages, especially if they have got attachments. We have illustrated all the steps in creating a SwA (SOAP Messages with Attachments) in the short self-explanatory example which can be adapted for all purposes.
package saajexample;
import java.awt.Image;
import java.awt.Toolkit;
import javax.xml.soap.*;
public class Main {
public static void main(String[] args) throws Exception {
// Factory needed to create SOAP message
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
// illustrate the story so far by dumping out the message
message.writeTo(System.out);
// detach the header from the SOAP Envelope
message.getSOAPHeader().detachNode();
System.out.println("");
message.writeTo(System.out);
// manipulate the body of the SOAP message
SOAPBody body = message.getSOAPBody();
SOAPElement getStockPrice = body.addChildElement(
"getStockPrice",
"rt",
"http://www.rajeev.com/jws/StockQuote");
System.out.println("");
message.writeTo(System.out);
getStockPrice.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);
System.out.println("");
message.writeTo(System.out);
SOAPElement code = getStockPrice.addChildElement("stockCode");
System.out.println("");
message.writeTo(System.out);
code.addTextNode("IBM");
System.out.println("");
message.writeTo(System.out);
// attach an image
Image image = Toolkit.getDefaultToolkit().createImage("raj.jpg");
AttachmentPart jpegAttach = message.createAttachmentPart();
// use setDataHandler method below if connecting to FileDataSource object for pdf file
jpegAttach.setContent(image, "image/jpeg");
// add the mime type for the image
jpegAttach.addMimeHeader("Content-Transfer-Encoding", "binary");
jpegAttach.setContentId("xxx");
message.addAttachmentPart(jpegAttach);
System.out.println("");
// message.writeTo(System.out); // cannot stream image
// check attachment created successfully
System.out.printf("Number of attachments: %d%n", message.countAttachments());
// remove the attachment and verify
message.removeAllAttachments();
System.out.printf("Number of attachments: %d%n", message.countAttachments());
}
}
package saajexample;
import java.awt.Image;
import java.awt.Toolkit;
import javax.xml.soap.*;
public class Main {
public static void main(String[] args) throws Exception {
// Factory needed to create SOAP message
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
// illustrate the story so far by dumping out the message
message.writeTo(System.out);
// detach the header from the SOAP Envelope
message.getSOAPHeader().detachNode();
System.out.println("");
message.writeTo(System.out);
// manipulate the body of the SOAP message
SOAPBody body = message.getSOAPBody();
SOAPElement getStockPrice = body.addChildElement(
"getStockPrice",
"rt",
"http://www.rajeev.com/jws/StockQuote");
System.out.println("");
message.writeTo(System.out);
getStockPrice.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);
System.out.println("");
message.writeTo(System.out);
SOAPElement code = getStockPrice.addChildElement("stockCode");
System.out.println("");
message.writeTo(System.out);
code.addTextNode("IBM");
System.out.println("");
message.writeTo(System.out);
// attach an image
Image image = Toolkit.getDefaultToolkit().createImage("raj.jpg");
AttachmentPart jpegAttach = message.createAttachmentPart();
// use setDataHandler method below if connecting to FileDataSource object for pdf file
jpegAttach.setContent(image, "image/jpeg");
// add the mime type for the image
jpegAttach.addMimeHeader("Content-Transfer-Encoding", "binary");
jpegAttach.setContentId("xxx");
message.addAttachmentPart(jpegAttach);
System.out.println("");
// message.writeTo(System.out); // cannot stream image
// check attachment created successfully
System.out.printf("Number of attachments: %d%n", message.countAttachments());
// remove the attachment and verify
message.removeAllAttachments();
System.out.printf("Number of attachments: %d%n", message.countAttachments());
}
}
Monday, March 29, 2010
JAXB tutorial
XML is the lingua franca of the web services world. Unsurprisingly, the ability to process XML documents simply is an essential requirement. To my mind DOM and SAX parsers are the equivalent of assembler programming compared to the high-level programming provided by the Java Architecture for XML Binding, JAXB. It is an essential tool in every Java developer's portfolio. But many tutorials on the web hark back to JAXB1.0 so here is something to get you started.
The JAXB tutorial provided by Rose India is rather dated now. The IBM resource was a fairly good introduction to Java-XML mapping once upon a time but the Sun/Oracle JAXB tutorial is simply amazing.
Rarely a tutorial is written which is as comprehensive as the one provided here. All the aspects of mapping XML Schema Language types to Java, marshalling Java-based tree content to XML, unmarshalling from XML-to-Java, ObjectFactory class, XML annotations, the JAXB schema compiler (xjc) et al have been covered very lucidly.
If it still doesn't satisfy your curiosity then the book JAXB 2.0
is all you need for all the JAXB requirements but unfortunately it is in German.
Here is a sample code to marshal and unmarshal a simple letter written by me to Helen of Troy.
package raj;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Letter {
/**
* The sender of the letter.
*/
private String sender;
/**
* The receiver.
*/
private String receiver;
/**
* A unique number for the message number sent .
*/
private int messageNo;
/**
* The missive despatched.
*/
private String message;
public Letter() {
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getMessageNo() {
return messageNo;
}
@XmlAttribute
public void setMessageNo(int messageNo) {
this.messageNo = messageNo;
}
public String toString() {
return String.format("Letter %s from %s to %s, saying '%s'", messageNo, sender, receiver, message);
}
public static void main(String[] arg) {
Letter text = new Letter();
text.setSender("Rajeev Trikha");
text.setMessageNo(2010);
text.setReceiver("Helen of Troy");
text.setMessage("Welcome to my world of JAXB in 2010!");
// Create a JAXB context and a marshaller
try {
// here just using a class as an argument but normally is a package
JAXBContext context = JAXBContext.newInstance(Letter.class);
Marshaller marshaller = context.createMarshaller();
// Set the output in formatted manner
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Make the actual serialization
marshaller.marshal(text, new File("raj.xml"));
Unmarshaller unmarshaller = context.createUnmarshaller();
// Get the object
Letter msg = (Letter) unmarshaller.unmarshal(new File("raj.xml"));
System.out.println(msg);
} catch (Exception e) {
System.out.println("exc");
}
}
}
The marshalled file raj.xml shows the created XML message which is well indented.
The unmarshalling prints out to the console:
Letter 2010 from Rajeev Trikha to Helen of Troy, saying 'Welcome to my world of JAXB in 2010!'
If you are using Netbeans then check out for understanding how xjc is tied up within the product.
The JAXB tutorial provided by Rose India is rather dated now. The IBM resource was a fairly good introduction to Java-XML mapping once upon a time but the Sun/Oracle JAXB tutorial is simply amazing.
Rarely a tutorial is written which is as comprehensive as the one provided here. All the aspects of mapping XML Schema Language types to Java, marshalling Java-based tree content to XML, unmarshalling from XML-to-Java, ObjectFactory class, XML annotations, the JAXB schema compiler (xjc) et al have been covered very lucidly.
If it still doesn't satisfy your curiosity then the book JAXB 2.0
Here is a sample code to marshal and unmarshal a simple letter written by me to Helen of Troy.
package raj;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Letter {
/**
* The sender of the letter.
*/
private String sender;
/**
* The receiver.
*/
private String receiver;
/**
* A unique number for the message number sent .
*/
private int messageNo;
/**
* The missive despatched.
*/
private String message;
public Letter() {
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getMessageNo() {
return messageNo;
}
@XmlAttribute
public void setMessageNo(int messageNo) {
this.messageNo = messageNo;
}
public String toString() {
return String.format("Letter %s from %s to %s, saying '%s'", messageNo, sender, receiver, message);
}
public static void main(String[] arg) {
Letter text = new Letter();
text.setSender("Rajeev Trikha");
text.setMessageNo(2010);
text.setReceiver("Helen of Troy");
text.setMessage("Welcome to my world of JAXB in 2010!");
// Create a JAXB context and a marshaller
try {
// here just using a class as an argument but normally is a package
JAXBContext context = JAXBContext.newInstance(Letter.class);
Marshaller marshaller = context.createMarshaller();
// Set the output in formatted manner
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Make the actual serialization
marshaller.marshal(text, new File("raj.xml"));
Unmarshaller unmarshaller = context.createUnmarshaller();
// Get the object
Letter msg = (Letter) unmarshaller.unmarshal(new File("raj.xml"));
System.out.println(msg);
} catch (Exception e) {
System.out.println("exc");
}
}
}
The marshalled file raj.xml shows the created XML message which is well indented.
The unmarshalling prints out to the console:
Letter 2010 from Rajeev Trikha to Helen of Troy, saying 'Welcome to my world of JAXB in 2010!'
If you are using Netbeans then check out for understanding how xjc is tied up within the product.
Saturday, March 20, 2010
CORBA or web services
CORBA has the key advantage of being truly object-oriented component architecture and comes with a host of standard services like naming, transactions, printing, events etc which support complex applications in a heterogeneous environment in a platform and language independent manner. For example, there is no equivalent of CORBA Security service in web service environment and only now the suppliers have started addressing these aspects. So the disadvantage of web services over CORBA is that it is reinventing-the-wheel and cannot handle the required amount of complexity in its current state. However the complexity of CORBA, the issues with its specification and the slowness of new development have opened way for web services which are more suited to web-environment with their loose coupling, XML and HTTP usage. The SOAP messages of web services are simple to use and implement. Unsurprisingly, this simplicity has given momentum to web services over CORBA.
Java Web Services: Up and Running
is one of the most up-to-date and practical books on web services.
Java Web Services: Up and Running
Subscribe to:
Posts (Atom)