test2qa

Upload: ramakrishnan-harihara-venkatasubramania

Post on 10-Oct-2015

9 views

Category:

Documents


0 download

DESCRIPTION

advancedjavadatabaseservletnotes

TRANSCRIPT

1. List out the types of JDBC drivers. JDBC drivers are divided into four types or levels. The different types of jdbc drivers are: Type 1: JDBC-ODBC Bridge driver (Bridge)Type 2: Native-API/partly Java driver (Native)Type 3: AllJava/Net-protocol driver (Middleware)Type 4: All Java/Native-protocol driver (Pure)2. What are the purposes of multimedia database?Multimedia data typically means digital images, audio, video, animation and graphics together with text data. The acquisition, generation, storage and processing of multimedia data in computers and transmission over networks have grown tremendously in the recent past.The huge amount of data in different multimedia-related applications warranted to have databases as databases provide consistency, concurrency, integrity, security and availability of data. From an user perspective, databases provide functionalities for the easy manipulation, query and retrieval of highly relevant information from huge collections of stored data.MultiMedia Databases (MMDBs) have to cope up with the increased usage of a large volume of multimedia data being used in various software applications. The applications include digital libraries, manufacturing and retailing, art and entertainment, journalism and so on. Some inherent qualities of multimedia data have both direct and indirect influence on the design and development of a multimedia database. MMDBs are supposed to provide almost all the functionalities, a traditional database provides. Apart from those, a MMDB has to provide some new and enhanced functionalities and features. MMDBs are required to provide unified frameworks for storing, processing, retrieving, transmitting and presenting a variety of media data types in a wide variety of formats. At the same time, they must adhere to numerical constraints that are normally not found in traditional databases.3. List out the states of servlet cycle.When we sent a request from client to server, the protocol will establish a socket connection Between Client and Server.Then the protocol will carry the client request to server machine.At server machine there are Main Server and Container.First the Main Server will Validates the client request ,if it is successfully then it will bypass to Container,Then the Container will perform the following steps.1.)The container will get the requested Uri with Application name and resource name .It checks for the resources name i.e whether it is html/jsp ,if it is html/jsp then the Container will get requested Resource above WEB-INF which is in public area.2.)If the requested resource is not html/jsp ,then it will think that is an url-pattern which is available under WEB-INF.3.)Then the container will go to Web.XML and find the respective resources i.e Servlet by matching the URL-pattern,then the Container will reform the following steps Loading and Instantiation:The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute of web.xml file. If the attribute has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.Initialization:After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.Servicing the Request:After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.Destroying the Servlet:If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.4. Define Strut. Struts is the most popular framework for developing Java based web applications. Struts is being developed as an open source project started by Apache Software Foundation . Struts framework is based on Model View Controller (MVC) architecture5. List out the differences between ODBC and JDBC.1.ODBC is for Microsoft and JDBC is for java applications.2.ODBC can't be directly used with Java because it uses a C interface.3.ODBC makes use of pointers which have been removed totally from java.4.ODBC mixes simple and advanced features together and has complex options for simple queries, But JDBC is designed to keep things simple while allowing advanced capabilities when required.5. ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in java and JDBC code is automatically installable, secure, and portable on all platforms.6. JDBC API is a natural Java Interface and is built on ODBC. JDBC retains some of the basic feature of ODBC

6. Write two examples of multimedia databases. ASPexplore Software v.1.1.22.1ASPexplore Software 1.1.22.1 is a effective program which lets you run Microsoft Web ASP scripts off-line, without any Web server and create an interactive, multimedia, database driven application. Web Multimedia Catalog & Player v.3A web-based multimedia database & player designed specifically to supplement your local hardware network by allowing you to graphically build & playback your playlists using streaming media. If you'd like to help, please email the project. File Name:download?use_mirror=heanet Author:ten3pm License:Freeware (Free) File Size:114 Kb Runs on:Windows; Mac; Linux ASPexplore Software v.1.1.22.1 ASPexplore Software 1.1.22.1 is a effective program which lets you run Microsoft Web ASP scripts off-line, without any Web server and create an interactive, multimedia, database driven application.It consists of two important components:. File Name:http://www.makolab.pl/ Author:makolab License:Trial ($99.00) File Size:4 Mb Runs on:Windows 95, Windows XP, Windows 2000, Windows Almagest v.1.2.0 A multimedia database system comprised of a relational database and a web-based user interface, written in Java, JSP and PL/SQL. It features various searching capabilities and the ability to arrange media items into stored. File Name:download?use_mirror=iweb Author:princeton License:Freeware (Free) File Size:635 Kb Runs on:Solaris; Linux Web Multimedia Catalog & Player v.3 A web-based multimedia database & player designed specifically to supplement your local hardware network by allowing you to graphically build & playback your playlists using streaming media. If you'd like to help, please email the project manager. File Name:download?source=directory Author:Matt Croydon, Adam Shantz License:Freeware (Free) File Size:114 Kb Runs on:Windows; Mac; Linux Kaztrix DataBuilder v.1.0 KazTrix DataBuilder 1.0 is the ultimate database designer/publisher. It allows novice and expert users to build databases of all kinds and access them on their PC or easily publish them to the Internet. Simply Intelligent!! File Name:kazv1.zip Author:Kaztrix Software License:Commercial ($149.00) File Size:13.35 Mb Runs on:Win95, Win98, WinME, WinXP, Windows2000 Photo Organizer Deluxe v.3.0 Photo Organizer Deluxe is a complete program that allows PC users to create and manage all kinds of picture and multimedia catalogs. For the database novice, Photo Organizer's intuitive interface and ready-to-use templates make it easy to set up and. File Name:pho.exe Author:PrimaSoft PC License:Shareware ($75.00) File Size:6.84 Mb Runs on:Win95, Win98, WinME, WinNT 4.x, Windows2000, WinXP, Windows2003, Windows Vista M-DVD.Org V2 v.2.5

M-DVD.Org V2 provides you with a uniform interface to easily and professionally manage your music and movie collections and the corresponding covers. Bonus: Integrated DVD archive - offline details of more than 25,000 DVDs + Blu-ray/HD DVD. File Name:M-DVD_Org_Ver_2_5-DEMO_EN.ex e Author:SynApp GmbH License:Demo ($58.50) File Size:31.51 Mb Runs on:WinXP, Windows2000, Windows Vista, Windows M-DVD.Org V2 - Audio-Manager v.2.5

M-DVD.Org V2 - Audio-Manager provides you with a uniform interface to manage your music (audio data) and the corresponding covers easily and professionally. The following formats are supported: CD, MP3, WMA, AAC, FLAC, Ogg, MPC, APE, MP4, WAV. File Name:Audio-Manager_Ver_2_5-DEMO_E N.exe Author:SynApp GmbH License:Demo ($36.50) File Size:31.63 Mb Runs on:WinXP, Windows2000, Windows Vista, Windows M-DVD.Org V2 - DVD-Manager v.2.5

M-DVD.Org V2 - DVD-Manager provides you with a uniform interface to manage your DVDs and corresponding covers easily and professionally. Bonus: Integrated DVD-Archive - offline information on more than 25,000 DVDs + Blu-ray and HD DVD. File Name:DVD-Manager_Ver_2_5-DEMO_EN. exe Author:SynApp GmbH License:Demo ($29.50) File Size:31.63 Mb Runs on:WinXP, Windows2000, Windows Vista, Windows AtomicView for Mac OS v.1.5 A digital asset manager (DAM) software program. Thanks to AtomicView you can find, view and organize all your photo, image, video and sound files with great ease. AtomicView is extremely rapid and responsive. With its 100% parallelism, it brings out. File Name:AtomicViewDemoMac.zip Author:AntZero License:Freeware (Free) File Size:51.6 Mb Runs on:Mac OS X 10.4 or later Zabaan v.101b a multimedia database of human languages, written in java. provides the flashcard functionality used for learning foreign languages.You can enter words, (both text and sounds,) from multiple languages, and play them back in multiple ways7. Compare servlets with CGI.

