Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Mar Java Jazz Up Java Jazz Up Mar Editorial Dear Readers, March Volume I Issue IX Optimism with determination lets you hit the goal harder We are back here with the Holi Mar issue of Java Jazzup. The current edition is specially designed for the sprouting technocrats. This issue highlights the interesting Java technologies especially for the beginners. Though it was a hard job to simplify the complexities of the technologies like Hibernate ., struts , JSF and Design Patterns. Still our team has done a marvelous work in making it easy and simpler for the new programmers regime. This issue reflects our consistent attempts to avail the quality technological updates that enforce the readers to appreciate it a lot and be a part of its Readers Community. Java News and Updates section provides the latest updates of the things happening around the globe making the readers aware of the java technological advancement. In this section, you will know the new features introduced in the existing tools, utilities, application servers, IDEs, along with the Java API updates. We are providing it in a PDF format so that you can view and even download it as a whole and get its hard copy. Please send us your feedback about this issue and participate in the Readers Forum with your problems, issues concerned with the topics you want us to include in our next issues. EditorinChief Deepak Kumar Java Jazz up Published by RoseIndia JavaJazzUp Team EditorinChief Deepak Kumar EditorTechnical Ravi Kant Sr. Graphics Designer Suman Saurabh Graphics Designer Santosh Kumar Amardeep Patel Register with JavaJazzUp and grab your monthly issue Free Mar Java Jazz Up Content Java News Testing and optimizing Java code without test automation for handling concurrent activities is rather difficult. Introduction to XSL XSL stands for EXtensible Stylesheet Language. The World Wide Web Consortium WC started to develop XSL because there was a need for an XMLbased Stylesheet Language. Thus it is a language for expressing Stylesheets. JAXP API using DOM Parser In the previous issue of Java Jazz Up, you have read about the JAXP APIs and learned how an XML document is parsed using the serially access mode SAX parser. Struts . This tutorial provides you a better understanding to develop a robust application using Jakarta Struts Framework. Struts Nonform Tags UItags Apache Struts is an opensource framework used to develop Java web applications. In this section, struts nonform tags UItags will be discussed. Design Pattern These types of design patterns are used as templates. These design patterns are used in such conditions when we need a parent class having one or more methods to be implemented by their child classes. Visitor Design Pattern The design pattern provides additional functionality to a class. The Visitor pattern allows us to create an external class to act on data in other classes. Dojo Tutorial Dojo Dojo is an Open Source JavaScript toolkit libraries that provides a simple APIApplication Programming Interface for building the serious applications in less time. Hibernate Query Language In the previous issue of Javajazzup you learned about Hibernate Query Language and its different kind of clauses. Lets quickly focus on the overview of HQL. Using the Desktop class to launch a URL with default browser in Java This article describes the new Desktop API, which allows Java applications to interact with the default applications associated with specific file types on the host platform. Advertise with Us We are the top most providers of technology stuffs to the java community. Our technology portal network is providing standard tutorials, articles, news and reviews on the Java technologies to the industrial technocrats. Valued JavaJazzup Readers Community We invite you to post Javatechnology oriented stuff. It would be our pleasure to give space to your posts in JavaJazzup. Java Jazz Up Mar Java News and Releases Concurrency Testing in Java Applications Testing and optimizing Java code without test automation for handling concurrent activities is rather difficult. Even with test automation, being able to correlate the test activity from the client side to observations of thread, memory, object and database connection use on the server side is difficult at best. This tool describes methods to test concurrency in Java applications and also displays the new technique for correlating about the task that a Java application server is doing on the server side however a load test automation tool drives a test on the client side. Most of the IT managers consent about the concurrency testing that it is the right way to determine many performance bottlenecks, resource contention issues, and service interruptions. However, only few of the developers use concurrency testing because the available test tools are not satisfactory. New Features in EJB . New features are added to the EJB .. Experts are trying to make changes to the EJB . for the next version of the Java EE specification. The idea behind these changes is to provide the heads up on the changes as well as gather your feedback early so the expert group has the best chance of getting it right. EJB . is made simple to Java EE by moving away from a heavyweightprogramming model. EJB . targets to build the successes movement down the path of simplicity along with a handful of muchneeded features. The features added to EJB . makes the interfaces optional for EJBs and Singleton Beans, but none of the features has been finalized yet all of this is really just a peek into the inner workings of the JCP so that you have a chance provide early feedback. . EJB Interfaces are Optional In EJB ., now you do not need to define any interfaces for Session Beans, just like JPA Entities and Message Driven Beans. All you have to do is annotate a POJO with the Stateless or Stateful to get a fully functional EJB. . The Singleton Beans A new feature of Singleton Beans is added in EJB . that is used to store applicationwide shared data. The JEE container maintains a single shared instance of an EJB . Singleton that can cache state across the application tier. Like all other EJBs, Singletons are simply annotated POJOs. . Support for direct use of EJBs in the servlet container, including simplified packaging options. Like the web.xml file that resides in the WEBINF directory, you would be able to place an EJB jar into the WEBINF/lib directory. . Support for stateful web services via Stateful Session Bean web service endpoints. Mar Java Jazz Up simultaneously. choosing the desired set of server plugins e. we think that the Java EE requirements add significant value to standalone technologies. Gshell It is a commandline processing environment required to execute Geronimo administrative commands.g. The idea behind Java EE is to rewrite such type of requirements. by the large number of servlet containers implementing JTA so that it is compatible with what Java EE mandates. The logic includes two components the first one is that. concerning the relevant combination of technologies. calling out the requirements that helps to ensure that applications that target profiles will work on the full platform.Java News and Releases Load Balancing Tomcat with Apache Tomcat is the most popular application server that is used for hosting web applications. E. Released . greatly simplifies the buildtime customization. It allows the users to follow a functioncentric approach. Comet Reverse Ajax for streaming data from the server Comet is a technology that pushes the events from the server side to a browser client. WADI Clustering Now WADI enables to cluster Web Applications for both Tomcat and Jettybased configurations of Geronimo. But Comet is all about concerning the last process having the same vanilla technologies like Ajax namely JavaScript and Java Jazz Up Mar . Profiles in the Java EE Platform Profiles are an attempt to modularize the different parts in Java EE so that the technologies can be combined in a product. release of Geronimo. provides the following new features Custom Server Assemblies Geronimo . which can be applied to any profiles and implementations.. Apache Geronimo team announced the release of Apache Geronimo . Web ContainerJMSDeploy capabilities.g. Geronimo . Richclient technologies such as Flash or Java this process seems original particularly since these last technologies have combined mechanisms such as remoting and steaming that deals with asynchronous requests from both server to client and vice versa.g any product corresponding to any Java EE profile including servlets as well as JTA will have to be sincere to those requirements. URL rewriting etc.Java EE server Recently. as testified e. Apache Geronimo . Apache also serves as a load balancer for balancing the load between several Tomcat application servers. E. Apache is also popular web server that enables services such as https encryption and decryption. as those technologies will be tied together in interesting ways. deliver more functionality than they would on their own. Flexible Administration Console Now the Geronimo Administration Console matches the dynamic capabilities of the server runtime. such as those occurring in the stock market or in sporting matches. This will help in solving the issue of compatibility requirements in order to provide the natural approach by spanning the multiple technologies. It avoids the issues related to having a browser poll a server to check for new events. is developed on the Java EE certified . Comet looks at the nature of realtime events.g Java EE specification contains requirements to which the servlet containers must honor with respect to the availability of JTA. This whole phenomena makes profiles more than just collections of independently tested technologies. Apache Geronimo . Blue Edition is in Milestone stage . This new Blue Edition has a cost only per year. on It is a better static analyzer identify a variety of bugs and potential bugs in Java code. It can analyze class files and/or source files. This is available for download sourceforge. Mar Java Jazz Up .. While there are many of the performance tools available for Java leverage the application server and its APIs in just this fashion. MyEclipse Blue Edition LowCost Tool Alternative for WebSphere Genuitec announced the new release of a product. With ending support to WebSphere Application Developer WSAD. Since many of these IBM shops are necessarily requiring changing their tool environments. a technique that will surely be of the same impact and go hand in hand with what we know today as Ajax. FindBugs Released new version Version . Blue Edition is the new edition offering a complimentary toolsuite for a tiny fraction of the cost to the RAD users. server that is a transition having high cost in terms of time and hard currency.. Comet is different to Ajaxs meaning outside IT circles as a household cleaner. as the application failures are the larger aspect of application maintenance. new features are created as if they were being built in maintenance mode instead of being made out of whole cloth. App Performance Management Scenario Changing Java Developers Role Developers are spending most of their time in maintaining existing applications. rather than deploying and testing the application and finding out after quotcompletionquot that it doesnt meet its performance requirements. The other maintenance obstacle is performance performance is managed in a better way by assuming it as an attribute of the code throughout development.net. FindBugs recently released a new version Version . and can be installed. MyEclipse . You donot need to worry about nullifying your existing support contracts. Youre free to use as MyEclipse Blue Edition uses IBMs own Web Services. This is not the new task as most of the developers rarely admit the new development. MyEclipse Blue Edition that targets IBMs Rational Application Developer RAD and WebSphere development. and provides a full support. A lot of tools exist to impose the specific problems therefore most of the application management lifecycle are spending their time in finding specific problems. But sudden name or not. all WebSphere users necessitates to upgrade their toolsuites to IBM RAD so that they can support the latest features in the WebSphere . MyEclipse . The first maintenance obstacle is testing The whole application can be tested. Comet serves the purpose of an umbrella name for delivering data onto browsers as it becomes available on the serverside. and provided as a tool to download and use upto April st. Agile development helps by forcing for more tests throughout the entire lifecycle.Java News and Releases HTML. instead of actually developing new features. However concerning with the actual term. Genuitec has offered a choice to the consumers. by monitoring the boundaries between APIs. using Java application servers helps in isolating the performance issues as they provide a central node for monitoring. Two processes avoid most of the maintenance work while the SSQ article mentions only one of them. This changes the scenario of development that tends to be a little more workmanlike than wed like to admit sometimes. even in the new projects.. Iteration over a flat Rope a Rope having depth of is much faster than pulling data character by character from a String is the most considerable thing for an enterprise Java developer. which is a set of specifications to simplify SOA application development. a specification for dynamic modules for Java The Java Content Repository spec. multiple windows. access dlls. RTE provides some new capabilities like multithreaded. FindBugs quickly provides an overview of items required by the programmer in the java code. If you do not need to do this.. unlimited undo/redo etc. incubating released Apache Tuscany team has announced the release of the Java SCA project of version . first version released in May. improved policy support and an implementation extension for representing client side JavaScript applications as SCA components. New Networking features with PPF grid toolkit Releases in v.Java News and Releases It provides a bug tree. or distributed computing without using EJB Java Jazz Up Mar . It provides a runtime environment based on SCA Service Component Architecture. Provides a new networking tool i.. They are Java so it is very expandable. User can select an item in the bug tree and may get an explanation in the text panel. New Run Time Editor RTE for Java Released The new RTE is the control system interface design environment that has been designed for network control in java. multiple pages. group editing. RTE is fully written in OSGi. It is available for Windows and Linux environment. Recently JPPF i. appeared first time in the JCP in February Google Web Toolkit. Better graphical and programmatic tools reliability through redundancy failover recovery capabilities Apache Tuscany SCA Java .e. then Ropes are completely meaningless to you. unlimited run time editing/ scripting. Carlos Perez Top Five Java Technologies to Learn in Carlos Perez has posted a list of the top five Javabased technologies to learn in . provides pointers for effective use of the library and defines performance issues.e. MP and MPEG capabilities. multiprocessor aware. A rope data structure may be a better alternative. Java Parallel Processing Framework was released with version . Cloud computing. easy socket communication. standardized by OASIS. the TCP port multiplexer that allows it even to work in the fire walled environments Addition of new node monitoring feature PPF grid takes no time to be up and run provides highly scalable. shell scripting. grouping. builtin database access. Groovy. first version released in May. distributed framework for the execution of Java tasks. New features of JPPF Several bugs are fixed Theory and Practice of Ropes for Java String Manipulations Java languages default String and StringBuilder classes poorly serves to large quantities of data manipulated by the Systems. This release has added features like JMS binding. A rope implementation for the Java platform. a concept designed around the use of virtual servers. with competitions to spur awareness or active community involvement. yet it runs JavaScript if memory is available while HotJava did not. a web browser in Java JavaLobby have introduced a LoboBrowser. Apache Jackrabbit provides one of the best JCR implementations and was also used as the reference implementation of JSR .Java News and Releases However all the above technologies are holder technologies perhaps are coming of age and became matured to the point of recommendation. can be seen to anyone. Apache Jackrabbit .g providing browser support without allowing explicit browser tieins. Apache Jackrabbit . Apache Jackrabbit is the biggest ever release Mar Java Jazz Up having new features. but thats the wrong solution. It is big deal to develop a workable and installable fully Java based browser even if it cant render TSS very well. a fully Java web browser. E. by providing additional leverage in the open source community and also allowing access to MySQL to its larger corporations. The API provides various functionalities such as browsing. Hippo. and vendors are trying to address that. is a stable and featurerich content repository aimed having a wide range of content applications including Magnolia. released Apache Jackrabbit . and Mindquarry. locking. Sun Microsystems has agreed to buy MySQL AB for B Sun Microsystems has acceded to buy MySQL AB for B. but it always doesnt look like it. or shifting away from JavaDB/ Derby JVM Lies The OutOfMemory Myth The concept quotJVM Lies The OutOfMemory Myth. modifying. while Groovy is continuously accepting by the developer with its formal specification and continually improved releases. Integration into IDEs. Shades of HotJava LoboBrowser. and searching the content in full text search in a content repository. A content repository is a hierarchical representation storage media similar to an advanced file system supporting different levels of content structure and granularity. The grand question that arises is that what does this mean in the long term Sun already offers a smallscale database as compared to compared to large offerings like Oracle and IMS. provides the full open source implementation of JCR. improvements and bug fixes on the basis of feedback and contributions from the user community. is the latest and greatest version of Content Repository for Java Technology API or JCR in short conforming that Apache Jackrabbit . Although it is not HotJava. Standard allows advanced features like versioning. On the other hand. Is Sun considerably looking for an additional revenue stream from MySQL ABs customers. JCR is a standard API to access the content repositories in a uniform manner and is specified in JSR . and throws more RAM at the JVM may help. Corba that can be used to watch DOM of a page even after JavaScript has been run over it. .quot tells about the happening when a JVM throws an OutOfMemoryError the developers who have encountered it have noticed. It also includes a rendering engine. observation. But definitely all these technologies are still useful as OSGi works as module system behind Eclipse. and XA transactions as optional. OpenKM. and cloud computing is becoming more and more famous in this growing marketplace. it seems like its out of memory. GWT is already mature and stable. Jackrabbit provides implementation for all the mandatory and optional JCR features as well as a number of extensions and related JCR tools. JCR and cloud computing are the least accepted of these technologies. on the other hand Java is a statically typed objectoriented language. distributed and reliable systems.. Erlang is nothing but a functional programming language having native constructs for concurrency and reliability. but the main criteria include performance. uptimes of five nines or more.and surprise the binary protocols did far better on average than the XMLbased protocols. SJSWS . JavaMail . Solaris . will have the facility to upgrade to ServletExec . Erlang is a dynamically typed functional language. Java Web Services support through JAXWS . Erlang provides a trivial solution for Building scalable. for download and purchase http//www. Java Jazz Up Mar . Released New Atlanta has released ServletExec . Springs HttpInvoker. JavaServer Faces JSF . or . Java Remoting Protocol Benchmarks examines Javas RMI/JRMP. is required for ServletExec . Oracles ORMI with and without HTTP tunneling enabled.x. are Java Remoting Protocol Benchmarks Every client/server application may have different remoting requirements. Hessian and Burlap.x on or after November st.newatlanta. free of charge ServletExec is one of the original implementations of the Java Servlet API and around customers in countries has been purchased to this original implementation. A SimpleDB is webservice for running queries on structured data in real time. and three flavors of Apache XMLRPC and Cauchos Hessian. and quothot deploymentquot of code. The current version supports the following features Java Servlet API . Updated Web Server support IIS .com/products/ servletexec Key new features contained in ServletExec . HPUX v AMD/Intel bit support x Additional improvements are Improved Performance IPv Protocol support Improved Administrative Interface Important notes JDK/JRE . The two graphs are consistent a good sign for the libraries involved . JSP Standard Tag Library JSTL . Erlang is a programming language and Jinterface is an open source component of Ericssons Open Telecom Platform having capability to integrate Java with Erlang. New license for ServletExec . JavaServer Pages JSP . Java Persistence API JPA implementation for Amazon SimpleDB JPA provides implementation for SimpleDB. Article Integrating Java and Erlang Enterprise software development world introduces a new face Erlang. Apache . Erlang works as a agitator in case of traditional enterprise development as it is an standard similar to concurrency. will be provided to the existing customers with current subscriptions free of charge Customers who have already purchased ServletExec . AIX .Java News and Releases ServletExec . Two graphs are added named as a small list having items or less and a large list having from to items.u Updated OS support Windows Vista. At least. It may be a little bit hard to swallow for many enterprise developers. you would to know that how much performance you are sacrificing in order to fulfilling other requirements.. for example Bit or bitmap used for optimizing the indexes for columns in which values repeat frequently TimeSeries class used in dealing efficiently with small fixedsize objects Specialized versions of collections used in thick indices indexes having multiple duplicate values. OneToMany . the KDTree helps them in expanding coding efficiency and helps in making Java data objects easier to use in certain types of application. McObject provides support for the KDTree. and deletions Rtrees used for geospatial indexing mainly in GPS/navigation systems Ttrees used in allinmemory data storage and accessHash tables for Mar Java Jazz Up . including Btrees used in common sorting. that is used for speedly searching in networking and telephony applications Custom indexes used in btrees allowing to the application to define the collating sequence of entries. McObjects Perst embedded database and eXtremeDB embedded database provides a collection various index types. Inheritance Lob .Useful timestamping class and for a common ID. to Perst. objectoriented allJava embedded database system.collections. The new kdimensional tree or in short KDTree index enables us to add a structure in Perst for storing and manipulating point objects in a kdimensional space by partitioning that space.Assigns UUID automatically Lazy loading on ManyToOne.object references. Rudimentary caching to reduce hits on SDB JPA Queries Perst AllJava Embedded Database Adds KDTree Indexes quickly locating a single unique index entry Patricia trie index. geographical information systems and biometric applications like fingerprint matching as well as their efficiency in handling multidimensional data. These are practically used in computer graphics. insertions. and bit indexes KDTree is developed by using the latest versions of Perst for Java and . it is also useful in implementing soundex algorithm searches. It is an open source. Developers who have been working with Perst. It is available for free download at McObjects Web site. searching.Java News and Releases ManyToOne . A KDTree is a database index that is used in spatial and patternmatching applications. KDtrees helps the developers in quotnormalquot applications where query predicates include different combinations of object fields.NET. Id . Lobs and OneToMany so only hits SDB on an as needed basis. MappedSuperClass .stores lobs in S so make it as big as you want up to GB. w.org//XSL/ Transformgt or ltxsltransform version. gt ltxsloutput methodhtml/gt .quot.quot gt ltxslstylesheet version. Most templates have the following form ltxsltemplate match/gt lthtmlgtltbodygt ltxslapplytemplates/gt lt/bodygtlt/htmlgt lt/xsltemplategt An optional transformation of the input document into another structure. XSLT stylesheets are free to use any prefix. lt/xslstylesheetgt b Stylesheet Element The ltxsltemplategt Element An XSL style sheet consists of a set of rules that are called templates.quot xmlnsxslhttp//www.. However. Thus it is a language for expressing Stylesheets. A stylesheet specifies the presentation of XML information using two basic categories of techniques ltxml version.quot gt To get access to the XSLT elements. Understanding XSL Stylesheet Structure a XSLT namespace The XSL stylesheet starts with the root element ltxslstylesheetgt or ltxsltransformgt that declares the document to be an XSL style sheet. This specification uses a prefix of xsl for referring to elements in the XSLT namespace.quot xmlnsxslhttp//www. The World Wide Web Consortium WC started to develop XSL because there was a need for an XMLbased Stylesheet Language.Introduction to XSL Introduction to XSL XSL stands for EXtensible Stylesheet Language. which are described in three WC World Wide Web Consortium Recommendations XPath XML Path Language is an expression language used by XSLT to access or refer specific parts of an XML document XSLT XSL Transformations is a language for describing how to transform one XML document represented as a tree into another..org//XSL/ Transform points to the official WC XSLT namespace. you must also include the attribute version.org//XSL/ Transformgt Since an XSL style sheet is an XML document itself. Each template matches some set of elements in the source tree and then describes the contribution that the matched element makes to the result tree. The components of the XSL language The full XSL language logically consists of three component languages.. attributes and features we must declare the XSLT namespace at the top of the document. A description of how to present the transformed information. The xmlnsxslhttp//www. Now set it up to produce HTMLcompatible output ltxslstylesheet . The correct way to declare an XSL style sheet according to the WC XSLT Recommendation is Java Jazz Up Mar . it always begins with the XML declaration ltxml version. XSLFO Extensible Stylesheet Language Formatting Objects is a language for formatting XML documents and Formatting Properties..w. If you use this namespace.w. ltxslforeach selectEmployeegt ltxslvalueof selectEmpId/gt ltxslvalueof selectEmpName/gt lt/xslforeachgt Introduction to XSLT Extensible Stylesheet Language Transformations XSLT is an XMLbased language that transforms an XML documents and generates output into a different format such as HTML. With XSLT you can add/remove elements and attributes to or from the output file. The selected section of the document is called a node and is normally selected with the match operator. and XHTML. XSLT uses XPath to find information in an XML document. which is a stylesheet definition language for XML. XSLT is an extension of XSL. all of the EmployeeDetail elements will be selected. The ltxslapplytemplatesgt Element The ltxslapplytemplatesgt element applies a template to the current element or to the current elements child nodes. the given expression will select the value of EmpId attribute of the specified element and write to the output ltxslvalueof selectEmpId/gt or ltxslvalueof selectEmployeeDetail/ Employee/EmpId/gt Note The value of the select attribute is an XPath expression. In the above statements. Mar Java Jazz Up If the selected node contains all elements in the root. where a forward slash / selects subdirectories. You can also rearrange and sort elements. If we add a select attribute to the ltxslapplytemplatesgt element it will process only the child element that matches the value of the attribute. Another approach is to match the document element the element that includes the entire document. The ltxslforeach selectelementName gt Element The foreach expression is a loop that processes the same instructions for these elements. The ltxslvalueofgt Element The ltxslvalueofgt element can be used to extract the value of an XML element and add it to the output stream of the transformation. the given expression finds all Employee elements in the EmployeeDetail element context using the XPath expression EmployeeDetail/ Employee. For example. XML or another type of document that is recognized by a browser like WML. and make decisions about which elements to hide and display. The XSL ltxslforeachgt element can be used to select every XML element of a specified nodeset. XPath is used to navigate through elements and attributes in XML documents. The match/ attribute associates the template with the root node of the XML source document. For example. We can use the select attribute to specify the order in which the child nodes are processed. the part of the XML document with the information to be copied to the output must be selected with an XPath expression.Introduction to XSL Before processing can begin. the ltxsltemplategt element defines a template. . An XPath expression works like navigating a file system. but a few good one Open sources. unpack it and add these files to your CLASSPATH. An instance of the Transformer class is then created using the instance of the TransformerFactory class. XT.org/xalan/. You can create the source XML document using SAX. We will concentrate on using this engine for transformation our XML document that we have developed and want to transform it into output document in the HTML format. These components are An instance of the TransformerFactory An instance of the Transformer The predefined transformation instruction TransformerFactory is an abstract class used to create an instance of the Transformer class that is responsible for transforming a source object to a result object.jar. This instance of the Transformer class uses the XML document as a source object and optionally uses the predefined instructions required for transformation to generate the formatted output as a result object. Oracle. the original document is not changed. Once the Xalan. During transformation process. or an input stream.zip or . Working with XSLT APIs XSLT consist of three components that transform an XML document into the required format.gzip file is downloaded. This processor is available at http// xml. Saxon. such as HTML or plain text. DOM. Apaches Xalan XSLT engine Xalan is the Apache XML Projects XSLT engine.jar file for the Xalan stylesheet engine itself.jar. The following figure shows the working process of XSLT APIs XSLT Processors The job of an XSLT processor is to apply an XSLT stylesheet to an XML source document and produce a result document. a new document is created based on the content of an existing one. and xalan.jar files are named xercesImpl. for example HTML document. The process of XML transformation starts when you create an instance of the TransformerFactory class. such as MSXML. The result object of the transformation process is in the form of a SAX event handler. and the . Most of them can be downloaded free from Web sites. or an output stream.apache.Introduction to XSL The following figure shows the working process of XSLT the Xerces parser. The new document may be serialized output by the processor in standard XML syntax or in another format. DOM. There are several XSLT processors. The .jar file for Java Jazz Up Mar . and Xalan. These files include the . rather. This method provides an input source and output result. javax.transform.transform. Create an XSL Stylesheet Lets see the source code of XSL stylesheet emp.xsl that provides templates to transform the XML document ltxml version.xml. we will convert a simple XML file into HTML using XSLT APIs.stream Defines classes . Create an XML file The code for the emp. ltEmployeegt ltEmpIdgt E lt/EmpIdgt ltEmpNamegt Nisha lt/EmpNamegt ltEmpEmailgt Nishayahoo. do the following steps .xml file is given below ltxml version . gt ltEmployeeDetailgt The XSLT Packages The XSLT APIs is defined in the following packages Package javax.w.xml.xml. These classes are used to get an object for doing transformations. its transform method is invoked.dom Defines classes used to create input and output objects from a DOM.com lt/ EmpEmailgt lt/Employeegt lt/EmployeeDetailgt . To develop this program.transform Description Defines the TransformerFactory and Transformer classes.com lt/EmpEmailgt lt/Employeegt ltEmployeegt ltEmpIdgt E lt/EmpIdgt ltEmpNamegt Deepak lt/EmpNamegt ltEmpEmailgt Deepakyahoo. After creating a transformer object.quot gt ltxslstylesheet xmlnsxslhttp// www. In this tutorial.org//XSL/Transform version. javax.transform.xml.com lt/ EmpEmailgt lt/Employeegt ltEmployeegt ltEmpIdgt E lt/EmpIdgt ltEmpNamegt Amitlt/EmpNamegt ltEmpEmailgt Amityahoo.sax Defines classes used to create input from a SAX parser and output objects from a SAX event handler.Introduction to XSL used to create input and output objects from an I/O stream.quotgt ltxsloutput methodhtml indentyes/gt Mar Java Jazz Up javax. stream. String inXML arg.inXSL.xml. String outTXT arg. public class SimpleXMLTransform static public void mainString arg ifarg. SimpleXMLTransform st new SimpleXMLTransform. System.xml.printlnUsage SimpleXMLTransform ltinput.xslgt ltoutputgt.err.err.Transformer.transform. String inXSL arg.transforminXML.String outTXT throws TransformerConfigurationException.xml.xml.printlne.transform.java of the javax. transformer. import javax.exit.String inXSL. import Java Jazz Up Mar . public void transformString inXML.err.setErrorListenernew MyErrorListener.err.transform.xml. System.newInstance. Here is the source code SimpleXMLTransform.newTransformerxslStream.TransformerFactory.printlnInvalid factory configuration.ErrorListener. System. import javax. TransformerException TransformerFactory factory TransformerFactory.err.transform.outTXT. import javax.xml. import javax.Introduction to XSL ltxsltemplate match/gt lthtmlgt lttitlegtXSLT Style Sheetlt/titlegt ltbodygt lthgtltp aligncentergtEmployee Detailslt/ pgtlt/hgt ltxslapplytemplates/gt lt/bodygt lt/htmlgt lt/xsltemplategt ltxsltemplate matchEmployeeDetailgt lttable borderquot width aligncentergt lttr bgcolorLIGHTBLUEgt lttdgtltbgtEmpIdlt/bgtlt/tdgt lttdgtltbgtEmpNamelt/bgtlt/tdgt lttdgtltbgtEmpEmaillt/bgtlt/tdgt lt/trgt ltxslforeach selectEmployeegt lttrgt lttdgtltigtltxslvalueof selectEmpId/ gtlt/igtlt/tdgt lttdgtltxslvalueof selectEmpName/ gtlt/tdgt lttdgtltxslvalueof selectEmpEmail/ gtlt/tdgt lt/trgt lt/xslforeachgt lt/tablegt lt/xsltemplategt lt/xslstylesheetgt .xml.printlnError during transformation.xmlgt ltinput.printlne.transform.StreamResult. Transformer transformer factory. catchTransformerConfigurationException e System. catchTransformerException e System. Create a Java program using XSLT APIs Now we will develop a class in Java that takes both XML and XSL file as an input and transforms them to generate a formatted HTML file. try st.TransformerException.transform.StreamSource.stream.Transformer ConfigurationException. import javax.transform. StreamSource xslStream new StreamSourceinXSL. import javax.length System. public void fatalErrorTransformerException e throws TransformerException showFatal Error.getLocationAsString.html The generated HTML file isemp.out. Compile and Run the Program Cnishaxsltgtjavac SimpleXMLTransform. ife.TransformerException e System.out. First. throwe. throwe. System. and arg is for taking the name of the html file that will be generated after the transformation.out.e. public void errorTransformerException e throws TransformerException showError.printlntype e. transformer. arg is for XSL file.xml emp.e. Its method transformin. class MyErrorListener implements ErrorListener public void warningTransformerException e throws TransformerException showWarning.transformin. private void showString type.java Cnishaxsltgtjava SimpleXMLTransform emp. .printlne. StreamResult out new StreamResultoutTXT. The new instance of the Transformer class is created using an xslStream instance of the StreamSource class.html The format of the generated output file emp. This program uses three arguments to take inputs from the command line arg is for XML file.getLocationAsString null System. this program creates an instance of the TransformerFactory class.html will look like this .printlnThe generated HTML file is outTXT.getMessage.out takes two arguments the XML document as a source object and the result document as an output object in the form of HTML. As in the earlier section.xsl emp. This instance of the Transformer class required for transformation to generate the Mar Java Jazz Up formatted output as a result object.Introduction to XSL StreamSource in new StreamSourceinXML. we have described the working process of XSLT APIs.e. throwe.out. Nonvalidating parsers are smaller and faster. This makes easier to modify the data. Parsing XML Documents To manipulate an XML document. attributes. where it can be accessed and manipulated by the user. XML parsers can be validating or nonvalidating.dom Description Defines the Document class a DOM along with the classes for all of the components of a DOM. the parser recognizes and responds to each XML structure taking some specified action based on the structure type. DOM provides access to the information stored in your XML document as a hierarchical object model. .xml. XML parser is needed. its data can be manipulated using the appropriate parser.JAXP API using DOM Parser In the previous issue of Java Jazz Up. This mechanism is also known as the random access protocol. Lets quickly focus on the overview of XML parser. or as an XML Schema. you have read about the JAXP APIs and learned how an XML document is parsed using the serially access mode SAX parser. and text defined as nodes. create and manipulate an XML document. The textual information in XML document gets turned into a bunch of tree nodes and a user can easily traverse through any part of the object tree. The DOM is most suited for interactive applications because the entire object model is present in memory. The DOM API is easier to use. The Document Object Model implementation is defined in the following packages JAXP APIs org. XML parser is used to read. The JAXP APIs provide a common interface for different vendors to use SAX and DOM parsers. tags. The parser loads the document into the computers memory. DOM is very useful when the document is small. javax. They only check whether the XML document is structurally well formed or not. In this section. so it is much more CPU and memory intensive. The DOM presents an XML document as a treestructure a node tree. The specifications to ensure the validity of XML documents are DTDs and the Schemas.wc. and breaks them up into easily manageable parts. in what order they must appear. Whenever the XML document executes.parsers The DOM API is defined in org. with the elements. Now you will learn how the DOM parser works with the same xml document.e. to remove it. These rules appear in an XML document either as an optional XML structure called a document type definition. or even to insert a new one.wc. DOM reads the entire XML structure and holds the object tree in memory. or DTD. Validating parser checks the contents of a document against a set of specific rules i. update. Once the document is loaded. DOM Document Object Model The XML Document Object Model XML DOM Java Jazz Up Mar defines a standard way to access and manipulate XML documents using any programming language and a parser for that language. It provides a tree structure of objects. or some other defined sequence of tokens. but they do not check documents against the DTD. any time. we will discuss about DOM parsers of JAXP APIs and for accessing XML documents in random access mode. The DOM API is used to manipulate the hierarchy of application objects it encapsulates. The DOM converts an XML document into a collection of objects in an object model in a tree structure which can be manipulated in any way.dom package of JAXPAPIs. a parser is a program that takes input in the form of sequential instructions. Introduction to XML Parser In computing terms. Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents an empty Document. The System property determines the builder at the run time using javax. you can add the element to it.wc. The newDocument method of the class returns a blank DOM document. First element of the document is called the root element. Creating DOM Child Elements Once new document has been created. As a result.Document interface that creates Mar Java Jazz Up .newDocument.xml. Through which it produces a Document a DOM that conforms to the DOM specification.newDocument. Creating the root element As you have seen above that how to create a blank DOM document using DocumentBuilder object.newInstance. The following steps generate a DOM document having root and child elements. The class DocumentBuilderFactory is responsible for creating new DOM parsers. another elements added to the document are called child elements of the root. //Create blank DOM Document Document doc parser.parsers. system property can be overridden from the command line.xml. one of the builders parse methods can be used to create a Document from existing XML data.parsers. javax. Alternatively. The instance of the class DocumentBuilder is used to create a blank document. Creating Blank DOM Document The following code creates a blank document //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory DocumentBuilderFactory. The createElement method is used to create the root element and appendChild method is DocumentBuilderFactory The diagram here shows the JAXP APIs to process xml document using the DOM parser Understanding DOM Parser At the very first. The following code creates a blank document.DocumentBuilderFactory it selects the factory implementations to produce the builder. Another method of DocumentBuilder as newDocument can also be used implementing org.JAXP API using DOM Parser Main classes of javax. //Get the DocumentBuilder DocumentBuilder parser factory.parsers package for the DOM Classes DocumentBuilder Description Defines the API to obtain DOM Document instances from an XML document.dom. //Create blank DOM Document Document doc docBuilder. The platforms default value i. a DOM tree like that shown in the diagram.e.newDocumentBuilder.Document BuilderFactory class creates the instance of DocumentBuilder.xml. createComment method is used to reate Comment object. TransformerFactory tranFactory TransformerFactory. //add in the root element root.xml. import javax..stream.createElementroot.appendChildroot.newDocumentBuilder. Result dest new StreamResultSystem.newDocument. class CreateDomXml public static void mainString args try //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory DocumentBuilderFactory.xml.wc.dom. Result dest new StreamResultSystem.appendChildchildElement. //all it to the xml tree doc.createElementChild.transform.JAXP API using DOM Parser used to append the element to the DOM document. //Add the atribute to the child childElement.transformsrc.appendChildcomment.appendChildroot.transform. Adding Comment Element to DOM Tree The doc.DocumentBuilderFactory.DOMSource.createElement method is used to create Child element.transform. import Java Jazz Up Mar . //add it to the xml tree doc.The value of Attribute quot.createCommentThis is comment.newInstance. import org.xml. //add in the root element root.createCommentThis is comment. Here is the full CreateDomXml. //create a comment Comment comment doc. //create child element Element childElement doc. dest. //Add the atribute to the child childElement.appendChildchildElement. //create child element Element childElement doc.StreamResult.The value of Attribute quot. Adding Child Element to DOM Tree The doc.createElementroot. //Create blank DOM Document Document doc docBuilder..out.xml. //create the root element Element root doc. Source src new DOMSourcedoc. //create the root element Element root doc.parsers.dom. Transformer aTransformer tranFactory. import javax.appendChildcomment.setAttributeattribute. aTransformer. root.newTransformer.newInstance.createElementChild.newInstance.parsers. import javax. Transformer aTransformer tranFactory.java source code of javax. Printing the DOM Tree on console An finally we will print the DOM tree on the console with the following code TransformerFactory tranFactory TransformerFactory.out.DocumentBuilder.xml.setAttributeattribute. //Get the DocumentBuilder DocumentBuilder docBuilder factory. //create a comment Comment comment doc. root. Source src new DOMSourcedoc.newTransformer. import javax. To parse the xml file you need the DoucnemtBuilderFactory and DocumentBuilder.printlne. DocumentBuilder builder factory. Initially the program checks that the given file exists or not by using exists method.com lt/ EmpEmailgt lt/Employeegt lt/EmployeeDetailgt Mar Java Jazz Up .printlnelement. gt ltEmployeeDetailgt ltEmployeegt ltEmpIdgt E lt/EmpIdgt ltEmpNamegt Vinod lt/EmpNamegt ltEmpEmailgt Vinodyahoo. //Source src new DOMSourceelement. Now.com lt/EmpEmailgt lt/Employeegt ltEmployeegt ltEmpIdgt E lt/EmpIdgt ltEmpNamegt Deepak lt/EmpNamegt ltEmpEmailgt Deepakyahoo.out. ltxml version. The object of the DocumentBuilder uses parse method and determines that the parsed xml is well formed or not.parsexmlFile. Develop a java file GetDomData.newInstance.java that uses an xml file to parse.xml to be parsed ltxml version . Here is a sample code of this program File file new FilexmlFile.getMessage. System.xml isnt wellformed. EmpName and EmpEmail in our case.getLength.getNodeName.transformsrc.quot encodingUTFquot standalonenogt ltrootgt ltThis is commentgt ltChild attributeThe value of Attribute quot/ gt lt/rootgt Download the Program Lets see another example that helps you to retrieve the elements as well as their corresponding data from the DOM tree.getElementsByTagName.out.itemi. lets see the sample code to retrieve the data from the elements The given code will generate the following xml code and display on the console. The doc object helps in create a NodeList through the getElementByTagName method. Here is the XML File emp. For getting the node name you use the getNodeName method. If xml document is willformed. catchException e System.printlnxmlFile is wellformed . In this example you need a wellformed XML file that has some data EmpId.exists DocumentBuilderFactory factory DocumentBuilderFactory. lets see the sample code to retrieve the elements from the xml file NodeList list doc. It determines that the parsed xml is well formed or not.com lt/ EmpEmailgt lt/Employeegt ltEmployeegt ltEmpIdgt E lt/EmpIdgt ltEmpNamegt Amit lt/EmpNamegt ltEmpEmailgt Amityahoo. Document doc builder. The NodeList helps you in getting the length and Element. i // Get element Element element Elementlist. Now. it will display a message emp. if file. for int i. iltlist.out.JAXP API using DOM Parser aTransformer.newDocumentBuilder. System.xml is wellformed Otherwise prints emp. dest. If you enter a file that doesnt exist it will show File not found. import javax.out.exists DocumentBuilderFactory factory DocumentBuilderFactory.xml.out.xml emp. // Write the document to a file Source source new DOMSourcedoc.transform.itemi. System.printlne.sax.dom. import javax.readLine.java Cnishagtjava GetDomData Enter XML file name emp. public class GetDomData static public void mainString arg try BufferedReader bf new BufferedReadernew InputStreamReaderSystem. import org. for int i.stream. // Output text type tFormer.out to display the data on the console. import javax. This program uses the System.printEnter XML file name .newDocumentBuilder.dom.setOutputPropertyOutputKeys.. System.transform. System. //Write the document to a file Source source new DOMSourcedoc. The setOutputProperty method of the Transformer class set the output key as a text to print the data on console.parsers. result. Here is full source code of GetDomData.newInstance. else System. String xmlFile bf.. tFormer.newInstance.out. catch Exception e System. // Create transformer Transformer tFormer TransformerFactory.METHOD. if file. text. Result result new StreamResultSystem.xml.printlnelement.xml. i // Get element Element element Elementlist.out.xml. // Output text type tFormer. Result result new StreamResultSystem.getLength.METHOD.err.in.newInstance. System. Output of the Program Cnishagtjavac GetDomData. text.transformsource. File file new FilexmlFile..wc.JAXP API using DOM Parser //Create transformer Transformer tFormer TransformerFactory.parsexmlFile.printlnFile not found.exit.xml.setOutputPropertyOutputKeys. result.xml is wellformed EmployeeDetail Employee EmpId EmpName EmpEmail Employee EmpId EmpName .out. DocumentBuilder builder factory.out. import javax. import org. tFormer.transformsource.newTransformer.printlnxmlFile is wellformed .getElementsByTagName. Then the transform method displays the data source and the given destination. iltlist..transform.DOMSource.newTransformer.StreamResult. //Source src new DOMSourceelement.getNodeName.io. Document doc builder. Java Jazz Up Mar NodeList list doc..java import java. com E Deepak deepakyahoo.com Cnishagt Mar Java Jazz Up .com E Amit amityahoo.JAXP API using DOM Parser EmpEmail Employee EmpId EmpName EmpEmail E Nisha nishayahoo. Changes made to one component have less or no impact on other component.org/.Struts . You can down the latest version of struts from http//jakarta. We are using this file to create our Java Jazz Up Mar .apache. ModelViewController MVC Architecture ModelViewController architecture separates the application components into three different parts named Model. Extract file into the desired directory and then copy strutsblank. This tutorial provides you a better understanding to develop a robust application using Jakarta Struts Framework. Action. Follow the instruction given in the installation process to install JDK on your machine. Controller Controller part controls the flow of the entire application. JSPs. or above from sun site. HTML. For this application we have downloaded jakartatomcat. Installing Struts Application Download any version of Struts from the site of Struts http//jakarta.. dispatching the request to the controller and receiving response from the controller and displaying the result to the user. We are using jakartastruts. Before going to start lets first take a brief introduction about MVC architecture.war is a blank struts application which is useful in creating struts application from scratch. Setting Up Development Environment Before going to start first of all we have to setup the development environment for the application. go to your installation directory/bin and issue startup command to run the server. Struts is an open source framework and maintained as a part of Apache Jakarta project..webapps directtory into jakartatomcat. Custom Tag Libraries and Resources files are used as part of view component. Each component of the MVC architecture is independent with the other and also has unique responsibility..war. View and the Controller. for this application. Tomcat Installation Download the binary version of Tomcat from the apache site and follow the instruction to install the tomcat on your machine. Here is description about the responsibilities of the components of MVC architecture Model This part of the MVC architecture provides access to the data from the database and also saves the data into the database. Model includes the business logic of the application. Struts Framework suits to develop any size of application. Before starting we are considering that you have an idea about developing a web application by using JSP. If it is successfully installed it should display the welcome page. strutsblank.xml as its parts. Controller also receives the request from client process that request by executing the appropriate business logic of the Model and then sends the response to the user using the View component. Servlets. Struts Struts Frame is nothing but the implementation of ModelViewController MVC design pattern. Data access.. and jakartatomcat. To test the installation.war from jakartastruts.apache. Data validation and the data saving logic are also part of Model.war and strutsexample. So lets from the Jakarta Struts Framework. struts documentation. Model part also checks the Data send by the user through View before saving it into the database. JDBC and custom tags. JDK Installation Download JDK . If not consult tomcat documentation before going further.org/struts. Open the browser and type http/ /localhost/ . After successfully completion of the installation process test your installation.webapps directory. View View part of the MVC architecture handle the view part of the application by taking the input from the user. It interacts with Model and View and the works as Intermediary between these two components of the MVC architecture. Controller part includes ActionServlet. ActionForm and strutsconfig. findForwardedit.http. jsp files MappingDispatchAction.out.http. if everything is ok then the welcome page that is index.webapps and copy it to the jakartatomcat. public ActionForward editActionMapping mapping. HttpServletResponse response throws Exception System.save.add. map. public ActionForward addActionMapping mapping.war includes important documents and API for the struts application development. return map.printlnYou are in edit function..printlnYou are in search function. import org.jar files into the lib directory and then compile the whole application. import org.java package roseindia. public ActionForward saveActionMapping mapping. start the tomcat server.out.jar and struts. strutsconfig. import javax. ActionForm form. HttpServletResponse response throws Exception System. Here are the different files used in our application.ActionForm. web.action.edit.servlet.war is simple MailReader Demonstration Application. import javax.struts. index.Struts .ServletException. map.webapps directory.. HttpServletRequest request.ActionForward.HttpServletRequest..struts. and finally copy the servletapi. import javax.servlet.putroseindia.action. Copy the source files LookupDispatchAction.xml.net.util.add. Developing First Struts Application Rename strutsblank. HttpServletResponse response throws Exception System.edit. return mapping.search.search.net..servlet. HttpServletRequest request. map.. HttpServletRequest request.findForwardsearch. strutsbean. HttpServletResponse response throws Exception System. own web application.action.jsp file in the StrutsApplication directory parallel to the pages and WEBINF directory.struts. import org.printlnYou are in add function. LookupDispatchAction.io.struts.LookupDispatchAction.jsp into the pages directory.apache. ActionForm form.save.putroseindia.putroseindia.jsp in case of our application will be displayed. strutsexample.jsp and MappingDispatchActionSave.net.findForwardadd.apache.java and MappingDispatchAction.war from jakartatomcat.putroseindia. import java. import org. ActionForm form. and strutshtml. map.net.war to StrutsApplication. ActionForm form.java into the source directory src directory.out. strutsdocumentation. return mapping.apache.tld parallel to the lib and the classes directory in the WEBINF directory.tld. public ActionForward searchActionMapping mapping. Tomcat automatically extracts the file and loads the application.. open the browser and enter the url http/ /localhost/StrutsApplication/ and then press enter.ActionMapping.apache.out.net. HttpServletRequest request. import java.printlnYou are in save function. return Mar Java Jazz Up .actions.HttpServletResponse.xml. public class LookupDispatchAction extends LookupDispatchAction protected Map getKeyMethodMap Map map new HashMap. return mapping. ActionForm form.printlnYou are in edit function.tld prefixhtmlgt lthtmlhtml localetruegt ltHEADgt ltBODYgt ltpgtlthtmllink page/ MappingDispatchAction.MappingDispatchAction.out.tld prefixbeangt lt taglib uri/WEBINF/strutshtml.http.out.findForwardadd. import org.doparametersearchgtCall Search Sectionlt/htmllinkgtlt/pgt ltpgtlthtmllink page/ MappingDispatchAction.action. import java.apache.http. HttpServletRequest request. public ActionForward searchActionMapping mapping. return mapping.struts. ActionForm form. HttpServletResponse response throws Exception System.struts. import javax.util.printlnYou are in save function. import org.jsp lthtmlgt ltheadgt lttitlegtSuccess Messagelt/titlegt lt/headgt ltbodygt ltp aligncentergtltfont sizequot colorquotgtWelcome to save Pagelt/ fontgtlt/pgt lt/bodygt lt/htmlgt index. import org. MappingDispatchAction.jsp lt taglib uri/tags/strutshtml prefixhtml gt lthtmlhtml localetruegt ltheadgt .findForwardsearch.HttpServletResponse.out. HttpServletRequest request.action.jsp lt taglib uri/WEBINF/strutsbean.apache. MappingDispatchAction. public ActionForward saveActionMapping Java Jazz Up Mar mapping.ActionForm.servlet.doparametereditgtCall Edit Sectionlt/htmllinkgtlt/pgt ltpgtlthtmllink page/ MappingDispatchAction.ActionMapping. HttpServletRequest request.doparametersavegtCall Save Sectionlt/htmllinkgtlt/pgt lt/htmlhtmlgt MappingDispatchActionSave.action..apache. HttpServletResponse response throws Exception System. mapping. ActionForm form. ActionForm form. HttpServletResponse response throws Exception System.findForwardsave.. HttpServletRequest request.printlnYou are in add function. import java. return mapping. import org. return mapping.doparameteraddgtCall Add Sectionlt/htmllinkgtlt/pgt ltpgtlthtmllink page/ MappingDispatchAction.struts.ActionForward. public ActionForward editActionMapping mapping. return mapping.ServletException. import javax.findForwardsave.apache.servlet.io. public class MappingDispatchAction extends MappingDispatchAction public ActionForward addActionMapping mapping.. HttpServletResponse response throws Exception System.java package roseindia.struts.net.Struts .out..HttpServletRequest.servlet.actions.printlnYou are in search function. import javax.findForwardedit. / /EN http//java.net. lthtmlbase/gt lt/headgt ltbodygt ltp aligncentergtltfont sizequot colorquotgtWelcome to the Simple Struts Applicationlt/fontgtlt/pgt ltdiv aligncentergt ltcentergt lttable borderquot cellspacingquot widthquotgt ltligt lthtmllink page/pages/ MappingDispatchAction.jsp scoperequest validatefalsegt ltforward nameadd path/pages/ LookupDispatchActionAdd.net.jsp /gt ltforward nameedit path/pages/ LookupDispatchActionEdit.net.xml ltxml version.jsp scoperequest validatefalsegt ltforward namesave path/pages/ MappingDispatchActionSave.//ENhttp// jakarta.org/struts/dtds/strutsconfig.net.jsp/gt ltforward namesave path/pages/ LookupDispatchActionSave.net.MappingDispatchAction parametersave input/pages/ MappingDispatchAction.jspgtDemo of a Simple Struts Applicationlt/htmllinkgt lt/ligt lt/tablegt lt/centergt lt/divgt lt/bodygt lt/htmlhtmlgt strutsconfig.LookupDispatchAction parameterparameter input/pages/LookupDispatchAction.quot encodingISOquotgt ltDOCTYPE webapp PUBLIC //Sun Microsystems.jsp /gt lt/actiongt ltaction path/MappingDispatchAction typeroseindia.jsp /gt lt/actiongt ltaction path/MappingDispatchAction typeroseindia.dtdgt ltstrutsconfiggt ltactionmappingsgt ltaction path/LookupDispatchAction typeroseindia.jsp /gt ltforward namesearch path/pages/ LookupDispatchActionSearch.xml ltxml version.quot encodingISOquot gt ltDOCTYPE strutsconfig PUBLIC //Apache Software Foundation//DTD Struts Configuration .MappingDispatchAction parameteredit input/pages/ MappingDispatchAction.dtdgt ltwebappgt Mar Java Jazz Up .jsp /gt lt/actiongt lt/actionmappingsgt lt/strutsconfiggt web.apache.com/jee/dtds/webapp.jsp /gt lt/actiongt ltaction path/MappingDispatchAction typeroseindia.MappingDispatchAction parameteradd input/pages/MappingDispatchAction.sun.jsp scoperequest validatefalsegt ltforward nameadd path/pages/ MappingDispatchActionAdd.//DTD Web Application .jsp scoperequest validatefalsegt ltforward nameedit path/pages/ MappingDispatchActionEdit.MappingDispatchAction parametersearch input/pages/ MappingDispatchAction.jsp scoperequest validatefalsegt ltforward namesearch path/ pages/MappingDispatchActionSearch.jsp/gt lt/actiongt ltaction path/MappingDispatchAction typeroseindia.Struts . Inc. xmllt/paramvaluegt lt/initparamgt ltinitparamgt ltparamnamegtdebuglt/paramnamegt ltparamvaluegtlt/paramvaluegt lt/initparamgt ltinitparamgt ltparamnamegtdetaillt/paramnamegt ltparamvaluegtlt/paramvaluegt lt/initparamgt ltloadonstartupgtlt/loadonstartupgt lt/servletgt lt Standard Action Servlet Mapping gt ltservletmappinggt ltservletnamegtactionlt/servletnamegt lturlpatterngt.tldlt/tagliblocationgt lt/taglibgt lt/webappgt Java Jazz Up Mar .ActionServletlt/ servletclassgt ltinitparamgt ltparamnamegtconfiglt/paramnamegt ltparamvaluegt/WEBINF/strutsconfig. ltdisplaynamegtStruts Blank Applicationlt/ displaynamegt lt Standard Action Servlet Configuration with debugging gt ltservletgt ltservletnamegtactionlt/servletnamegt ltservletclassgtorg.apache.dolt/urlpatterngt lt/servletmappinggt lt The Usual Welcome File List gt ltwelcomefilelistgt ltwelcomefilegtindex.struts.action.jsplt/welcomefilegt lt/welcomefilelistgt lt Struts Tag Library Descriptors gt lttaglibgt lttagliburigt/tags/strutshtmllt/tagliburigt lttagliblocationgt/WEBINF/strutshtml.Struts . In this section. Just download the zip file strutsnonformuitags.CheckValidUsergt ltresult nameinputgt/pages/ nonformTags/login.jsplt/resultgt ltresult nameerrorgt/pages/ nonformTags/error. Start tomcat and write http// localhost/strutsnonformuitags to the address bar. else addActionErrorInvalid User. Add the following code snippet into the struts. unzip it and copy this application to the webapps directory of Tomcat.xml ltaction nameactionerrorTaggt ltresultgt/pages/nonformTags/login.jsplt/resultgt ltresultgt/pages/nonformTags/ validuser. addActionMessageValid User. return ERROR. CheckValidUser.xml file.equalsjavajazzup ampamp getPassword. Mar Java Jazz Up . public String execute throws Exception if getUsername.xwork. Action Error and Action Message Tags Example The actionerror tag is a UI tag that renders action errors in the jsp pages. private String password null. return SUCCESS. struts. import java.opensymphony.zip from any link given below of each page of this article. import com.equalsjavajazzup .javajazzup. if they exist while the actionmessage tag renders action messages if they exist. struts nonform tags UItags will be discussed. You can examine the result of each tag from the index page.java package net.Struts Nonform Tags UItags Apache Struts is an opensource framework used to develop Java web applications.javajazzup.jsplt/ resultgt lt/actiongt ltaction namelogin classnet. public class CheckValidUser extends ActionSupport private String username null.. The addActionMessageString will print the passed string on the success jsp page while the addActionErrorString will print the passed string on the error jsp page.ActionSupport.util.jsplt/resultgt lt/actiongt Create an action class that uses methods addActionMessageString and addActionErrorString within the execute method. jsp lt taglib prefixs uri/strutstags gt lthtmlgt ltheadgt lttitlegtActionerror Tag Examplelt/titlegt ltbodygt ltsform actionlogin methodPOSTgt ltstextfield labelUser Name nameusername sizequot maxlengthquot /gt ltspassword labelPassword namepassword sizequot maxlengthquot /gt ltssubmit valueSubmit /gt lt/sformgt lt/bodygt lt/htmlgt Create a jsp page that will display your error message when fails to loggedin using the empty ltsactionerror /gt tag as shown error. //set and get the password public void setPasswordString pass password pass.jsp lt taglib prefixs uri/strutstags gt lthtmlgt Enter the wrong user name or password in the login page.jsp as shown below.actiongtGo Backlt/ agt lt/bodygt lt/htmlgt Create a jsp page that will display a message when successfully loggedin using the empty ltsactionmessage /gt tag as shown validuser. public String getUsername return username. Java Jazz Up Mar ltheadgt lttitlegtlt/titlegt ltbodygt lthgt ltsactionerror /gt lt/hgt lta href/strutsnonformuitags/ javajazzup/actionerrorTag. Create a login jsp page as shown login. Put correct user name and password. public String getPassword return password.jsp lt taglib prefixs uri/strutstags gt lthtmlgt ltheadgt lttitlegtActionerror Tag Examplelt/titlegt ltbodygt lthgt ltsactionmessage /gt lt/hgt lt/bodygt lt/htmlgt You will see the output of the login.Struts Nonform Tags UItags Struts Nonform Tags UItags //Set and get the user name public void setUsernameString name username name. You will get output . left. Div Ajax Tag tag Example The div tag is an Ajax component that is used with Ajax that refreshes the content of a particular section without refreshing the entire page.Struts Nonform Tags UItags lt/headgt ltbodygt ltsurl idtest value/pages/ nonformTags/mask. strurts. height.gt lthgtEnter first and last namelt/hgt ltsform themeajax actiondoMaskgt ltstextfield namefirstname labelFirstname /gt ltstextfield namelastname labelLastname /gt ltssubmit valueSubmit themeajax targetsmaskValue /gt lt/sformgt lt/divgt ltbrgt ltdiv idquot stylepositionabsolute. Html ltdiv / gt tag created by Ajax div tag includes its content and is used to obtain its content through a remote XMLHttpRequest call through the dojo framework. div.jsplt/resultgt lt/actiongt Create a jsp using the tag ltsdivgt.xml ltaction namedivgt ltresultgt/pages/div.jsp lt taglib prefixs uri/strutstags gt lthtmlgt ltheadgt lttitlegtEnter first and last namelt/titlegt ltshead themeajax debugfalse/gt Mar Java Jazz Up .top. Add the following code snippet into the struts.xml file.backgroundcolorEEE. width. The div tag when used with Ajax refreshes the content of a particular section without refreshing the entire page.top. left.jsp lt taglib prefixs uri/strutstags gt lthtmlgt ltheadgt lttitlegtEnter first and last namelt/titlegt ltshead themeajax debugfalse/gt lt/headgt ltbodygt ltsdiv idmaskValue gt ltdiv stylepositionabsolute.jsp /gt ltsdiv idone themeajax hreftestgt lt/sdivgt lt/bodygt lt/htmlgt mask. height. width.backgroundcolorEEE.gt lthgtOutput lt/hgt Firstname ltsproperty valuefirstname /gt ltbrgtltbrgt Lastname ltsproperty valuelastname /gt lt/divgt You will get the following output . CheckFieldgt ltresult nameinputgt/pages/ nonformTags/loginFielderrorTag.xml ltaction namefieldErrorgt ltresultgt/ pages/nonformTags/loginFielderrorTag. Add the following code snippet into the struts. . CheckField.xml file.equalsjavajazzup addFieldErrorusername.jsplt/ resultgt lt/actiongt ltaction namecheckUser classnet. public String getUsername return username.jsplt/resultgt ltresult nameerrorgt/pages/nonformTags/ Java Jazz Up Mar ifgetPassword.equalsjavajazzup addFieldErrorpassword. import com.xwork. This method adds an error message for a given field to the corresponding jsp page.equalsjavajazzup ampamp getPassword.java package net.username username.javajazzup. return SUCCESS. //Set and get the user name public void setUsernameString username this. public String execute throws Exception if getUsername. String errorMessage method.javajazzup.opensymphony. struts.Invalid password. //set and get the password public void setPasswordString pass password pass. ifgetUsername.jsplt/resultgt ltresultgt/pages/nonformTags/ validuser. private String password null.Struts Nonform Tags UItags lt/sdivgt lt/bodygt lt/htmlgt Output fielderrorTag. public class CheckField extends ActionSupport private String username null.jsplt/resultgt lt/actiongt Develop an action class using addFieldErrorString fieldName.Invalid username. Fielderror Tag NonForm UI Tags Example The fielderror tag is a UI tag that renders field errors if they exist.equalsjavajazzup addActionMessageValid User. return ERROR. public String getPassword .ActionSupport. actiongtGo Backlt/agt lt/bodygt lt/htmlgt Create a jsp page that will display your messages when succeed to loggedin using the empty ltsactionmessage /gt tag as shown validuser. You will get the following output Enter the wrong user name and correct password in the login page. You will see the output of the loginFielderrorTag.jsp as shown Enter correct values in both fields of the login page. where each tab is either a local content or a remote content refreshed each time when user selects that Mar Java Jazz Up .jsp lt taglib prefixs uri/strutstags gt lthtmlgt ltheadgt lttitlegtFielderror Tag Examplelt/titlegt ltbodygt lthgtltsfielderror /gtlt/hgt lta href/strutsnonformuitags/ javajazzup/fieldError. You will get the following output Enter incorrect values in both fields of the login page. TabbedPanel Ajax Tag Example This is an Ajax component.jsp lt taglib prefixs uri/strutstags gt lthtmlgt ltheadgt lttitlegtActionerror Tag Examplelt/titlegt ltbodygt lthgt ltsactionmessage /gt lt/hgt lt/bodygt lt/htmlgt Enter the correct user name and wrong password in the login page. below Create a login jsp page as shown loginFielderrorTag.jsp lt taglib prefixs uri/strutstags gt Create a jsp page that will display your field error messages when fails to loggedin using the empty ltsfielderror/gt tag as shown fielderrorTag.Struts Nonform Tags UItags return password. You will get the following output . xml file. treenode This is a tree node which renders a tree node within a tree widget with AJAX support. The id attribute is required if the selectedNotifyTopic or the href attribute is going to be used.ltbrgt Tabbed Panel Exampleltbrgt JavaJazzUp lt/sdivgt ltsdiv idtwo labelTab quot themeajaxgt Second Panel. you get the output as . Add the following code snippet into the struts. The following of the two combinations are used depending on the requirement like the tree is needed to be constructed dynamically Java Jazz Up Mar . tree This is a tree widget with AJAX support. tree and treenode Ajax Tag tags Example In this section. Normally this tag uses the id attribute.Struts Nonform Tags UItags tab. This tag is used for creating the tabs. struts.xml ltaction nametabbedPanelgt ltresultgt/pages/nonformTags/ tabbedpanel.ltbrgt JavaJazzUp lt/sdivgt ltsdiv idthree labelTab quot themeajaxgt Third Panel. the head tag must be included on the jsp page and must be configured for performance or debugging purposes. If you want to use the cookie feature then you must provide a unique id for the tabbedpanel component. This is used for identifying the name of component that is stored by the cookie. you will learn about the tree and treenode tags.ltbrgt JavaJazzUp lt/sdivgt lt/stabbedPanelgt lt/tdgt lt/trgt lt/tablegt lt/bodygt lt/htmlgt Output When you run the above example. These both work with the Ajax support.jsplt/resultgt lt/actiongt Create a jsp using the tag ltstabbedPanelgt. To use tabbedPanel tag. tabbedpanel. However.jsp lt taglib prefixs uri/strutstags gt lthtmlgt ltheadgt ltshead themeajax debugtrue/gt lt/headgt ltbodygt lttable borderquot widthgt lttrgt lttd widthgt ltstabbedPanel idtest gt ltsdiv idone labelTab quot themeajax labelpositiontop gt First Panel. struts.jsp lt taglib prefixs uri/strutstags gt lthtmlgt ltheadgt ltshead themeajax debugtrue/gt lt/headgt Mar Java Jazz Up . nodeIdProperty . Add the following code snippet to the struts. treenode. you get id .jsplt/resultgt lt/actiongt Create a jsp using the tag ltstreegt. nodeTitleProperty . title .This is the current tree nodes title.This is the current tree nodes children.. ltstreenode themeajax idsubchildquot labelsubchildquot /gt tag attaches a new node to the created tree with a tree node having idsubchildquot and a labelsubchildquot. childCollectionProperty .This is the current tree nodes id. This tag is used for rendering a tree widget.This is the parent node where the tree is derived form.This is an id of tree node.This is as like a label to be displayed for the tree node Statically rootNode .Struts Nonform Tags UItags or statically. Dynamically ltbodygt ltstree themeajax idroot labelRootgt ltstreenode themeajax idchildquot labelltbgtChild lt/bgt /gt ltstreenode themeajax idsubchildquot labelSubChild quotgt ltstreenode themeajax idsubchildquot labelSubChild quot /gt ltstreenode themeajax idsubchildquot labelSubChild quot /gt lt/streenodegt ltstreenode themeajax idchildquot labelltbgtchild lt/bgt /gt lt/streegt lt/bodygt lt/htmlgt Output When you run the above example.xml file.xml ltaction nameTreeNodegt ltresultgt/pages/nonformTags/ treenode. Similarly the tag ltstreenodegt renders a tree node with a label attached to the created tree widget eg. reusing the common behavior to simplify code. from many generalized to specialized operations.out. this application may have several steps to complete its processing.. Stockdetails. abstract class CheckVariousdtls public abstract void Bankdetails. This design pattern introduces an idea of defining an algorithm in a class and leaving some of the methods to be implemented by their subclasses. public void Stockdetails System. Here we are illustrating several steps to complete Creditdetails. Credit score of the clients check taken from three different companies..printlnChecking credit details. This design pattern is used to develop similar kind of operations template... Other loan information of clients check. public abstract void Creditdetails.. public abstract void Stockdetails. public void Loandetails System. public abstract void Incomedetails.. public void checkdetails Bankdetails. public void Creditdetails System..... public LoanApplicationString name this.Design Pattern . Stock holding value of a clients check. class TestTemplateApplication public static void mainString args LoanApplication Clientdtls new LoanApplicationAmit.name name. class LoanApplication extends CheckVariousdtls private String name.. Incomedetails. Java Jazz Up Mar .printlnChecking stock values details. public void Incomedetails System.out. Future income potential of that clients check.out. Loandetails.printlnChecking bank details...out.printlnChecking family income details. public abstract void Loandetails.printlnChecking other loan details. These design patterns are used in such conditions when we need a parent class having one or more methods to be implemented by their child classes. Bank balance history of a clients check. algorithm related improvement. Template Design Pattern These types of design patterns are used as templates. public String getName return name. public void Bankdetails System. Lets take an example of loan application...out. In all of the above situations we can use a template method hold the steps of the process together without deliberating the actual implementation of the processs steps together without considering the real implementation in the subclass. b . This add method may take any primitive type numerical value and we can type cast the result according to our requirement.out. Clientdtls.printlnbyteaddanytype Number. int i .addnumberss. System.out.b. d .. short s . System.out. double d return d d. .f. The example illustrated below has an add method that is a template method. Best example of template design pattern is method overloading and method overriding.out.printlnintaddanytype Number. double d.i.out. . AddAnyTypeOfNumber addanytypeNumber new AddAnyTypeOfNumber.printlnnChecking Clientloandtls. System.out. class AddAnyTypeOfNumber extends AddNumbers public double addnumbersdouble d.Design Pattern System. System.l. s .addnumbersl. LoanApplication Clientloandtls new LoanApplicationAqueel. System.checkdetails. float f . System. Clientloandtls.out. i . abstract class AddNumbers public abstract double addnumbersdouble d.s.addnumbersd.printlnlongaddanytype Number. f . class TestApplication public static void mainString args byte b .out.printlnfloataddanytype Number.d..addnumbersb.f. long l .addnumbersi.addnumbersf.f.printlnshortaddanytype Number. double d .printlnaddanytype Number. For example.printlnnChecking Clientdtls. Mar Java Jazz Up .getName client loan details. l .checkdetails.getName client loan details. System. addnew Pepsi. interface Colddrink public String Order. Visitor Design Pattern The design pattern provides additional functionality to a class. public void visitColddrink clddrnk name clddrnk. In the following example we are taking the two interfaces one is Visitor interface and the other is Colddrink interface and then we implement to these interfaces into our classes.Order. import java.Order.Order. public String Order return name.. public String toString return name method. public void visitColddrink clddrnk name clddrnk. case return new GetByDelivery. private final String method Pick and Go.util. Lets take an example that demonstrates that how the classes implement the Visitor interface.addnew CocaCola. class Drinkthere implements Visitor private String name. colddrinkList. This is useful in those conditions if a fair number of instances are available of small number of classes and we have to perform some operations on all or on most of those classes. case return new CocaCola. class Pepsi implements Colddrink final String name Pepsi. Java Jazz Up Mar . The Visitor pattern allows us to create an external class to act on data in other classes. public String toString return name method. Iterator it colddrinkList. private final String method Get it by delivery. class CocaCola implements Colddrink final String name Coke. default return null. case return new Drinkthere.Visitor Design Pattern . class Pickup implements Visitor private String name. class GetByDelivery implements Visitor private String name. public String Order return name. public void visitColddrink clddrnk name clddrnk. colddrinkList. public Visitor howto switch intMath. public String toString return name method. interface Visitor public void visitColddrink clddrnk. class TestVisitors public static void mainString args List colddrinkList new ArrayList.iterator. private final String method Take the drink over there. class Drink public Colddrink getDrink switch intMath.random case return new Pepsi.random case return new Pickup. default return null. Order.Visitor Design Pattern System.getDrink.printlnColddrinkit. System.howto. Colddrink clddrnk drink.printlnnnChoose the shop to take the drink. vstr.printlnHow many Cold drink Shop are there in this area. System.out.visitclddrnk. while it.out. Mar Java Jazz Up .next. Visitor vstr drink.out.hasNext System.printlnvstr. Drink drink new Drink.out. To create a button in dojo you need to a Button Widget that contains three visual states as mouseOut. lt/scriptgt dojo. mouseOver and mouseDown. // Load Dojos code relating to the Button widget dojo. If you dont include this line.requiredojo.requiredojo.widget. Dojo applications are used where the JavaScript and browsers dont work far enough. queues and stacks. Insert the following code into the HTML body ltbutton dojoTypeButton w i d g e t I d h e l l o B u t t o n onClickhelloPressed.Button. It also provides packages for string manipulation. This is responsible for instructing Dojo on how to process the element when the page is loading. portable.Dojo will work with either as long as the dojoType attribute is present. Create a Button The following example we are going to create a button Hello World.requiredojo. lightweight and tested tools for creating a dynamic interfaces.Dojos widget system is smart Hello world Example Here.gtHello Worldlt/ buttongt The key attribute of this HTML element to notice is the dojoType attribute.Button This line instructs you to load the Dojo button widget. resulting in a plain HTML button instead of what you expect.requiredojo. Java Jazz Up Mar . in which place the dojo application gives you the powerful. The main functionality of Dojo is to make HTTP requests and receive their responses. In this case you will use a button element for the button that is used to input element . Before creating any examples or applications you must follow the directory structure. you will learn to create a Hello World example in Dojo. dojo. the markup code for the button would not be evaluated by Dojo upon loading.widget. Dojo Directory Structure Whenever you use Dojo then you follow the following directory structure and set up the files of the specified location. draganddrop support and DS Data Structures such as lists.widget. widgetIdhelloButton This is replaced with idhelloButton without the functionality being affected . To follow the following steps for creating a dojo button widget ltscript typetext/javascriptgt // Load Dojos code relating to widget managing functions dojo. It instructs you to include the dojo widget Not load all the widgets for managing functions.widget.Dojo Tutorial Dojo Tutorial Dojo Dojo is an Open Source JavaScript toolkit libraries that provides a simple APIApplication Programming Interface for building the serious applications in less time.. DOM manipulation. widget.event. without clicking a mouse it appears a small box with supplementary information regarding the items.requiredojo. If the mouse cursor over an item.Button. Here is the code of program lthtmlgt ltheadgt lttitlegtTooltip Demolt/titlegt ltstyle typetext/cssgt import . lt/scriptgt lt/headgt ltbody bgcolorFFFFCCgt ltp aligncentergtltfont sizequot colorquotgtWelcome to Roseindia Dojo Projectlt/fontgtlt/pgt ltbutton dojoTypeButton widgetIdhelloButton onClickhelloPressed.requiredojo.widget.event.addOnLoadinit.Dojo Tutorial enough to convert regular id attributes to widgetIds if no widgetId attribute is explicitly named. dojo. onClick. dojo.. dojo. function helloPressed alertClick on the Hello World Button. Here is the code of program lthtmlgt ltheadgt lttitlegtbuttonlt/titlegt ltscript typetext/javascriptgt dojo.css../resources/dojo.byIdhelloButton.event.requiredojo.requiredojo. that includes all events functionality of Dojo But not all widgets.gtHello Worldlt/ buttongt ltbrgt lt/bodygt lt/htmlgt Output of program Tool tips Example Tool tips This is a GUI Graphical User Interface element that is used in conjunction with a cursor and usually a mouser pointer. dojo. helloPressed dojo..event.. function helloPressed alertClick on the Hello World Button. function init var helloButton dojo. Mar Java Jazz Up . Connecting an Event to the Widget When you click the command button then it doing something We specify an onClick event handler for the given command button. Above code we use dojo. Following function that will called by the button when we clicked.widget.connecthelloButton. After clicking the helloPressed method is called and it displays an alert message like Click on the Hello World Button. requiredijit.Tooltip connectIdsitequot labelThis is a news publishing sitegt lt/divgt lt/bodygt lt/htmlgt Output of the program Whenever your mouse pointer goes on the Roseindia.parser.requiredojo. If you want to change the value then click the date text and select the appears date. The inner textarea tag is the Textarea widget. When a user run this code then they see the paragraph of rich text. lt/scriptgt lt/headgt ltbody classtundragt ltbgtTooltipslt/bgt ltbrgtltbrgt ltspan idsitequotgtRoseindia.comlt/ spangt ltdiv dojoTypedijit.com then you get ltscript typetext/javascriptgt dojo. The InlineEditBox has methods get/ setDisplayedValue.js djConfigparseOnLoad truegtlt/scriptgt Whenever your mouse pointer goes on the Newstrackindia. Here is the code of program lthtmlgt ltheadgt lttitlegtInlineEdit Date Demolt/titlegt ltstyle typetext/cssgt import ./resources/dojo.css.form.parser.Tooltip. dojo.requiredijit. If user clicks the text.. lt/stylegt ltscript typetext/javascript srcdojo.netlt/spangt ltdiv dojoTypedijit.you will learn about the dojo inline DateTextBox and how to create a inline DateTextBox and how to make its editable.DateTextBox save it automatically.xd.form.js djConfigparseOnLoad truegtlt/scriptgt ltscript typetext/javascriptgt dojo.requiredojo.Tooltip connectIdsitequot labelThis is a software developement companygt lt/divgtltbrgtltbrgtltbrgt ltspan idsitequotgtNewstrackindia.requiredijit. The following code shows the DateTextBox that makes inline in HTML. the plain text appears in paragraph. import .DateTextBox. inline. dojo../dijit/themes/tundra/ tundra. The following code is the InlineEditBox that edits date of dijit./dijit/themes/tundra/ tundra. lt/scriptgt Java Jazz Up Mar ..form.xd.net then you get Inline DateTextBox Here.InlineEditBox. dojo.css.css.Dojo Tutorial import . lt/stylegt ltscript typetext/javascript srcdojo. import . Add./resources/dojo. There are following steps for creating Dojo trees Create a rooted or rootless trees forests Nest.requiredojo. Events fire when users clicked on it. lt/scriptgt lt/headgt ltbody classtundragt Simple Treeltbrgtltbrgt ltdiv dojoTypedojo. you will learn about the tree and how to create a tree in dojo..parser.data. It represents the hierarchical structure of tree.requiredojo.xd.data. Here is the code of Program When you click the following date then you get the following and select any date and it automatically save lthtmlgt lttitlegtTreelt/titlegt ltheadgt ltstyle typetext/cssgt import .txt jsidpopStore /gt ltdiv dojoTypedijit.. Tree The tree is a GUI that helps to lists the hierarchical lists.data API. remove or disable nodes of tree. Data is fed by the powerful dojo.InlineEditBox gt ltinput namedate valuequot dojoTypedijit. lt/stylegt ltscript typetext/javascript srcdojo.ItemFileReadStore.form.data implementing API.js djConfigparseOnLoad truegtlt/scriptgt ltscriptgt dojo. each branch is independently expandible Different icons for different leaf or branch classes Tree data are stored in any dojo.gt lt/bodygt lt/htmlgt Output of the program but the real power comes in the data.css./dijit/themes/tundra/ tundra.requiredijit.Tree. The tree widget is a simple .DateTextBox constraintsdatePatternMM/dd/ yy langenus requiredtrue promptMessagemm/dd/yy invalidMessageInvalid date.ItemFileReadStore urltree. dojo. Please use mm/dd/yy format.Dojo Tutorial lt/headgt ltbody classtundragt ltp idbackgroundArea dojoTypedijit.Tree storepopStore labelAttrsname labelTreegtlt/divgt lt/bodygt lt/htmlgt Mar Java Jazz Up Dojo Tree In this section. dojo.form.css. nameDeepak. children nameApple. type cat. typegr . nameSour. typefr . typegr . typefr . nameGraps. identifier name. type cat. nameSuman. nameMango. children nameSweets. nameFruits. children nameVinod.Output of the Program tree. typest . typegr . nameSalt. nameEducation. label name.txt In JSON format. typecat Java Jazz Up Mar . typest . items nameStudents. typecat. nameVegetables. typefr. typest . There are five core APIs that are commonly used. addOrderOrder order createAliasString associationPath. HQL is much like SQL and are caseinsensitive. Hibernate Query Language is extremely powerful and it supports Polymorphism. It is a simplified API for retrieving entities by composing Criterion objects. setFirstResultint first Set the first result Result to be retrieved. Projection . Order setFetchSizeint fetchSize Set a fetch size for the underlying JDBC query. Criterion . Restrictions . except for the names of the Java Classes and properties. These are . Associations. Criteria The interface org. assigning an alias to the joined entity This method is used to create new Criteria. This is a very convenient approach for functionality like search screens where there is a number of conditions or fields to be placed upon the result set. The interfaces of the Criteria Query API represent an aspect of the relational approach. It uses Classes and properties instead of tables and columns. It provides a welldesigned way of building dynamic queries on Hibernatepersisted databases. Introduction to Hibernate Criteria APIs Hibernate Criteria API is a powerful and elegant alternative to traditional HQL. It is mostly used in case of complex multi criteria search screens. Convenience method to return a single instance that matches the query. String alias createCriteriaString associationPath Hibernate Query Language HQL Query By Criteria QBC and Query BY Example QBE using Criteria API Native SQL queries Lets discuss about the Hibernate Criteria APIs in brief. or null if the query returns no results.Criteria is used to create the criterion for the search. setMaxResultsint maxResults uniqueResult Set a limit upon the number of objects to be retrieved.hibernate. Introduction to Hibernate Query Language Hibernate Query Language or HQL for short is extremely powerful query language. where HQL is not very effective. Join an association .Hibernate Query Language In the previous issue of Javajazzup you learned about Hibernate Query Language and its different kind of clauses. Much less verbose than SQL. Lets quickly focus on the overview of HQL. It automatically generates the sql query and executes it against underlying database. Mar Java Jazz Up . Criteria Interface provides the following methods Method addCriterion criterion Description Adds a Criterion to constrain the results to be retrieved Add an Order to the result set. HQL has its own objectoriented query language and supports native SQL. rooted at the associated entity. Criteria . Hibernate uses the following ways to retrieve objects from the database . Criterion.Restrictions defines factory methods for obtaining certain builtin . Finally. Restrictions The class org. List list crit.hibernate.between This is used to apply a between constraint to Java Jazz Up Mar the named property Expression. For example crit. In other words. Criterion Another core API. use the createCriteria method by invoking the Session class.and Expression. gt. The above statements are fired on the investementAmount field of the Insurance class. d.gtinvestementAmount.hibernate. The standard SQL operators . This returns the disjunction of the two expressions. respectively eq. lt. setMaxResults. In essence the Session acts as a factory for the Criteria class. Methods such as setFirstResult. A criterion is an instance of the interface org. new Integer.createCriteriaInsurance.criterion. le.addExpression. This method takes the name of the ORM class on which the query has to be executed.eq This is used to apply an equal constraint to the named property This is used to apply a greater than or equal constraint to the named property This is used to apply a greater than constraint to the named property This is used to apply a less than constraint to the named property This is used to apply an in constraint to the named property This is used to apply a less than or equal constraint to the named property This returns the conjunctions of two expressions. in the relational approach conditions is know as criterion. Expression.list.le Expression. which specify the list of those records that have the investment amount greater than .gt Expression.Hibernate Query Language Creating a Criteria instance To get a reference to the Criteria interface.criterion. the list method is invoked.in Expression. . Criterion is the objectoriented representation of the where clause of a SQL query.or . Expressions The Hibernate Query API supports a rich set of comparison operators with the Expression class. Once created.ge Expression. you add Criterion objects generally obtained from static methods of the Expression class to build the query. gt. lt. To retrieve data based on certain conditions. to execute the query. ge. The statement for it would be written as Criteria criteria session. e are supported by the following methods in the Expression class. Restriction must be used on the criteria query.lt Expression.class The above statement returns a reference to Criteria for the Order ORM class. and setCacheable may be used to customize the query behavior in the same way as in the Query interface. Following important methods of the Expression class are shown in the table Method Description Expression. eqlngInsuranceId.addcrit.gt Restriction.allEq Description This is used to apply an equals constraint to each property in the key set of a Map This is used to apply a between constraint to the named property This is used to apply an equal constraint to the named property This is used to apply a greater than or equal constraint to the named property This is used to apply a greater than constraint to the named property This is used to apply an equal constraint to the identifier property This is caseinsensitive like.or This returns the disjuction of two expressions Restriction. In code this would beCriterion critRestriction.lt Restriction.ltProperty This is used to apply a less than constraint to two properties Restriction.neProperty This is used to apply a not equal constraint to two properties Restriction. Following important methods of the Expression class are shown in the table Method Restriction.le Restriction.ge Restriction.like Restriction..idEq Restriction.not This returns the negation of an expression Restriction.isNotNull This is used to apply an is not null constraint to the named property This is used to apply an is null constraint to the named property This is used to apply a less than or equal constraint to the named property This is used to apply a like constraint to the named property This is used to apply a less than constraint to the named property Restriction.between Restriction.isNull Restriction. criteria.eq Restriction. similar to Postgres ilike operator This is used to apply an in constraint to the named property Restriction.ne This is used to apply a not equal constraint to the named property Restriction.Hibernate Query Language Criterion types.in The Hibernate criteria query API provides two query types that allow programmatic fetching of persistent objects query by criteria QBC Mar Java Jazz Up .ilike Restriction. clear. sess fact.out.list. uses two parameter e.util.text. It fetches those records from the table that meets the specified date.SessionFactory.printlnId ins.class.Configuration. This example is taking the same table Insurance as we have used in our previous issue.openSession. public class HibernateCriteriaQueryExpressionEq Java Jazz Up Mar .SimpleDateFormat. Consider the following table Insurance having such records ID insurance name Life Insurance Jivan Dhara Life Insurance Car Insurance invested amount investement date / param args / public static void mainString args // TODO Autogenerated method stub Session sess null.hibernate.hibernate.configure.addExpression. import org.text. List list crit.date. sess. import java.eq investementDate.Iterator.out.next.out.DateFormat.parse .createCriteriaInsurance. System.Hibernate Query Language and query by example QBE. System.List.cfg.getInsuranceName.getInvestementDate. import java. import org.getLngInsuranceId. Date date Dateformat.Criteria.hasNext.iterator.printlnInvestement Date ins.eqinvestementDate. DateFormat format new SimpleDateFormatyyyyMMdd hhmmss. System.Object val.Expression.date. try SessionFactory fact new Configuration. import org. Criteria crit sess. eqpropertyname.printlnInsurance Amount ins.criterion.addExpression.printlne.out. import java.hibernate.hibernate. The output of this program will be shown as Dental Insurance Life Insurance Travel Insurance Here is the code of the class using eq Expression package javajzzup. crit.Date.util. Lets take an example of query by criteria QBC using Expressions. System. import java.hibernate. In the above code the crit.getInvestementAmount.out. Insurance ins Insuranceit.buildSessionFactory. catchException e System. import org.Session.g.getMessage. forIterator it list.util. import java.printlnInsurance Name ins. import org.it.hibernate. import org. sess sfact. crit. import org.hibernate. The fieldname is passed as an argument to the property method of the Projection class.configure.cfg. List list crit. ProjectionList is the list of projection instances.hibernate. The above code retrieves all the rows from the insurance table.propertyprice.java. proList. In the above code. public class projectionExample / param args / public static void mainString args // TODO Autogenerated method stub Session sess null. proList. Then use the createQuery method of the Session object which returns a Query object.Projections.hibernate.buildSessionFactory. as in the following SQL query SELECT NAME FROM PRODUCT Here.class. Here is the full source code of projectionExample. Set it to the Criteria object by invoking the setProjection method and passing the projectList object into this method and then add this object into the List interfaces list object and iterate this object list object to display the data contained in this object. Querying with Projections Projections are used to customize the results from the database. import java.projectionList.Iterator. import org.util. proList. ProjectionList proList Projections.setProjectionproList. ifit. import org.Configuration. Now lets see an example of hibernate projection In the class projectionExample.ProjectionList.SessionFactory.addProjections.hasNext System.hibernate.setProjectionproList. Now we use the openSession method of the SessionFactory interface simply to instantiate the Session object. try SessionFactory sfact new Configuration. Now create a projectionList object add the fields having properties name and price. The Projection instance returned in turn becomes an argument to the setProjection method.hibernate.Hibernate Query Language invoking the createCriteria method of the Sessions object.list. In general Projection means to retrieve.out.printlnNo any data.hibernate.Criteria. The above query can be rewritten into a Criteria query as ProjectionList proList Projections.openSession. Then the criteria object is obtained simply by Mar Java Jazz Up .projectionList. crit.java package javajzzup.Session.propertyname. while in case of SQL Projection means Select clause.hibernate.criterion. Criteria crit sess.iterator.criterion.propertyname. which are result of Querys object.addProjections. But what if only the data contained in one of the fields has to be retrieved.addProjections. import org.util. the Projection class comes into play.List. Download Program . import org. Iterator it list. import java.createCriteriaProduct. first a session object created with the help of the SessionFactory interface. this. public void setPricedouble price this.price price.id id.cfg. Order The Order class defined in the org. The output of this program will be shown as logjWARN No appenders could be found for logger org. Java Jazz Up Mar . forint i .java to set the classs objects with the tables fields.Hibernate Query Language else whileit. Mobile . Hibernate select this. System. Keyboard . i lt row.length. public void setNameString name this.dealer dealer.Environment. double price super. public void setDidint did this.out. public int getId return id.println.printlne. public Product super. this. public class Product private int id. package javajzzup. // TODO Autogenerated constructor stub this.hasNext Object row Objectit. catchException e System. private double price. Download example . public void setIdint id this. order can be imposed upon the Criteria resultselt.did did.name as y. logjWARN Please initialize the logj system properly.out. public void setDealerDealer dealer this.i System.name name. public ProductString name.hibernate.out. public double getDid return did. private String name.close.price price.printrowi. PenDrive . public String getName return name. public double getPrice return price. // TODO Autogenerated constructor stub public Dealer getDealer return dealer. private Dealer dealer. HardDisk .name name.hibernate. private int did. Here is the code for Product. Laptop .next. sess.price as y from Product this Product Name Price Computer .getMessage.criterion package represents the order by clause of SQL.hibernate. By using the asc and desc methods of this class. new Integer . you use the addOrder method and the Order class List orde r session.list.ascname .ltprice.addExpression. The generated HQL query would be something like from Product p order by p.class .name asc Mar Java Jazz Up .addOrder Order.Hibernate Query Language To order your query results.createCriteriaProduct. isDesktopSupported desktop Desktop. the JToolTip. For example. This new functionality is provided by the java.awt. which is adopted from the JDesktop Integration Components JDIC project.Desktop class. catch URISyntaxException use use.browseuri.com. In Java.printStackTrace.URL Example with Desktop class . if Desktop. Using the Desktop class to launch a URL with default browser in Java This article describes the new Desktop API.com automatically like Launch the host systems default browser with a specific Uniform Resource Identifier URI. it will automatically open a specified URL in the systems default browser. edit.setToolTipText method is used to specify the text for a standard tooltip. import java.URISyntaxException.isDesktopSupported method to determine whether the Desktop API is available.java file. To create a custom ToolTip. which allows Java applications to interact with the default applications associated with specific file types on the host platform.URI.io. import java. Launch the host systems default email client Launch applications to open.swing package provides a class known as JToolTip. It returns the instance of JToolTip that should be used to display the tooltip. import java. Whenever this program is run. This swings component is used to display a Tip for another Component and provides API to computerize the process of using ToolTips. Desktop.printStackTrace. After compiling and running this program.net. the browser will be open with the URL javajazzup. Java Jazz Up Mar . After determining it.awt. the application can retrieve a Desktop instance using the static method getDesktop. Desktop desktop null. the JComponents createToolTip method is overridden. Lets see the code of DesktopClassToLaunch. or print files associated with those applications The sample code given below demonstrates how to launch the host systems default browser with a specific Uniform Resource Identifier URI.IOException. javax.javajazzup. public class DesktopClassToLaunch public static void mainString a try URI uri new URIhttp// www. The new Desktop API allows your Java applications to do the following ioe. import java. catch IOException ioe Download Example .Desktop.net.getDesktop. if desktop null desktop. Display ToolTip within a specified area on JFrame. tip.java import java. import java. JLabel label new JLabelHello World public JToolTip createToolTip JToolTip tip super. import javax.awt.URL Example with Desktop class The given code in the DispalyTooltip.red..setSize.setVisibletrue. .setBackgroundColor.JFrame. else setToolTipTextGot Frame. return tip.setDefaultCloseOperation JFrame.addpanel. frame.CENTER. .green. import javax.Container. label. panel. .getContentPane. Mar Java Jazz Up . public boolean containsint x. Move mouse outside of the frame area.createToolTip.swing. Lets see the outputs from the three kinds of ToolTips.setToolTipTextHello World. Download Example . tip.NORTH.swing.java file has a label component.getContentPane. int y if x lt setToolTipTextGot Component.swing. frame.setForegroundColor. JPanel panel new JPanel.setToolTipTextltHtMlgt TooltipltbrgtMessage. public class DisplayTooltip public static void mainString args String title Tooltip Sample. frame.containsx.JLabel. BorderLayout. Move mouse outside of the component area. return super. JFrame frame new JFrametitle.JPanel.EXITONCLOSE. DispalyTooltip. a related tooltip is displayed with the specified text.BorderLayout.swing. import javax. Move the mouse on the Label component. . Whenever we move the mouse on the particular component.awt. import javax. . container. y. frame. BorderLayout.JToolTip. Container container frame.addlabel. Shuffle the elements of a Collection using ArrayList interface.awt. import java. static void shuffleListltgt list static void shuffleListltgt list. System. if Arrays. char password javajazzup. Arrays.readPasswordEnter password . E. which can be found in the java.out.printlnn Access granted n.out. PasswordPrompting. else System. the password will not be echoed to the console screen and returned as an array of characters. Collections.Arrays.out.exit. C.printlnlist.console. .out. the output will be generated different each times when we shuffle the list of a Collection. It includes a method specifically for reading passwords that disables console echo and returns a char array for security purpose. The example below shows how to produce the values from to in a random order. If the given password matches with the specified characters as javajazzup then a message Access granted is displayed. B./ char passwordEntered console. The example given below read the password from the console but the password will not be echoed to the console screen.shufflelist.util.io.util namespace provides two methods that suffle the elements of a Collection. import java. otherwise it displays Access denied as an output. D. // Create a list with elements List list Arrays. B Download Example . / Read password.printlnConsole is not available. The random number methods generate numbers with replacement. import java.printlnAccess denied.Console.Arrays. public class ShuffleExample public static void mainString args String str A. CTipsampTricksgtjavac ShuffleTest.List.java import java. Random rand new Random.asListstr.java CTipsampTricksgtjava ShuffleTest A. import java.io package. ShuffleExample. Password Prompting with Java Jazz Up Mar .Collections.util. D. In this program. System.shufflelist.Console The new released JDK includes a new Console class.out. // Clear the password after validation successful Arrays. E . This class adds some new features to enhance and simplify commandline applications. while the second uses a specified source of randomness. rand.io.equalspassword. System.printlnlist. B.Random.java import java.toCharArray.URL Example with Desktop class The Collections class which can be found within the java. passwordEntered System. if console null System. . import java. a particular random number may be generated repeatedly. java. // Shuffle the elements in the list Collections. C A.fillpasswordEntered.fillpassword.util. Random rnd The first method shuffles the elements according to a default source of randomness. public class PasswordPrompting public static void mainString args Console console System. C. rand. D.exit.util. E. This means that. System.util. javajazzup.swing.addtextField. textField. DnDFieldDemo.setDragEnabledtrue. frame. DnD is a data transfer API.com. JTextField textField new JTextField.swing.pack.setContentPanenew JPanel.JPanel. frame. This program contains a TextArea and TextField with some specified text. Download Example .setDefaultCloseOperation JFrame. public class DnDFieldDemo public static void mainString args JFrame frame new JFrameDrag and Drop Demo. textArea.EXITONCLOSE.addnew JScrollPanetextArea. frame.setDragEnabledtrue.JScrollPane. JTextArea textArea new JTextArea.getContentPane. The setDragEnabled method having a true argument of each swings make it as a drag and droppable component.setVisibletrue.swing.java import javax.URL Example with Desktop class See the output when you type javajazzup as a password CTipsampTricksgtjava PasswordPromptingDemo Enter password Access granted And when you type another password CTipsampTricksgtjava PasswordPromptingDemo Enter password Access denied Download Example . drags it moves the mouse while keeping the mouse button pressed and releases the mouse button someplace else.JFrame. When the button is released the data is dropped at that location. import javax. textArea.JTextField. frame. import javax. The output will be show as Now you can drag and drop the text between TextField and TextArea. frame. The user transfers the data from one place to another by using the mouse usually.JTextArea. Drag and drop between JTextArea and JtextField In Java. .swing. import javax. import javax. One selects something with a mouse press.swing. The example given below shows how to use the draganddrop support built into Swing components.setTextwww. Mar Java Jazz Up textField.setTextdrag and drop. frame. net http//www. news and reviews on the Java technologies to the industrial technocrats. USD . articles. Un Limited Un Limited Monthly USD . we have succeeded in the dissemination of the information on technical and scientific facets of IT community providing an added value and returns to the readers..Advertise with JavaJazzUp We are the top most providers of technology stuffs to the java community. For a long time we have endeavored to provide quality information to our readers.com http//www. Deepak Kumar deepakroseindia.. Furthermore.roseindia. USD .javajazzup.com http//www.roseindia.net Java Jazz Up Mar .. JavaJazzUp Network comprises of http//www. USD USD . We have serious folks that depend on our site for real solutions to development problems.com Advertisement Options Banner Top Banner Box Banner Banner Pay Links Pop Up Banners Size x Page Views . . You may also ask about advertising on other Technology Network. .newstrackindia.allcooljobs. Our technology portal network is providing standard tutorials.net network is the real deal for technical Java professionals. Contact me today to discuss your customized sponsorship program. The http//www. Our network is getting around million hits per month and its increasing with a great pace. We do not expect everybody at Readers Forum to be an expert in some areas. your article will attract people interested in talking about it at the Readers Forum. its up to you to get it discussed. wed love to set you up in the Readers Forum and let people ask you questions. especially if they promote readers participation. Even you can post general URLs that you think would be really appreciated by the readers community. If youd like to show others aroud some familiar sites and tools. how to get your images onto Flickr. Post resourceful URLs If you think you know such URL links which can really help the readers to explore their java skills. demonstrations of PP software. If theres something youre curious about.. that would be great. Your expertise is a real resource you may contribute to the Java Jazzup. You can also present a question. combined with the knowledge of other participants. If theres a topic you feel needs to be discussed at JavaJazzup. or puzzle Were inviting people from lots of different worlds. Were open to all sorts of suggestions. If you like. a tour of MySpace. Present a question.. It would be our pleasure to give you a chance to provide your demonstrations on such issues How to set Mar Java Jazz Up . wed really love to hear about it. problem. Whether its something you think lots of people will be interested in. were confident that your curiosity.Valued JavaJazzup Readers Community We invite you to post Javatechnology oriented stuff. Handson technology demonstrations Some people are Internet experts. Some are barely familiar with the web. problem. It would be our pleasure to give space to your posts in JavaJazzup. or a narrow topic only a few people may care about. too. talk to us. Convene a discussion on a specific subject If you have a topic youd like to talk about . Anything else If you have another idea for something youd like to do. you can prepare a really a good article to explain what youre interested to tell java technocrates about. We want your curiosity to be a resource. These can be online or technologyrelated innovations that would bring you a great appreciations and recognition among the java technocrates around the globe. or puzzle that revolves around java technologies along with their solution that you think would get really appreciated by the java readers around the globe. How to get your videos onto YouTube. If theres something youre an expert on that you think other technocrates might like to know about. a tour of Second Life or let us know if there are other tools or technologies you think people should know about. will be enough to generate a useful and exciting Readers Forum. Sharing Expertise on Java Technologies If youre a great expert on a subject in java. have a crazy idea. the years you spent developing that expertise and want to share it with others.. If you want to do something that we havent thought of. Contribute to Readers Forum up a blog. Show your innovation We invite people to demonstrate innovative ideas and projects. Java Jazz Up Mar . Mar Java Jazz Up .