8. What is meant by EJB?Enterprise JavaBeans (EJB) is server side component architecture that enables and simplifies the process of building enterprise class distributed object applications in Java. 9. Define JNI.The Java Native Interface (JNI) is a native programming interface that is part of the Java SoftwareDevelopment Kit (SDK). JNI lets Java code use code and code libraries written in other languages,such as C and C++. The Invocation API, which is part of JNI, can be used to embed a Java virtualmachine (JVM) into native applications, thereby allowing programmers to call Java code fromwithin native code. A Java compiler: javac.exe ships with the SDK. A Java virtual machine (JVM): java.exe ships with the SDK. A native method C file generator: javah.exe ships with the SDK. Library files and native header files that define JNI. The jni.h C header file, jvm.lib, andjvm.dll or jvm.so files all ship with the SDK. A C and C++ compiler that can create a shared library. 10.What is JBuilder?JBuilderis anintegrated development environment(IDE) for theprogramming languageJavafromEmbarcadero Technologies. Originally developed byBorlandJBuilder was spun off withCodeGearwhich was eventually purchased by Embarcadero Technologies in 2008.11 a). Briefly describe apache struts. 8 marks Apache Strutswas anopen-sourceweb application frameworkfor developingJava EEweb applications. It uses and extends theJava ServletAPIto encourage developers to adopt amodelviewcontroller(MVC) architecture. It was originally created byCraig McClanahanand donated to theApache Foundationin May, 2000. Formerly located under the ApacheJakarta Projectand known asJakarta Struts, it became a top-level Apache project in 2005.TheWebWorkframework spun off from Apache Struts aiming to offer enhancements and refinements while retaining the same general architecture of the original Struts framework. However, it was announced in December 2005 that Struts would re-merge with WebWork. WebWork 2.2 has been adopted asApache Struts 2, which reached its first full release in February 2007.Design goals and overview[edit]In a standardJava EEweb application, the client will typically call to the server via aweb form. The information is then either handed over to aJava Servletwhich interacts with a database and produces anHTML-formatted response, or it is given to aJavaServer Pages(JSP) document that intermingles HTML and Java code to achieve the same result. Both approaches are often considered inadequate for large projects because they mix application logic with presentation and make maintenance difficult.The goal of Struts is to separate themodel(application logic that interacts with a database) from theview(HTML pages presented to the client) and thecontroller(instance that passes information between view and model). Struts provides the controller (a servlet known asActionServlet) and facilitates the writing of templates for the view or presentation layer (typically in JSP, butXML/XSLTandVelocityare also supported). The web application programmer is responsible for writing the model code, and for creating a central configuration filestruts-config.xmlthat binds together model, view, and controller.Requests from the client are sent to the controller in the form of "Actions" defined in the configuration file; if the controller receives such a request it calls the corresponding Action class that interacts with the application-specific model code. The model code returns an "ActionForward", a string telling the controller what output page to send to the client. Information is passed between model and view in the form of specialJavaBeans. A powerful custom tag library allows it to read and write the content of these beans from the presentation layer without the need for any embedded Java code.Struts is categorized as aModel 2request-based web application framework.[3]Struts also supportsinternationalizationby web forms, and includes a template mechanism called "Tiles" that (for instance) allows the presentation layer to be composed from independent header, footer, menu navigation and content components.Apache Struts 2is anopen-sourceweb application frameworkfor developingJava EEweb applications. It uses and extends theJava ServletAPIto encourage developers to adopt amodelviewcontroller(MVC) architecture. TheWebWorkframework spun off fromApache Strutsaiming to offer enhancements and refinements while retaining the same general architecture of the original Struts framework. In December 2005, it was announced that WebWork 2.2 was adopted as Apache Struts 2, which reached its first full release in February 2007.[1]Features[edit] SimplePOJO-based actions Simplified testability Thread safe AJAXsupport jQueryplugin Dojo Toolkitplugin (deprecated) Ajax client-side validation Template support Support for different result types Easy to extend with plugins RESTplugin (REST-based actions, extension-less URLs) Convention plugin (action configuration via Conventions and Annotations) Spring plugin (dependency injection) Hibernateplugin Support in design JFreechart plugin (charts) jQueryplugin (Ajax support, UI widgets, dynamic table, charts) Rome plugin plugin11 b). Briefly describe JBuilder. 8 marks JBuilderis anintegrated development environment(IDE) for theprogramming languageJavafromEmbarcadero Technologies. Originally developed byBorlandJBuilder was spun off withCodeGearwhich was eventually purchased by Embarcadero Technologies in 2008.JBuilder's main competitors are the products fromEclipse Foundation(Eclipse),Genuitec(MyEclipse),JetBrains(IntelliJ IDEA), andOracle(JDeveloperandNetBeans). Oracle used to base the first versions of JDeveloper on code from JBuilder licensed from Borland, but it has since been rewritten from scratch.[1]Contents[hide] 1Versions 2See also 3References 4External linksVersions[edit]NameYearEditions

JBuilder 11997Client/Server, Professional, Standard

JBuilder 21998Client/Server, Professional, Standard

JBuilder 31999

JBuilder 3.51999Introducing 100%-Java PrimeTime core IDE available on Linux, Solaris and Windows

JBuilder 42000

JBuilder 52001Adding host support for Mac OS X[2]

JBuilder 62001

JBuilder 72002Enterprise, Standard (SE), Personal; updated (code patches) to at least Update 3

JBuilder 82002Enterprise, Standard (SE), Personal; updated to at least the first one: JBuilder 8 Update

JBuilder 92003Enterprise, Standard (SE), Personal; updated to at least Update 2

JBuilder X2003Enterprise, Developer, Foundation; updated to at least Update 3

JBuilder 20052004Enterprise, Developer, Foundation; updated to at least Update 4

JBuilder 20062005Enterprise, Developer, Foundation

JBuilder 20072006Enterprise, Professional, Developer;User interface and features changed much from prior versions, first version redone to work on Eclipse[3]

JBuilder 2007 R22007Enterprise, Standard (SE), Turbo[4]

JBuilder 20082008Enterprise, Professional, Turbo

JBuilder 2008 R22009Enterprise, Professional, Turbo

JBuilder 1 through 3 were based on the Delphi IDE. JBuilder 3.5 through 2006 were based on Primetime, their all-Java IDE framework. JBuilder 2007 "Peloton" was the first JBuilder release to be based on the Eclipse IDE framework.[5]Advantages1. Reduce learning curve by using the same IDE for multiple platformsJBuilder 2008 R2 supports the latest commercial and open source Java application servers including Borland Enterprise Server, BEA WebLogic Application Server, IBM WebSphere, JBoss, Oracle Application Server, Oracle Containers for Java (OC4J), Apache Geronimo, Apache Tomcat, and Sun GlassFish. This means that regardless of which application server(s) you are targeting for deployment, you can use a single IDE.2. Speed development with support for the latest Java technologiesThe graphical EJB Workbench in JBuilder 2008 R2 provides a simplified RAD development experience for both novice and experienced Java EE developers alike. Legacy projects using EJB 2.x are easily converted to the new annotation-based EJB 3.x specification. Easily create EJBs and model relationships, security and OCL constraints. JBuilder's patented LiveSourceTMtechnology insures that changes to the source code, annotations, properties view and graphical view are always in sync.3. Enhanced usability and feature navigationJBuilder 2008 R2 includes several new features which enhance the user experience and ultimately make developers more productive. JBuilder 2008 R2 now comes with a standard set of UI profiles which reduce clutter in the workbench. The new Getting Started wizard helps with the initial configuration of a workspace. The Feature Navigator moves through existing IDE features and UI elements using help topics, wizards and one or more cheat sheets which collectively define common workflows or development activities.4. Easily move JBuilder and Eclipse projects forwardJBuilder 2008 R2 advances developers to the latest Eclipse-based JBuilder platform with backward compatibility support for previous versions of JBuilder. Easily import existing projects into the new JBuilder 2008 R2 IDE. Enjoy the flexibility and cost-efficiencies associated with the Eclipse open source framework, and the enterprise-class functionality, reliability, and support you require.5. Experience unparalleled productivity and code reuseThe Application Factories functionality in JBuilder 2008 R2 introduces an application-driven development paradigm, where the structure, evolution, and logic behind the development of the application are checked into version control along with the source code for the application itself. The Application Factory records the developers intent as an application is being created so that the workings of the code can be easily ascertained at a later date. And while Application Factories certainly yields higher levels productivity during the development of an application, one of the biggest benefits may come when that application has to be modified or enhanced. This is because the metadata, which stays attached to the code when it is created, can be opened by any subsequent developer to understand the context and purpose of code snippets, methods, and classes which are part of the application.6. Rapidly create sophisticated Swing-based applicationsSwing Designer in JBuilder 2008 R2 is a comprehensive set of user interface construction tools designed to enable developers to rapidly create Java Swing applications. The visual designer, wizards, editors, and intelligent layout assistance supports Swing/AWT development including the most popular controls and layout managers. Swing Designer provides full bi-directional code generation, with the visual design and the source always in 100% synchronization. JBuilder developers can focus on creating application specific functionality rather than coding the low-level logic required for graphical user interfaces.7. Analyze, debug, and tune applications within the IDEHigh-level performance-related data displayed in real time allows developers to understand whether a performance issue is related to CPU, memory, or both. Automatic Memory Leak Detector monitors the evolution of memory usage over time for the immediate identification of potential memory leaks. Real-time monitoring of object allocations to understand how the profiled program uses the virtual machine memory; Allocation Backtrace View allows developers to identify the code or part of the program responsible for instance allocations. Thread Debugger gives real-time display of the progress of all threads running within the Virtual Machine. Code Coverage provides a Real-time Class Coverage View to quickly see the coverage for each class and identify classes not fully covered.8. Increase individual and team productivityJBuilder 2008 R2 provides team and project manageability through the TeamInsight collaboration feature. Individual developers have a unified real-time view of their project responsibilities for bugs, change requests, code notes, tasks and requirements, and the entire team has a shared project Web portal with live data and statistics on team vector and velocity. ProjectAssist provides simple, single point installation and configuration of a complete developer tool stack for bug tracking, source code management, project planning/tracking, requirements management and continuous integration builds, saving days or weeks of manual configuration and integration. JBuilder 2008 R2 also provides integrated support for live and off-line editing of all project artifacts including defects, source, project tasks and requirements. All projects are automatically synchronized when on-line.9. Accelerate creation of Web servicesThe Web Services Workbench in JBuilder 2008 R2 is a visual, two-way designer for creating Axis based Web service-enabled applications. The workbench supports instant navigation between Web services components displayed in the designer (e.g. WSDL, methods, operations) and the corresponding source code. Key features of the Web Services Workbench include the ability to do the following: Import a WSDL document to build a test client for a Web service discovered through a UDDI registry Build a SOAP server to act as the base for a Web service Expose a simple Java class as a Web service Expose an EJB Session Bean as a Web service Debug a Web service and a Web service client concurrently Dynamically generates and deploy Web service components during project builds10. Improve productivity and code comprehension with UML modeling and code archeologyJBuilder 2008 R2 provides Java UML 2.0 modeling capabilities, including support for all standard modeling diagrams such as Sequence diagrams, Use Case diagrams, Activity diagrams, Class diagrams, Component diagrams, Deployment diagrams, State Machine diagrams, Composite Structure diagrams, Communication diagrams, and Web Services diagrams. Both HTML format and template-driven document generation are supported. The LiveSource technology in JBuilder 2008 R2 simultaneously synchronizes changes made to the UML models in the code, and vice versa.11. Improve code quality with audits and metricsThe audits and metrics capabilities in JBuilder 2008 R2 can be used to solve the code quality, code review and code dependency issues typically faced in software development. JBuilders audits and metrics are designed to aid developers in finding and fixing problems in their code earlier in the development process. JBuilders audits perform a static analysis of your source code, identifying coding problems like potential race conditions, unchecked exceptions and more. JBuilder's metrics provide a similar analysis for design problems in your project.12. Leverage the latest Eclipse open source frameworkThe JBuilder 2008 R2 product line builds on the common Java and Java EE development capabilities found in Eclipse 3.4.1 and Web Tools Platform 3.0 to meet the needs of Java developers at every level. And, because JBuilder 2008 R2 is based on the worlds most popular open source IDE framework, developers are more than likely already familiar with many of the basic features and functions found in the IDE which means a lower learning curve and shorter time to being fully productive.In addition to the core Eclipse functionality, Embarcadero also provides over one hundred third-party plug-ins and enhancements for a more complete user experience. As a trusted turn-key solution, JBuilder 2008 R2 gives developers the confidence to expand these capabilities by providing a one-stop shop for downloading and integrating these and other technologies into a single, managed, and supported development environment.

12 a). Outline the 6 steps for creating a JNI example for connecting java with C++. 8 marksSix steps to call C/C++ from Java codeThe process of calling C or C ++ from Java programs consists of six steps. We'll go over each stepin depth in the sections that follow, but let's start with a quick look at each one.1. Write the Java code. We'll start by writing Java classes to perform three tasks: declare thenative method we'll be calling; load the shared library containing the native code; and call thenative method.2. Compile the Java code. We must successfully compile the Java class or classes to bytecodebefore we can use them.3. Create the C/C++ header file. The C/C++ header file will declare the native functionsignature that we want to call. This header will then be used with the C/C++ functionimplementation (see Step 4) to create the shared library (see Step 5).4. Write the C/C++ code. This step consists of implementing the function in a C or C++ sourcecode file. The C/C++ source file must include the header file we created in Step 3.5. Create the shared library file. We'll create a shared library file from the C source code filewe created in Step 4.6. Run the Java program. We'll run the code and see if it works. We'll also go over some tipsfor dealing with the more commonly occurring errors.Step 1: Write the Java codeWe'll start by writing the Java source code file, which will declare the native method (or methods),load the shared library containing the native code, and actually call the native method.Here's our example Java source code file, called Sample1.java:public class Sample1{ public native int intMethod(int n); public native boolean booleanMethod(boolean bool); public native String stringMethod(String text); public native int intArrayMethod(int[] intArray);

public static void main(String[] args) { System.loadLibrary("Sample1"); Sample1 sample = new Sample1(); int square = sample.intMethod(5); boolean bool = sample.booleanMethod(true); String text = sample.stringMethod("JAVA"); int sum = sample.intArrayMethod( new int[]{1,1,2,3,5,8,13} );

System.out.println("intMethod: " + square); System.out.println("booleanMethod: " + bool); System.out.println("stringMethod: " + text); System.out.println("intArrayMethod: " + sum); }} What's happening in this code?First of all, note the use of the native keyword, which can be used only with methods. The nativekeyword tells the Java compiler that a method is implemented in native code outside of the Javaclass in which it is being declared. Native methods can only be declared in Java classes, notimplemented, so a native method cannot have a body.Now, let's look at the code line by line: In lines 3 through 6 we declare four native methods. On line 10 we load the shared library file containing the implementation for these nativemethods. (We'll create the shared library file when we come to Step 5.) Finally, in lines 12 through 15 we call the native methods. Note that this operation is nodifferent from the operation of calling non-native Java methods.Step 2: Compile the Java codeNext, we need to compile the Java code down to bytecode. One way to do this is to use the Javacompiler, javac, which comes with the SDK. The command we use to compile our Java code tobytecode is:javac Sample2.javaStep 3: Create the C/C++ header fileThe third step is to create a C/C++ header file that defines native function signatures. One way todo this is to use the native method C stub generator tool, javah.exe, which comes with the SDK.javah Sample1Results of running javah.exe on Sample1.javaSample1.h, below, is the C/C++ header file generated by running the javah tool on our Java code: 1. /* DO NOT EDIT THIS FILE - it is machine generated */ 2. #include 3. /* Header for class Sample1 */ 4. 5. #ifndef _Included_Sample1 6. #define _Included_Sample1 7. #ifdef __cplusplus 8. extern "C" { 9. #endif10.11. JNIEXPORT jint JNICALL Java_Sample1_intMethod12. (JNIEnv *, jobject, jint);13.14. JNIEXPORT jboolean JNICALL Java_Sample1_booleanMethod15. (JNIEnv *, jobject, jboolean);16.17. JNIEXPORT jstring JNICALL Java_Sample1_stringMethod18. (JNIEnv *, jobject, jstring);19.20. JNIEXPORT jint JNICALL Java_Sample1_intArrayMethod21. (JNIEnv *, jobject, jintArray);22.23. #ifdef __cplusplus24. }25. #endif26. #endifStep 4: Write the C/C++ codeWhen it comes to writing the C/C++ function implementation, the important thing to keep in mindis that our signatures must be exactly like the function declarations from Sample1.h. We'll lookat the complete code for both a C implementation and a C++ implementation, then discuss thedifferences between the two..

#include "Sample1.h"#include

JNIEXPORT jint JNICALL Java_Sample1_intMethod (JNIEnv *env, jobject obj, jint num) { return num * num; } JNIEXPORT jboolean JNICALL Java_Sample1_booleanMethod (JNIEnv *env, jobject obj, jboolean boolean) { return !boolean; }

JNIEXPORT jstring JNICALL Java_Sample1_stringMethod (JNIEnv *env, jobject obj, jstring string) { const char *str = env->GetStringUTFChars(string, 0);

char cap[128]; strcpy(cap, str); env->ReleaseStringUTFChars(string, str); return env->NewStringUTF(strupr(cap)); }

JNIEXPORT jint JNICALL Java_Sample1_intArrayMethod (JNIEnv *env, jobject obj, jintArray array) { int i, sum = 0; jsize len = env->GetArrayLength(array); jint *body = env->GetIntArrayElements(array, 0); for (i=0; iReleaseIntArrayElements(array, body, 0); return sum; }

void main(){}

Step 5: Create the shared library fileC syntax: jsize len = (*env)->GetArrayLength(env,array);C++ syntax: jsize len =env->GetArrayLength(array);Next, we create a shared library file that contains the native code. Most C and C++ compilers cancreate shared library files in addition to machine code executables. The command you use tocreate the shared library file depends on the compiler you're using. Below are the commands thatwill work on Windows and Solaris systems.Step 6: Run the Java programWindows: cl -Ic:\jdk\include -Ic:\jdk\include\win32 -LD Sample1.c -FeSample1.dllSolaris: cc -G -I/usr/local/jdk/include -I/user/local/jdk/include/solaris Sample1.c -o Sample1.soThe last step is to run the Java program and make sure that the code works correctly. Becauseall Java code must be executed in a Java virtual machine, we need to use a Java runtimeenvironment. One way to do this is to use the Java interpreter, java, which comes with the SDK.The command to use is:java Sample1When we run the Sample1.class program, we should get the following result:PROMPT>java Sample1intMethod: 25booleanMethod: falsestringMethod: JAVAintArrayMethod: 33PROMPT>12 b). Discuss the difference between servlets and applets. 8 marksApplet is a part of Core JAVA and Servlet of Advance Java. Applet is client side program and Servlet is Server side. When Applet runs it take the resources of client whereas Servlet is processed at server side.Applets Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers. An Applet is a client side java program that runs within a Web browser on the client machine. An applet can use the user interface classes like AWT or Swing. Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy()Servlets Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server. Servlet is a server side component which runs on the web server. The servlet does not have a user interface. Servlet Methods: doGet(), doPost()13 a)Write a JDBC program to store the data to student table and display it. A java application can be connected to Database in three steps.a) First a suitable driver for the databases has to be identified. For example ojdbc7 driver for oracle and derby driver for javadb (GlassFish free download) has to be downloaded. This has to be copied into jre/lib/ext directory.b) Import java.sql.* library into java program . this includes java.sql.connection, java..sql.DriverManager,java.sq.SQLException, java.sql.statement and java.sql.Resultset claases.c) Assuming already the database is started and assuming the database name is employees, the database is connected to 1527 port, and the username is drhvr3 and password radha the connection string Connection con = DriverManager.getConnection( host, uName,uPass) connects it to the database whereString host = "jdbc:derby://localhost:1527/Employees"; String uName = "drhvr3"; String uPass= "radha";d) Constructing different statements such as UPDATE, INSERT, CREATE the required database table can be updated , data inserted or table created.A sample program for creating a student table, inserting data and displaying the data is given below.import java.sql.*;public class StuDbCon { Connection con; ResultSet rs; public static void main(String[] args) { try { String host = "jdbc:derby://localhost:1527/Employees"; String uName = "drhvr3"; String uPass= "radha"; Connection con = DriverManager.getConnection( host, uName,uPass); String dropString = "Drop Table Students"; Statement stmt = con.createStatement(); stmt.executeUpdate(dropString); String createString = "create table Students(" +"REGNO INTEGER, " +"STUDENT_NAME VARCHAR(20), "+"BRANCH_NAME VARCHAR(30))"; stmt = con.createStatement(); stmt.executeUpdate(createString);String insertString1, insertString2, insertString3; insertString1 = "insert into Students values(29, 'hvr','CSE')"; insertString2 = "insert into Students values(36,'Manivannan', 'EEE')"; insertString3 = "insert into Students values(37, 'Bala', 'Mechanical')"; stmt = con.createStatement(); stmt.executeUpdate(insertString1); stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); show(); stmt = con.createStatement( ); String SQL = "UPDATE Students SET BRANCH_NAME= 'ELECTRICAL AND ELECTRONICS' WHERE BRANCH_NAME = 'EEE' "; stmt.executeUpdate( SQL ); show(); } catch ( SQLException err ) { System.out.println( err.getMessage( ) ); } }13b) Describe about database support in web applications.How do web applications work?The figure below details the three-layered web application model. The first layer is normally a web browser or the user interface; the second layer is the dynamic content generation technology tool such as Java servlets (JSP) or Active Server Pages (ASP), and the third layer is the database containing content (e.g., news) and customer data (e.g., usernames and passwords, social security numbers and credit card details).

+The figure below shows how the initial request is triggered by the user through the browser over the Internet to the web application server. The web application accesses the databases servers to perform the requested task updating and retrieving the information lying within the database. The web application then presents the information to the user through the browser.

Web SecurityIssuesDespite their advantages, web applications do raise a number of security concerns stemming from improper coding. Serious weaknesses or vulnerabilities, allow hackers to gain direct and public access to databases in order to churn sensitive data. Many of these databases contain valuable information (e.g., personal and financial details) making them a frequent target of hackers. Although such acts of vandalism as defacing corporate websites are still commonplace, nowadays, hackers prefer gaining access to the sensitive data residing on the database server because of the immense pay-offs in selling the data.In the framework described above, it is easy to see how a hacker can quickly access the data residing on the database through a dose of creativity and, with luck, negligence or human error, leading to vulnerabilities in the web applications.As stated, websites depend on databases to deliver the required information to visitors. If web applications are not secure, i.e., vulnerable to, at least one of the various forms of hacking techniques, then your entire database of sensitive information is at serious risk.Some hackers, for example, may maliciously inject code within vulnerable web applications to trick users and redirect them towards phishing sites. This technique is calledCross-Site Scriptingand may be used even though the web servers and database engine contain no vulnerability themselves.Recent research shows that 75% of cyber attacks are done at web application level.

Websites and related web applications must be available 24 hours a day, 7 days a week, to provide the required service to customers, employees, suppliers and other stakeholders. Firewalls and SSL provide no protection against web application hacking, simply because access to the website has to be made public All modern database systems (e.g. Microsoft SQL Server, Oracle and MySQL) may be accessed through specific ports (e.g., port 80 and 443) and anyone can attempt direct connections to the databases effectively bypassing the security mechanisms used by the operating system. These ports remain open to allow communication with legitimate traffic and therefore constitute a major vulnerability. Web applications often have direct access to backend data such as customer databases and, hence, control valuable data and are much more difficult to secure. Those that do not have access will have some form of script that allows data capture and transmission. If a hacker becomes aware of weaknesses in such a script, he may easily reroute unwitting traffic to another location and illegitimately hive off personal details. Most web applications are custom-made and, therefore, involve a lesser degree of testing than off-the-shelf software. Consequently, custom applications are more susceptible to attackWeb applications, therefore, are a gateway to databases especially custom applications which are not developed with security best practices and which do not undergo regular security audits. In general, you need to answer the question: Which parts of a website we thought are secure are open to hack attacks? and what data can we throw at an application to cause it to perform something it shouldnt do?.This is the work of a web vulnerability scanner.Acunetix Web Vulnerability ScannerProof of such exploits are readily available on the Internet and are the subject of discussion in several press releases by Acunetix, a leading vendor of web application security products.Click hereto learn more about Acunetix Web Vulnerability Scanner.

14a) Write a servlet program to verify the username and password. Reg.html:



USERID:

PASSWORD:

NAME:

DOB:

ADDRESS:



Registration servlet:Reg.java :import java.sql.*;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class reg extends HttpServlet{public void service(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{PrintWriter pw=resp.getWriter();resp.setContentType("text/html");pw.println("");String id1=req.getParameter("id");String pwd1=req.getParameter("pwd");String name=req.getParameter("name");String dob=req.getParameter("dob");String addr=req.getParameter("addr");int no=Integer.parseInt(phno);try{ String host = "jdbc:derby://localhost:1527/Employees"; String uName = "drhvr3"; String uPass= "radha"; Connection con = DriverManager.getConnection( host, uName,uPass);Statement stmt=con.createStatement();String sqlstmt="select id,pwd from login where id =id1";ResultSet rs=stmt.executeQuery(sqlstmt);int flag=0;while(rs.next()){flag=1;}} if(flag==1){pw.println("

SORRY INVALID ID ALREADYEXITS TRY AGAIN WITH NEW ID

");pw.println("press REGISTER toRETRY");} else{Statement stmt1=con.createStatement();stmt1.executeUpdate("insert into loginvalues('"+name+"','"+addr+"',"+no+",'"+id1+"','"+pwd1+"');");pw.println("

Welcome + name + Password + pwd1+ ENTERED

");}pw.println("");} catch(Exception e){resp.sendError(500,e.toString());}}} 14b) Write in detail about EJB. Enterprise JavaBeansFrom Wikipedia, the free encyclopediaJump to: navigation, search Not to be confused with JavaBeans.Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications.The EJB specification is one of several Java APIs in the Java EE specification. EJB is a server-side model that encapsulates the business logic of an application. The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999[1] and enhanced under the Java Community Process as JSR 19 (EJB 2.0), JSR 153 (EJB 2.1), JSR 220 (EJB 3.0), JSR 318 (EJB 3.1) and JSR 345 (EJB 3.2).The EJB specification intends to provide a standard way to implement the back-end 'business' code typically found in enterprise applications (as opposed to 'front-end' interface code). Such code addresses the same types of problems, and solutions to these problems are often repeatedly re-implemented by programmers. Enterprise JavaBeans are intended to handle such common concerns as persistence, transactional integrity, and security in a standard way, leaving programmers free to concentrate on the particular problem at hand.ContentsGeneral responsibilitiesThe EJB specification details how an application server provides the following responsibilities: Transaction processing Integration with the persistence services offered by the Java Persistence API (JPA) Concurrency control Event-driven programming using Java Message Service and Java EE Connector Architecture Asynchronous method invocation Job scheduling Naming and directory services (JNDI) Interprocess Communication using RMI-IIOP and Web services Security (JCE and JAAS) Deployment of software components in an application serverAdditionally, the Enterprise JavaBean specification defines the roles played by the EJB container and the EJBs as well as how to deploy the EJBs in a container. Note that the current EJB 3.2 specification does not detail how an application server provides persistence (a task delegated to the JPA specification), but instead details how business logic can easily integrate with the persistence services offered by the application server.Rapid adoption followed by criticismThe vision was persuasively presented by EJB advocates such as IBM and Sun Microsystems, and Enterprise JavaBeans were quickly adopted by large companies. Problems were quick to appear with initial versions. Some developers felt that the APIs of the EJB standard were far more complex than those developers were used to. An abundance of checked exceptions, required interfaces, and the implementation of the bean class as an abstract class were unusual and counter-intuitive for programmers. The problems that the EJB standard was attempting to address, such as object-relational mapping and transactional integrity, were complex, however many programmers found the APIs to be just as difficult, leading to a perception that EJBs introduced complexity without delivering real benefits.In addition, businesses found that using EJBs to encapsulate business logic brought a performance penalty. This is because the original specification only allowed for remote method invocation through CORBA (and optionally other protocols), even though the large majority of business applications actually do not require this distributed computing functionality. The EJB 2.0 specification addressed this concern by adding the concept of local interfaces which could be called directly without performance penalties by applications that were not distributed over multiple servers.[2]The complexity issue continued to hinder EJB's acceptance.[citation needed] Although developer tools made it easy to create and use EJBs by automating most of the repetitive tasks, these tools did not make it any easier to learn how to use the technology. Moreover, a counter-movement had grown up on the grass-roots level among programmers. The main products of this movement were the so-called 'lightweight' (i.e. in comparison to EJB) technologies of Hibernate (for persistence and object-relational mapping) and the Spring Framework (which provided an alternate and far less verbose way to encode business logic). Despite lacking the support of big businesses, these technologies grew in popularity and were adopted by businesses.Reinventing EJBsGradually an industry consensus emerged that the original EJB specification's primary virtue enabling transactional integrity over distributed applications was of limited use to most enterprise applications, and the functionality delivered by simpler frameworks like Spring and Hibernate was more useful.Accordingly, the EJB 3.0 specification (JSR 220) was a radical departure from its predecessors, following this new paradigm. It shows a clear influence from Spring in its use of plain Java objects, and its support for dependency injection to simplify configuration and integration of heterogeneous systems. Gavin King, the creator of Hibernate, participated in the EJB 3.0 process and is an outspoken advocate of the technology. Many features originally in Hibernate were incorporated in the Java Persistence API, the replacement for entity beans in EJB 3.0. The EJB 3.0 specification relies heavily on the use of annotations (a feature added to the Java language with its 5.0 release) and convention over configuration to enable a much less verbose coding style.Accordingly, in practical terms EJB 3.0 is much more lightweight and nearly a completely new API, bearing little resemblance to the previous EJB specifications.ExampleThe following shows a basic example of what an EJB looks like in code:@Stateless public class CustomerService { @PersistenceContext private EntityManager entityManager; public void addCustomer(Customer customer) { entityManager.persist(customer); } }The above defines a service class for persisting a Customer object (via O/R mapping). The EJB takes care of managing the persistence context and the addCustomer() method is transactional and thread-safe by default. As demonstrated, the EJB focuses only on business logic and persistence and knows nothing about any particular presentation.Such an EJB can be used by a class in e.g. the web layer as follows:@Named @RequestScopedpublic class CustomerBacking { @EJB private CustomerService customerService; public String addCustomer(Customer customer) { customerService.addCustomer(customer); context.addMessage(...); // abbreviated for brevity return "customer_overview"; }}The above defines a JavaServer Faces (JSF) backing bean in which the EJB is injected by means of the @EJB annotation. Its addCustomer method is typically bound to some UI component, like a button. Contrary to the EJB, the backing bean does not contain any business logic or persistence code, but delegates such concerns to the EJB. The backing bean does know about a particular presentation, of which the EJB had no knowledge.Types of Enterprise BeansAn EJB container holds two major types of beans: Session Beans [3] that can be either "Stateful", "Stateless" or "Singleton" and can be accessed via either a Local (same JVM) or Remote (different JVM) interface or directly without an interface,[4] in which case local semantics apply. All session beans support asynchronous execution[5] for all views (local/remote/no-interface). Message Driven Beans (MDBs, also known as Message Beans). MDBs also support asynchronous execution, but via a messaging paradigm.Session beansStateful Session BeansStateful Session Beans[6] are business objects having state: that is, they keep track of which calling client they are dealing with throughout a session and thus access to the bean instance is strictly limited to only one client at a time.[7] If concurrent access to a single bean is attempted anyway the container serializes those requests, but via the @AccessTimeout annotation the container can instead throw an exception.[8] Stateful session beans' state may be persisted (passivated) automatically by the container to free up memory after the client hasn't accessed the bean for some time. The JPA extended persistence context is explicitly supported by Stateful Session Beans.[9]Examples Checking out in a web store might be handled by a stateful session bean that would use its state to keep track of where the customer is in the checkout process, possibly holding locks on the items the customer is purchasing (from a system architecture's point of view, it would be less ideal to have the client manage those locks).Stateless Session BeansStateless Session Beans[10] are business objects that do not have state associated with them. However, access to a single bean instance is still limited to only one client at a time, concurrent access to the bean is prohibited.[7] If concurrent access to a single bean is attempted, the container simply routes each request to a different instance.[11] This makes a stateless session bean automatically thread-safe. Instance variables can be used during a single method call from a client to the bean, but the contents of those instance variables are not guaranteed to be preserved across different client method calls. Instances of Stateless Session beans are typically pooled. If a second client accesses a specific bean right after a method call on it made by a first client has finished, it might get the same instance. The lack of overhead to maintain a conversation with the calling client makes them less resource-intensive than stateful beans.Examples Sending an e-mail to customer support might be handled by a stateless bean, since this is a one-off operation and not part of a multi-step process. A user of a website clicking on a "keep me informed of future updates" box may trigger a call to an asynchronous method of the session bean to add the user to a list in the company's database (this call is asynchronous because the user does not need to wait to be informed of its success or failure). Fetching multiple independent pieces of data for a website, like a list of products and the history of the current user might be handled by asynchronous methods of a session bean as well (these calls are asynchronous because they can execute in parallel that way, which potentially increases performance). In this case, the asynchronous method will return a Future instance.Singleton Session BeansSingleton Session Beans[12][13] are business objects having a global shared state within a JVM. Concurrent access to the one and only bean instance can be controlled by the container (Container-managed concurrency, CMC) or by the bean itself (Bean-managed concurrency, BMC). CMC can be tuned using the @Lock annotation, that designates whether a read lock or a write lock will be used for a method call. Additionally, Singleton Session Beans can explicitly request to be instantiated when the EJB container starts up, using the @Startup annotation.Examples Loading a global daily price list that will be the same for every user might be done with a singleton session bean, since this will prevent the application having to do the same query to a database over and over again.Message driven beansMessage Driven Beans[14] are business objects whose execution is triggered by messages instead of by method calls. The Message Driven Bean is used among others to provide a high level ease-of-use abstraction for the lower level JMS (Java Message Service) specification. It may subscribe to JMS message queues or message topics, which typically happens via the activationConfig attribute of the @MessageDriven annotation. They were added in EJB to allow event-driven processing. Unlike session beans, an MDB does not have a client view (Local/Remote/No-interface), i.e. clients cannot look-up an MDB instance. An MDB just listens for any incoming message on, for example, a JMS queue or topic and processes them automatically. Only JMS support is required by the Java EE spec,[15] but Message Driven Beans can support other messaging protocols.[16][17] Such protocols may be asynchronous but can also be synchronous. Since session beans can also be synchronous or asynchronous, the prime difference between session- and message driven beans is not the synchronicity, but the difference between (object oriented) method calling and messaging.Examples Sending a configuration update to multiple nodes might be done by sending a JMS message to a 'message topic' and could be handled by a Message Driven Bean listening to this topic (the message paradigm is used here since the sender does not need to know the number of consumers, their location, or even their exact type). Submitting a job to a work cluster might be done by sending a JMS message to a 'message queue' and could also be handled by a Message Driven Bean, but this time listening to a queue (the message paradigm and the queue is used, since the sender doesn't have to care which worker executes the job, but it does need assurance that a job is only executed once). Processing timing events from the Quartz scheduler can be handled by a Message Driven Bean; when a Quartz trigger fires, the MDB is automatically invoked. Since Java EE doesn't know about Quartz by default, a JCA resource adapter would be needed and the MDB would be annotated with a reference to this.[18]Entity beans (deprecated)Previous versions of EJB also used a type of bean known as an Entity Bean. These were distributed objects having persistent state. Beans in which their container managed the persistent state were said to be using Container-Managed Persistence (CMP), whereas beans that managed their own state were said to be using Bean-Managed Persistence (BMP). In EJB 3.0, Entity Beans were replaced by the Java Persistence API, which was completely separated to its own specification to allow the EJB specification to focus only on the "core session bean and message-driven bean component models and their client API".[19] Entity Beans were still available in EJB 3.1 for backwards compatibility, but they had been officially proposed to be removed from the specification (via a process called "pruning").[20] In EJB 3.2 Entity Beans have indeed been removed (officially, "made optional"). [21]Other types of Enterprise Beans had been proposed. For instance, Enterprise Media Beans (JSR 86) would address the integration of multimedia objects in Java EE applications.ExecutionEJBs are deployed in an EJB container, typically but not necessarily, within an application server. The specification describes how an EJB interacts with its container and how client code interacts with the container/EJB combination. The EJB classes used by applications are included in the javax.ejb package. (The javax.ejb.spi package is a service provider interface used only by EJB container implementations.)Clients of EJB beans do not instantiate those beans directly via Java's new operator, but instead have to obtain a reference via the EJB container. This reference is then not a reference to the implementation bean itself, but to a proxy, which either dynamically implements the local or remote business interface that the client requested or dynamically implements a sub-type of the actual bean. The proxy can then be directly cast to the interface or bean. A client is said to have a 'view' on the EJB, and the local interface, remote interface and bean type itself respectively correspond with the local view, remote view and no-interface view.This proxy is needed in order to give the EJB container the opportunity to transparently provide cross-cutting (AOP-like) services to a bean like transactions, security, interceptions, injections, remoting, etc.E.g. a client invokes a method on a proxy, which will then first start a transaction with the help of the EJB container and then call the actual bean method. When the actual bean method returns, the proxy ends the transaction (i.e. by committing it or doing a rollback) and transfers control back to the client.TransactionsEJB containers must support both container managed ACID transactions and bean managed transactions.[22]Container-managed transactions (CMT) are by default active for calls to session beans. That is, no explicit configuration is needed. This behavior may be declaratively tuned by the bean via annotations and if needed such configuration can later be overridden in the deployment descriptor. Tuning includes switching off transactions for the whole bean or specific methods, or requesting alternative strategies for transaction propagation and starting or joining a transaction. Such strategies mainly deal with what should happen if a transaction is or isn't already in progress at the time the bean is called. The following variations are supported:[23][24]Declarative Transactions Management Types

TypeExplanation

MANDATORYIf the client has not started a transaction, an exception is thrown. Otherwise the client's transaction is used.

REQUIREDIf the client has started a transaction, it is used. Otherwise a new transaction is started. (this is the default when no explicit type has been specified)

REQUIRES_NEWIf the client has started a transaction, it is suspended. A new transaction is always started.

SUPPORTSIf the client has started a transaction, it is used. Otherwise, no transaction is used.

NOT_SUPPORTEDIf the client has started a transaction, it is suspended. No new transaction is started.

NEVERIf the client has started a transaction, an exception is thrown. No new transaction is started.

Alternatively, the bean can also declare via an annotation that it wants to handle transactions programmatically via the JTA API. This mode of operation is called Bean Managed Transactions (BMT), since the bean itself handles the transaction instead of the container.[25]EventsJMS (Java Message Service) is used to send messages from beans to clients, to let clients receive asynchronous messages from these beans. MDBs can be used to receive messages from clients asynchronously using either a JMS Queue or a Topic.Naming and directory servicesAs an alternative to injection, clients of an EJB can obtain a reference to the session bean's proxy object (the EJB stub) using Java Naming and Directory Interface (JNDI). This alternative can be used in cases where injection is not available, such as non-managed beans or standalone remote Java SE clients, or when it's necessary to programmatically determine which bean to obtain.JNDI names for EJB session beans are assigned by the EJB container via the following scheme:[26][27][28]JNDI names

ScopeName pattern

Globaljava:global[/]//[!]

Applicationjava:app//[!]

Modulejava:module/[!]

(entries in square brackets denote optional parts)A single bean can be obtained by any name matching the above patterns, depending on the 'location' of the client. Clients in the same module as the required bean can use the module scope and larger scopes, clients in the same application as the required bean can use the app scope and higher, etc.E.g. code running in the same module as the CustomerService bean (as given by the example shown earlier in this article) could use the following code to obtain a (local) reference to it:CustomerServiceLocal customerService = (CustomerServiceLocal) new InitialContext().lookup("java:module/CustomerService");Remoting/distributed executionEJB session beans have elaborate support for remoting.For communication with a client that's also written in the Java programming language a session bean can expose a remote-view via an @Remote annotated interface.[29] This allows those beans to be called from clients in other JVMs which themselves may be located on other (remote) systems. From the point of view of the EJB container, any code in another JVM is remote.Stateless- and Singleton session beans may also expose a "web service client view" for remote communication via WSDL and SOAP or plain XML.[30][31][32] This follows the JAX-RPC and JAX-WS specifications. JAX-RPC support however is proposed for future removal.[20] To support JAX-WS, the session bean is annotated with the @WebService annotation, and methods that are to be exposed remotely with the @WebMethod annotation.Although the EJB specification does not mention exposure as RESTful web services in any way and has no explicit support for this form of communication, the JAX-RS specification does explicitly support EJB.[33] Following the JAX-RS spec, Stateless- and Singleton session beans can be root resources via the @Path annotation and EJB business methods can be mapped to resource methods via the @GET, @PUT, @POST and @DELETE annotations. This however does not count as a "web service client view", which is used exclusively for JAX-WS and JAX-RPC.Communication via web services is typical for clients not written in the Java programming language, but is also convenient for Java clients who have trouble reaching the EJB server via a firewall. Additionally, web service based communication can be used by Java clients to circumvent the arcane and ill-defined requirements for the so-called "client-libraries"; a set of jar files that a Java client must have on its class-path in order to communicate with the remote EJB server. These client-libraries potentially conflict with libraries the client may already have (for instance, if the client itself is also a full Java EE server) and such a conflict is deemed to be a very hard or impossible to resolve.[34]Message Driven Beans have no specific support for remoting, but being listeners to end-points (e.g. JMS queues) they are implicitly remote components by virtue of the properties of whatever type of end-point they are listening to.SecurityThe EJB Container is responsible for ensuring the client code has sufficient access rights to an EJB.[35] Security aspects can be declaratively applied to an EJB bean via annotations.[36]LegacyHome interfaces and required business interfaceWith EJB 2.1 and earlier, each EJB had to provide a Java implementation class and two Java interfaces. The EJB container created instances of the Java implementation class to provide the EJB implementation. The Java interfaces were used by client code of the EJB.The two interfaces, referred to as the Home and the Remote interface, specified the signatures of the EJB's remote methods. The methods were split into two groups:Class methodsNot tied to a specific instance, such as those used to create an EJB instance (factory method) or to find an existing entity EJB (see EJB Types, above). These were declared by the Home interface.Instance methodsThese are methods tied to a specific instance. They are placed in the Remote interface.

Required deployment descriptorWith EJB 2.1 and earlier, the EJB specification required a deployment descriptor to be present. This was needed to implement a mechanism that allowed EJBs to be deployed in a consistent manner regardless of the specific EJB platform that was chosen. Information about how the bean should be deployed (such as the name of the home or remote interfaces, whether and how to store the bean in a database, etc.) had to be specified in the deployment descriptor.The deployment descriptor is an XML document having an entry for each EJB to be deployed. This XML document specifies the following information for each EJB: Name of the Home interface Java class for the Bean (business object) Java interface for the Home interface Java interface for the business object Persistent store (only for Entity Beans) Security roles and permissions Stateful or Stateless (for Session Beans)Old EJB containers from many vendors required more deployment information than that in the EJB specification. They would require the additional information as separate XML files, or some other configuration file format. An EJB platform vendor generally provided their own tools that would read this deployment descriptor, and possibly generated a set of classes that would implement the now deprecated Home and Remote interfaces.Since EJB 3.0 (JSR 220), the XML descriptor is replaced by Java annotations set in the Enterprise Bean implementation (at source level), although it is still possible to use an XML descriptor instead of (or in addition to) the annotations. If an XML descriptor and annotations are both applied to the same attribute within an Enterprise Bean, the XML definition overrides the corresponding source-level annotation, although some XML elements can also be additive (e.g., an activation-config-property in XML with a different name than already defined via an @ActivationConfigProperty annotation will be added instead of replacing all existing properties).Container variationsStarting with EJB 3.1, the EJB specification defines two variants of the EJB container; a full version and a limited version. The limited version adheres to a proper subset of the specification called EJB 3.1 Lite [37][38] and is part of Java EE 6's web profile[39] (which is itself a subset of the full Java EE 6 specification).EJB 3.1 Lite excludes support for the following features:[40] Remote interfaces RMI-IIOP Interoperability JAX-WS Web Service Endpoints EJB Timer Service (@Schedule, @Timeout) Asynchronous session bean invocations (@Asynchronous) Message-driven beansEJB 3.2 Lite excludes less features. Particularly it no longer excludes @Asynchronous and @Schedule/@Timeout, but for @Schedule it does not support the "persistent" attribute that full EJB 3.2 does support. The complete excluded list for EJB 3.2 Lite is: Remote interfaces RMI-IIOP Interoperability JAX-WS Web Service Endpoints Persistent timers ("persistent" attribute on @Schedule) Message-driven beansVersion historyEJB 3.2, final release (2013-05-28)JSR 345. Enterprise JavaBeans 3.2 was a relatively minor release that mainly contained specification clarifications and lifted some restrictions that were imposed by the spec but overtime appeared to serve no real purpose. A few existing full EJB features were also demanded to be in EJB 3 lite and functionality that was proposed to be pruned in EJB 3.1 was indeed pruned (made optional). [41] [42]The following features were added: Passivation of a stateful session bean can be deactivated via attribute on @Stateful annotation (passivationCapable = false) TimerService can retrieve all active timers in the same EJB module (could previously only retrieve timers for the bean in which the TimerService was called) Lifecycle methods (e.g. @PostConstruct) can optionally be transactional for stateful session beans using the existing @TransactionAttribute annotation Autocloseable interface implemented by embeddable container

15. a) Write note about multimedia databases and its principles in detail A multimedia database is a database that hosts one or more primary media file types such as .txt (documents), .jpg (images), .swf (videos), .mp3 (audio), etc. And loosely fall into three main categories: Static media (time-independent, i.e. images and handwriting) Dynamic media (time-dependent, i.e. video and sound bytes) Dimensional media (i.e. 3D games or computer-aided drafting programs- CAD)All primary media files are stored in binary strings of zeros and ones, and are encoded according to file type.The term "data" is typically referenced from the computer point of view, whereas the term "multimedia" is referenced from the user point of view.Types of Multimedia DatabasesThere are numerous different types of multimedia databases, including: The Authentication Multimedia Database (also known as a Verification Multimedia Database, i.e. retina scanning), is a 1:1 data comparison The Identification Multimedia Database is a data comparison of one-to-many (i.e. passwords and personal identification numbers A newly-emerging type of multimedia database, is the Biometrics Multimedia Database; which specializes in automatic human verification based on the algorithms of their behavioral or physiological profile.This method of identification is superior to traditional multimedia database methods requiring the typical input of personal identification numbers and passwords-Due to the fact that the person being identified does not need to be physically present, where the identification check is taking place.This removes the need for the person being scanned to remember a PIN or password. Fingerprint identification technology is also based on this type of multimedia database.Difficulties Involved with Multimedia DatabasesThe difficulty of making these different types of multimedia databases readily accessible to humans is: The tremendous amount of bandwidth they consume; Creating Globally-accepted data-handling platforms, such as Joomla, and the special considerations that these new multimedia database structures require. Creating a Globally-accepted operating system, including applicable storage and resource management programs need to accommodate the vast Global multimedia information hunger. Multimedia databases need to take into accommodate various human interfaces to handle 3D-interactive objects, in an logically-perceived manner (i.e. SecondLife.com). Accommodating the vast resources required to utilize artificial intelligence to it's fullest potential- including computer sight and sound analysis methods. The historic relational databases (i.e the Binary Large Objects BLOBs- developed for SQL databases to store multimedia data) do not conveniently support content-based searches for multimedia content.This is due to the relational database not being able to recognize the internal structure of a Binary Large Object and therefore internal multimedia data components cannot be retrievedBasically, a relational database is an "everything or nothing" structure- with files retrieved and stored as a whole, which makes a relational database completely inefficient for making multimedia data easily accessible to humans.In order to effectively accommodate multimedia data, a database management system, such as an Object Oriented Database (OODB) or Object Relational Database Management System (ORDBMS).Examples of Object Relational Database Management Systems include Odaptor (HP): UniSQL, ODB-II, and Illustra.The flip-side of the coin, is that unlike non-multimedia data stored in relational databases, multimedia data cannot be easily indexed, retrieved or classified, except by way of social bookmarking and ranking-rating, by actual humans.This is made possible by metadata retrieval methods, commonly referred to as tags, and tagging. This is why you can search for dogs, as an example, and a picture comes up based on your text search tem.This is also referred to a schematic mode. Whereas doing a search with a picture of a dog to locate other dog pictures is referred to as paradigmatic mode.However, metadata retrieval, search, and identify methods severely lack in being able to properly define uniform space and texture descriptions, such as the spatial relationships between 3D objects, etc.The Content-Based Retrieval multimedia database search method (CBR), however, is specifically based on these types of searches. In other words, if you were to search an image or sub-image; you would then be shown other images or sub-images that related in some way to your the particular search, by way of color ratio or pattern, etc.15b) Explain the packaging structure of an EJB application.Packaging EJB 3 ApplicationsThe real success of Java EE applications lies in assembly and deployment, as this is the key to delivering on Java's promise of write once, run anywhere (WORA). If you fail to fully grasp this step, your application may not realize this level of portability.Java platform roles: it's all about juggling hats

The Java EE platform defines different roles and responsibilities relating to development, assembly, and deployment of Java EE applications. In this article we are mainly interested in the Developer, Assembler, and Deployer roles, but we introduce you to all the roles so that you can be familiar with them. The roles defined by the specifications are Enterprise Bean Provider Application Assembler Deployer EJB Server Provider EJB Container Provider Persistence Provider System AdministratorThe database administrator is not one of the defined Java EE roles. The database administrator may not even understand a line of Java code. However, the importance of this role cannot be overlooked, especially in large corporations where relational databases are outside the control of the application developers. Developers, Assemblers, and Deployers may need to work with the DBAs in order to successfully build and release Java EE applications.

A typical application has a handful of Java classes, and maintenance can be a nightmare if you are shipping your applications from one environment to another. To simplify maintenance you can create a Java archive (JAR) file. Typically, a JAR file is a file in zip format that contains classes. However, enterprise Java applications are packaged as specialized versions of JAR filesEAR, WAR, and EJB-JAR modulesbefore they can be deployed to a Java EE.compliant application server.In this article we begin with a discussion of application packaging and deployment. The article also provides critical information on class loading, so that you can appreciate why the archives are packaged as they are. This is intended to provide you a better understanding of the packaging requirements for EJB that include entities. We explain the need for deployment descriptors, and look at how to use them. Finally, we look at a persistence unit and how to per form object-relational (O/R) mapping using XML.Packaging your applicationsA typical enterprise Java application may contain several Java classes of different types, such as EJBs, servlets, JavaServer Faces (JSF) classes, as well as static files such as JSPs and HTML files. EJBs run in the EJB container whereas web applications such as servlets and JSF managed beans run in the web container. To run your application you have to make it available to the Java EE application server. This is known as deployment. Since EJB is a core part of the Java EE specification, you have to follow the Java EE standard for deployment.To understand packaging, you must consider how it fits into the bigger picture of Java EE packaging and know what constitutes a complete enterprise Java application. Up to this point we have focused on using EJB components such as session beans and MDBs to build business logic and JPA entities to implement your persistence code. However, your application will not be complete without a presentation tier that accesses the business logic you built with EJBs. For example, the EJBs we built for ActionBazaar do not make sense unless we have a client application accessing them. Most likely, you've used standard technologies such as JSP or JSF to build the web tier of your applications. These web applications, together with EJBs, constitute an enterprise application that you can deploy to an application server.To deploy and run an application, you have to package the complete application togetherthe web module and EJBsand deploy to an application server. Usually you will group similar pieces of the application together in modules. Java EE defines a standard way of packaging these modules in JAR files, and specifies the formats for these JARs. One of the advantages of having these formats defined as part of the specification is that they are portable across application servers.Table 1 lists the archives or modules supported by Java EE 5 and their contents. Note that each archive type is used for packaging a specific type of module, such as EJB or web. For instance, a WAR is used to package a web-tier application module, and the EAR file is intended to be the |ber archive containing all the other archives so that in the end, you're only deploying one file. The application server will scan the contents of the EAR and deploy it. We discuss how an EAR is loaded by the server in section 1.2.Table 1 Enterprise Java applications need to be assembled into specific types of JAR files before they can be deployed to an application server. These are the available module types as specified by Java EE.TypeDescriptionDescriptorContents

CARClient application archivesapplication-client .xmlThick Java client for EJBs

EAREnterprise application archiveapplication.xmlOther Java EE modules such as EJB-JARs.

EJB-JAREJB Java archiveejb-jar.xmlSession beans, message-driven beans, and optionally entities. Needs a persistence.xml if entities are packaged.

RARResource adapter archivesra.xmlResource adapters.

WARWeb application archivesweb.xmlWeb application artifacts such as servlets, JSPs, JSF, static files, etc. Entities can also be packaged in this module. Needs a persistence.xml if entities are packaged.

To create these files, you can use the jar utility that comes with JDK. The final step is to assemble all the JAR files into one EAR file for deployment. In 3.1 we show you a build script that creates a JAR file. Each of these JAR types contains an optional deployment descriptor that describes the archive. As we have been discussing throughout this article, you can use metadata annotations instead of a deployment descriptor.In this article, we focus primarily on the EAR file and the EJB-JAR file, which contains the session and message-driven beans, as well as entities.It's worth mentioning that entities can be packaged in most archive types. For example, the ability to package entities in WARs allows you to use the EJB 3 JPA in simple web applications or with lightweight frameworks such as Spring. Note that entities are not supported in RAR modules. This statement, however, begs the question of why Java does not have a different archive type to package EJB 3 entities, just as JBoss has the Hibernate Archive (HAR) to package persistence objects with Hibernate's O/R framework.You may know the answer to this question if you have followed the evolution of the EJB 3 specification. For those who haven't, we now regale you with Tales from the Expert Group (cue spooky music)...During the evolution of the EJB 3 Public Draft, the PAR (Persistence Archive) was introduced, which mysteriously vanished in the Proposed Final Draft. A huge, emotional battle was fought in the EJB and Java EE expert groups over whether to introduce a module type for a persistence module at the Java EE level, and suggestions were sought from the community at large, as well as from various developer forums. Many developers think a separate persistence module is a bad idea because entities are supported both outside and inside the container. Considering that persistence is inherently a part of any enterprise application, it makes sense to support packaging entities with most module types, instead of introducing a new module type specialized for packaging entities.Now that you know what modules are supported and a little about how they were arrived at, shall we take a quick peek under the hood of an EAR module?Dissecting the EAR fileTo understand how deployment works, let's take a closer look at the EAR file, the top-level archive file that contains other Java EE archives when it is deployed to the application server. For instance, the ActionBazaar application contains an EJB module, a web module, a JAR containing helper classes, and an application client module. The file structure of the EAR file that ActionBazaar uses looks like this:META-INF/application.xmlactionBazaar-ejb. jaractionBazaar .waractionBazaar-client.jar

lib/actionBazaar-commons.jarapplication .xml is the deployment descriptor that describes the standard Java EE modules packaged in each EAR file. The contents of application.xml look something like listing 1.Listing 1: Deployment descriptor for the ActionBazaar EAR module

Click here for a larger image. If you review the EAR file descriptor in listing 1, you'll see that it explicitly identifies each of the artifacts as a specific type of module. When you deploy this EAR to an application server, the application server uses the information in the deployment descriptor to deploy each of the module types.Java EE 5 made the deployment descriptor optional, even in the EAR. This is a departure from previous versions of Java EE, where it was mandatory. The Java EE 5.0.compliant application servers deploy by performing automatic detection based on a standard naming convention or reading the content of archives; see http://java.sun.com/blueprints/code/namingconventions.html

16. a) How to connect a database into Java application? Explain it with simple application Lesson: JDBC IntroductionThe JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.JDBC helps you to write Java applications that manage these three programming activities:1. Connect to a data source, like a database2. Send queries and update statements to the database3. Retrieve and process the results received from the database in answer to your queryThe following simple code fragment gives a simple example of these three steps:public void connectToAndQueryDatabase(String username, String password) {

Connection con = DriverManager.getConnection( "jdbc:myDriver:myDatabase", username, password);

Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");

while (rs.next()) { int x = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); }}This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It's that simple.JDBC Product ComponentsJDBC includes four components:1. The JDBC API The JDBC API provides programmatic access to relational data from the Java programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment.The JDBC API is part of the Java platform, which includes the Java Standard Edition (Java SE ) and the Java Enterprise Edition (Java EE). The JDBC 4.0 API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.2. JDBC Driver Manager The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple.The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface (JNDI) naming service to establish a connection with a data source. You can use either connecting mechanism, but using a DataSource object is recommended whenever possible.3. JDBC Test Suite The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.4. JDBC-ODBC Bridge The Java Software bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC driver is most appropriate on a corporate network where client installations are not a major problem, or for application server code written in Java in a three-tier architecture.This Trail uses the first two of these these four JDBC components to connect to a database and then build a java program that uses SQL commands to communicate with a test Relational Database. The last two components are used in specialized environments to test web applications, or to communicate with ODBC-aware DBMSs.JDBC ArchitectureTwo-tier and Three-tier Processing ModelsThe JDBC API supports both two-tier and three-tier processing models for database access.Figure 1: Two-tier Architecture for Data Access.

In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet.In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.Figure 2: Three-tier Architecture for Data Access.

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it