JAX-WS Web Service Fundamentals

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is the purpose of the sun-jaxws.xml file in a JAX-WS web service?

  • It specifies the implementation class for the web service.
  • It maps the web service's methods to their corresponding operations.
  • It configures the web service's security settings.
  • It defines the endpoint for the web service. (correct)

Which annotation is used to define a method in a JAX-WS web service interface?

  • `@Service`
  • `@WebService`
  • `@Endpoint`
  • `@WebMethod` (correct)

What is the role of the WSServlet class in a JAX-WS web service deployment?

  • It determines the web service's endpoint URL.
  • It provides the entry point for the web service. (correct)
  • It marshals and unmarshals SOAP messages.
  • It handles the communication between the client and the server.

In a JAX-WS RPC style web service, how is the communication between the client and the server typically performed?

<p>Via a service port defined by a QName. (B)</p> Signup and view all the answers

Which of the following is a benefit of using the JAX-WS RPC style for web services?

<p>It offers a more straightforward implementation compared to document style. (D)</p> Signup and view all the answers

What is the purpose of marshalling in the context of JAX-WS web services?

<p>It converts Java objects to XML representations for transmission. (D)</p> Signup and view all the answers

What is the role of the @WebService annotation in a JAX-WS web service?

<p>It marks a class as a web service implementation. (A)</p> Signup and view all the answers

Which of the following options is a reference implementation of JAX-WS?

<p>Glassfish Metro (B)</p> Signup and view all the answers

What is the primary function of the Endpoint.publish() method in the JAX-WS API?

<p>It deploys a web service implementation to a specific URL. (C)</p> Signup and view all the answers

How can you access the WSDL document for a deployed JAX-WS web service using the RPC style?

<p>By appending '?wsdl' to the web service's endpoint URL. (C)</p> Signup and view all the answers

What is the primary purpose of JAXB in the given example?

<p>To convert Java objects to XML and vice versa (A)</p> Signup and view all the answers

Which HTTP method is used to create a new resource according to the provided web services information?

<p>POST (A)</p> Signup and view all the answers

What is the purpose of the JAXBContext in the context of the given JAXB example?

<p>To provide an entry point for JAXB functionalities (B)</p> Signup and view all the answers

In the context of web services, what does SOAP stand for?

<p>Simple Object Access Protocol (C)</p> Signup and view all the answers

What is an envelope structure in SOAP?

<p>The wrapping or framing for a SOAP message (B)</p> Signup and view all the answers

What kind of data communication does web services typically utilize?

<p>XML-based messages (C)</p> Signup and view all the answers

What does the marshalling process in JAXB do specifically?

<p>It transforms a Java object into an XML representation (B)</p> Signup and view all the answers

Which approach does JAX-WS extend according to the information provided?

<p>JAX-RPC 1.0 (C)</p> Signup and view all the answers

What is the primary function of the SOAPHandler interface?

<p>To handle messages and determine whether the chain may continue. (D)</p> Signup and view all the answers

Which annotation is used to specify the XML file for handler mapping in a JAX-WS service?

<p>@HandlerChain (C)</p> Signup and view all the answers

What are the main components of RMI in Java?

<p>Remote method invocation and client/server architecture. (D)</p> Signup and view all the answers

What is the purpose of the Java Remote Method Protocol (JRMP)?

<p>To define a proprietary protocol for remote method calls. (D)</p> Signup and view all the answers

Which of the following statements about IIOP is true?

<p>IIOP is CORBA’s communication protocol that operates over TCP/IP. (D)</p> Signup and view all the answers

What is a key benefit of using RMI in distributed Java applications?

<p>It enables separate JVMs to call methods on each other seamlessly. (C)</p> Signup and view all the answers

What does the @WebMethod annotation signify in a JAX-WS service?

<p>The method can be accessed as a web service operation. (C)</p> Signup and view all the answers

Which protocol did RMI adopt later for enhanced interoperability?

<p>IIOP (B)</p> Signup and view all the answers

In what context is the MacAddressValidatorHandler referenced?

<p>As an example of a server-side handler. (B)</p> Signup and view all the answers

What is the default setting for the RMI property java.rmi.server.useCodebaseOnly as of JDK 7 Update 21?

<p>True (C)</p> Signup and view all the answers

What does the RMI Naming method 'Lookup' do?

<p>Returns a reference to a remote object (A)</p> Signup and view all the answers

In the provided server implementation, which class is used to allow a remote object to be accessed?

<p>UnicastRemoteObject (D)</p> Signup and view all the answers

What is the primary function of the 'Rebind' method in RMI naming?

<p>It replaces an existing binding with a new one (A)</p> Signup and view all the answers

How do clients connect to the RMI registry in the provided client implementation example?

<p>Using an IP address and port (B)</p> Signup and view all the answers

Which method is used to initialize the RMI security manager?

<p>System.setSecurityManager() (B)</p> Signup and view all the answers

What does the exception RemoteException signify in RMI communication?

<p>Issues with networking or remote communication (A)</p> Signup and view all the answers

What is required for an object to be exported for RMI access?

<p>It must implement the Remote interface (B)</p> Signup and view all the answers

What role does the 'Shared proxy object' play in RMI?

<p>It acts as a reference to remote objects (B)</p> Signup and view all the answers

In the context of server callbacks in RMI, what is essential for the communication object?

<p>It must extend the java.rmi.Remote interface (C)</p> Signup and view all the answers

What must be enabled to activate client-side validations?

<p>Client-side validation settings in web.xml (A)</p> Signup and view all the answers

Which method is required to implement custom client-side validation?

<p>validate() (A)</p> Signup and view all the answers

Which annotation is used to specify the size constraints for a name property in a Bean?

<p>@Size (A)</p> Signup and view all the answers

In which situation are messages with FacesMessage.Severity typically used?

<p>To indicate errors in forms (A)</p> Signup and view all the answers

What feature does a Panel provide as a container for other widgets?

<p>Dynamic event handling and user interaction (B)</p> Signup and view all the answers

What functionalities does a Panel grid support?

<p>Colspan and rowspan support (B)</p> Signup and view all the answers

Which component is typically used to display error messages in the top right corner of the interface?

<p>Growl (C)</p> Signup and view all the answers

What is a characteristic of AJAX processing in forms?

<p>It allows for partial processing and updates. (C)</p> Signup and view all the answers

What is the purpose of the @Asynchronous annotation in the given MathSessionBean code?

<p>It marks the method as capable of performing asynchronous operations, returning a <code>Future</code> object representing the eventual result. (A), It instructs the container to execute the method in a separate thread pool, improving performance by parallelizing operations. (B), It signifies that the method will be invoked asynchronously, allowing the caller to continue execution while the method completes. (C)</p> Signup and view all the answers

What does the isDone() method in the code snippet Future r = mathBean.compute(20, 11); while (!r.isDone()) {...} Integer i = r.get(); check for?

<p>If the asynchronous computation has completed successfully or encountered an error. (D)</p> Signup and view all the answers

Which transaction attribute ensures that a new transaction is always created when a method annotated with it is invoked?

<p>REQUIRES_NEW (B)</p> Signup and view all the answers

What is the main difference between Container-managed and Bean-managed persistence in EJB?

<p>Container-managed relies on JDBC calls, while Bean-managed allows for more flexibility using other data sources like LDAP. (A)</p> Signup and view all the answers

Which of the following EJB components is NOT supported by EJB Lite?

<p>Message-Driven Beans (C)</p> Signup and view all the answers

Which of these features is NOT offered by an Embeddable Container for EJBs?

<p>Enhanced scalability compared to traditional EJB deployments. (B)</p> Signup and view all the answers

What is the purpose of the UserTransaction interface in the Bean-managed persistence model?

<p>To initiate, commit, and rollback transactions manually within the EJB. (D)</p> Signup and view all the answers

Which of the following scenarios is best suited for using an EJB Lite implementation?

<p>A standalone batch processing application running within a single JVM. (A), A lightweight web application with a simple data model and minimal persistence requirements. (C)</p> Signup and view all the answers

Flashcards

JAX-WS

A Java API that allows developers to build web services using XML.

XML

A standard for exchanging structured data over the internet, often used in web services.

SOAP

A message-based protocol used for exchanging information between web services.

Web Services

A set of standards defining how to create and use web services.

Signup and view all the flashcards

GET

A request method used to retrieve data from a web service.

Signup and view all the flashcards

POST

A request method used to update an existing resource or create a new one in a web service.

Signup and view all the flashcards

PUT

A request method used to create a new resource or modify an existing one in a web service.

Signup and view all the flashcards

DELETE

A request method used to delete a resource from a web service.

Signup and view all the flashcards

SOAP Header

A part of a SOAP message containing header information about the message itself. It might include things like security credentials or routing instructions.

Signup and view all the flashcards

SOAP Body

The main part of a SOAP message where the actual message or data is enclosed. It contains the call or response information.

Signup and view all the flashcards

SOAP Fault

A section of a SOAP message that carries error information and status details. It indicates problems encountered during processing.

Signup and view all the flashcards

Web Service Interface

An interface on a web service representing the methods available for clients to call remotely. Think of it as a contract defining the service's capabilities.

Signup and view all the flashcards

Web Service Proxy

A software component created on the client side that represents the web service interface and acts as a proxy for communication with the server. This allows the client to call the server methods locally.

Signup and view all the flashcards

Document Style Web Service Endpoint

A type of web service endpoint that transmits data in the form of XML documents.

Signup and view all the flashcards

RPC Style Web Service Endpoint

A type of web service endpoint that uses a remote procedure call (RPC) style to transmit data, where the server acts like a remote function that can be called directly.

Signup and view all the flashcards

WSDL (Web Service Definition Language)

A common method for specifying the communication details of a web service, including the supported operations, message formats, and communication protocols.

Signup and view all the flashcards

Server Handler

A server-side component that handles incoming web service requests and processes them according to the defined logic.

Signup and view all the flashcards

SOAP Handler

A mechanism that allows developers to intercept and process web service requests before they reach the actual web service method.

Signup and view all the flashcards

Handler Configuration

A configuration file that defines the mapping between SOAP handlers and web service methods.

Signup and view all the flashcards

Handler Mapping

The process of associating SOAP handlers with specific web service methods, determining which handlers are invoked for each request.

Signup and view all the flashcards

SOAPHandler interface

An interface that defines the contract for SOAP handlers, outlining the methods they must implement for processing web service messages.

Signup and view all the flashcards

SOAPMessageContext

A context object that provides information about the currently processed web service message, including headers, body, and other relevant details.

Signup and view all the flashcards

Remote Method Invocation (RMI)

A Java API that allows developers to communicate between processes on different machines using objects.

Signup and view all the flashcards

java.rmi.server.useCodebaseOnly

A property that controls whether classes are loaded from a network location or only from preconfigured locations. When set to true, classes are loaded only from local sources, like the classpath.

Signup and view all the flashcards

Naming

A static class in Java RMI that provides methods for binding and looking up remote objects in a registry.

Signup and view all the flashcards

LocateRegistry

A static class that allows you to create and manage a registry for remote objects.

Signup and view all the flashcards

UnicastRemoteObject

A base class for remote objects in Java RMI. It allows objects to be exported and made accessible through the registry.

Signup and view all the flashcards

Shared Proxy Object (Interface)

A shared interface used by both the server and the client to define methods that can be invoked remotely.

Signup and view all the flashcards

Shared Proxy Object (Implementation)

An implementation of the shared proxy interface. The actual logic for remote methods resides within the implementation.

Signup and view all the flashcards

Remote Service

An object that represents a remote service. It resides on the server and is made available through the registry.

Signup and view all the flashcards

RPC (Remote Procedure Call)

A remote call made from a client to a remote service residing on a server.

Signup and view all the flashcards

Server Callback

A mechanism that allows a server to initiate communication back to a client. It requires the client object to implement the proxy interface and be exported.

Signup and view all the flashcards

@Asynchronous Annotation

An annotation that marks a method as being executed asynchronously, meaning it will run in a separate thread.

Signup and view all the flashcards

Future Object

A special kind of object in Java that represents the result of an asynchronous operation. It acts as a placeholder for the actual result, which may not be available immediately.

Signup and view all the flashcards

Container-managed Persistence

A mechanism in EJB where the container manages the persistence of data, typically using JDBC calls. Developers don't need to handle the low-level details of database interactions.

Signup and view all the flashcards

@TransactionAttribute

An attribute defining how transactions are handled within a method. This dictates whether the method will use existing transactions, create new ones, or operate outside of transactions.

Signup and view all the flashcards

REQUIRES NEW Transaction Attribute

A type of transaction attribute where a new transaction will be created if one is not already running. If a transaction is already running, it will be suspended while the method executes in its own transaction.

Signup and view all the flashcards

MANDATORY Transaction Attribute

A type of transaction attribute where the method can only be executed within an existing transaction. If no transaction is running, an error will be thrown.

Signup and view all the flashcards

Bean-managed Persistence

The programmer is responsible for managing data persistence using the javax.transaction.UserTransaction interface. This enables flexibility and control but requires more coding.

Signup and view all the flashcards

EJB Lite

A lightweight version of EJB that provides a subset of functionality. It is designed for use in web applications and can be packaged within a WAR file.

Signup and view all the flashcards

Client-Side Validation

A validation method which is executed in the client-side browser before the data is sent to the server.

Signup and view all the flashcards

Server-Side Validation

A validation method which is executed on the server-side after the data is sent from the client browser.

Signup and view all the flashcards

AJAX Validation (Partial Processing)

A feature where a component only processes or updates the parts of the page that are directly affected by the user's action, minimizing the amount of data transferred.

Signup and view all the flashcards

Messages Components

A component that allows developers to display messages to users, with different severity levels like Info, Warn, Error and Fatal. They are useful to communicate with users about errors and success.

Signup and view all the flashcards

Panels

A container for storing and organizing other widgets. They provide a flexible way to group and manage elements within your application.

Signup and view all the flashcards

Panel Grid

A more specific type of Panel which allows flexible layout configurations using concepts like column and row spans.

Signup and view all the flashcards

Lazy Loading

A feature that enables dynamic content loading in panels, especially for tabs, where only the content of the selected tab is loaded, which is efficient.

Signup and view all the flashcards

Form Validation in Non-AJAX

A form is validated by checking all visible and editable input components within it, ensuring the data entered by the user meets the predefined rules.

Signup and view all the flashcards

Study Notes

Introduction

  • Lectures are 2 hours per week.
  • Midterm test - 10 points.
  • Team project (29 product, 5 documentation, 5 defense) - 39 points.
  • Final exam - 51 points (10 points for oral part).
  • Lower limits: Team project - 10 points, Final exam - 20 points.
  • Projects: Web (and mobile) application for 5 students.
  • Fewer students possible after consultation.

Course Overview

  • Servlets, Java Server Pages
  • Maven, Testing and JAX (Java API for XML)
  • RMI (Remote Method Invocation) and JMS (Java Message Service)
  • EJB (Enterprise Java Beans) and Java Server Faces
  • PrimeFaces
  • Spring
  • Midterm test
  • Lectures by expert from practice
  • JPA (Java Persistence API), Hibernate
  • Google Web Toolkit
  • Android basics
  • Cloud
  • Advanced Android
  • Project defenses

Java EE and Jakarta EE

  • 1998 - Sun started Java Professional Edition project.
  • 1999 - Java 2 Platform Enterprise Edition (J2EE) was born.
  • 2006 - J2EE was renamed to Java EE or Java Platform Enterprise Edition.
  • 2017 - Oracle decided to give away the rights for Java EE to the Eclipse Foundation (the Java language is still owned by Oracle).
  • 2018 - Community voted for the new name and picked Jakarta EE.

Servlet Containers and Application Servers

CGI Scripts

  • CGI stands for "Common Gateway Interface".
  • CGI script is an external program, called by the web server
  • Web server is the mediator between client and application.
  • It runs a new instance for each request (stateless).

Servlets

  • A servlet is a small Java program.
  • It runs within a Web server (a Java class).
  • For a servlet not hosted in a distributed environment, the servlet container uses only one instance per servlet declaration.
  • For a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances for a heavy request load and serialize requests to a particular instance.

Servlets vs. CGI scripts

  • Advantages of servlets:
  • Running a servlet doesn't require creating a separate process each time.
  • A servlet stays in memory, so it doesn't need to be reloaded each time.
  • There's only one instance handling multiple requests, not a separate instance for every request.
  • It can keep context (session) in memory.
  • Untrusted servlets can be run in a "sandbox".
  • Disadvantage: More complicated configuration.

Servlets

  • A servlet is any class that implements the javax.servlet.Servlet or jakarta.servlet.Servlet interface.
  • Most servlets extend javax.servlet.http.HttpServlet or jakarta.servlet.http.HttpServlet (to support HTTP protocol).
  • Others extend javax.servlet.GenericServlet or jakarta.servlet.GenericServlet (if not specifically HTTP).
  • Servlets have an init, service, and destroy method.

Important Servlet Methods

  • When a servlet is first started, the init(ServletConfig config) method is called.
  • init should handle initializations.
  • Every servlet request results in a call to service(ServletRequest request, ServletResponse response).
  • service calls another method depending on the service type.
  • service handles multiple requests (must have thread safety).
  • When the servlet is shut down, the destroy() method is called.

Servlet deployment

  • Web archive
  • Contains deployment descriptors (e.g., MANIFEST.MF).
  • Actual program code and libraries,
  • Configuration file(web.xml) defining mapping from URLs to servlet components in WEB-INF,
  • filters, init context, servlet mapping, errors handlers.
  • Configuration can be done using annotations.

Methods and configuration

  • Init param (for given servlet)
  • Context param (for whole application)
  • Load on startup

Configuration

  • Filters
  • Mostly predefined from libraries, Used for tasks like logging, security.
  • Servlet Mappings
  • Mapping URLs to servlet instances.

HTTP requests

  • HTML form action attribute.
  • Almost always a GET or a POST request.
  • "get" - puts form data in the URL after "?".
  • "&" separates parameters.
  • "post" - enables sending large amounts of information.

Servlet methods

  • Service method dispatches various HTTP method requests.
  • doGet used for GET requests.
  • doPost used for POST requests.

A "Hello World" servlet

  • Example code for a simple "Hello World" servlet.

The superclass

  • Every class must extend GenericServlet or a subclass of.
  • GenericServlet (protocol-independent),
  • Usually extend HttpServlet (for HTTP requests).

The doGet method

  • This method serves a GET request.
  • Input in HttpServletRequest parameter.
  • Output via HttpServletResponse.
  • Uses request to get information sent.
  • Does not return a value, uses response for output.

Input to the servlet

  • GET requests: parameters in URL(e.g.,name=value&name=value).
  • Spaces encoded as "+".
  • POST requests: parameters in request body (harder to see).
  • Parameter names can occur multiple times.

Getting the parameters

  • Input parameters retrieved via HttpServletRequest object.
  • getParameterNames() returns an Enumeration of parameter names.
  • getParameter(name) returns the value of parameter name as a String.
  • getParameterValues(name) returns an array of values for parameter name.

Example of input parameters

  • Example code snippet demonstrating how to retrieve input parameters from a request.

Using the HttpServletResponse

  • The second parameter in doGet(and doPost).
  • Sets the MIME type of the reply to the client.
  • Uses PrintWriter to output character data.

Using the PrintWriter

  • Method to produce the web page.
  • Creates the header string "\n".
  • Shows the use of ‘println’method to print html structure.

Typical servlet operations

  • Input validation (can be done client-side).
  • Working with database (e.g., using API).
  • Uploading Files (using Commons IO and FileUpload library for example).

Commons FileUpload

  • Depends on Commons IO.
  • FileItemFactory, ServletFileUpload, FileItem.
  • For storing files, a repository (typically/tmp) is needed.

Direct handling (from servlet 3.0)

  • Request contains parts (e.g., Content-Type). • Methods such as getParts(). • More properties (e.g., getSize() getContentType())

Annotations

  • Annotations enable a declarative style of programming
  • Annotations specify how to process declared elements
  • Three Retention Policies:
  • SOURCE (used by IDEs before compilation),
  • CLASS (processed during compilation and in class files),
  • RUNTIME (available in the runtime environment).

Annotation declaration

  • Types of annotations:
  • normal (key-value pairs).
  • single-member (single value).
  • marker (no value).

Normal Annotation

  • Example annotations with multiple parameters.

Special annotations

  • Single-member annotations.

Built-in Annotations

  • @Override - Indicates overriding a method from superclass.
  • @Deprecated - A program element marked as deprecated.
  • @SuppressWarnings - Suppresses specific compiler warnings.
  • Example usages for @Override, @Deprecated, @SuppressWarnings

Meta-Annotations

  • @Target – Specifies the types of elements an annotation can be applied to.
  • @Retention – Specifies how long the annotation information will be retained
  • @Inherited – Indicates whether an annotation is inherited by subclasses
  • Example usages for @Target, @Retention, @Inherited

Meta-Annotation Examples

  • Example usages of built-in meta-annotations.

Meta-Annotation Inherited

  • How annotations of this type will be inherited.
  • Example code illustrating inheritance behavior

Target values

  • Possible targets for the @Target metadata annotation
  • TYPE, TYPE_PARAMETER, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE

References

  • Links to resources for servlets, configurations, and annotations.

The problem with servlets

  • Servlets can be complex to manage & update.
  • It is harder to use web tools to create interfaces if HTML. is hard-coded into the servlet directly.

JavaServer Pages

  • Alternate way to create servlets.
  • Written as standard HTML with embedded Java code.
  • JSP code is translated into Java servlets.

JSP Processing

  • JSPs compiled on first request.
  • First page load may be slower.
  • HTML translated to println() within servlet instance.

JSP Advantages

  • Ease of working with UI rather than pure Java classes.
  • Easier to add or modify UI components, as Java code is used within the HTML.

JSP scripting elements

  • Three types of tags (depending on function):
  • <%=expression%> (for expressions).
  • <%code%> (for scriptlets).
  • <%!declaration%> (for declarations).

Example JSP

  • Example of how to embed Java expressions into an HTML page using JSP.

Implicit objects

  • Predefined variables (objects) available in JSPs: • request • response • out • config • page • exception • pageContext • session • application

JSP scopes

  • Different scopes for JSP variables:
  • page
  • request
  • session
  • application

Scriptlets

  • Insert Java code directly into a servlet method.
  • Not recommended to mix scriptlets with HTML structures.
  • It is important to not write too much logic into the scriptlets.

Declarations

  • Declaring variables, methods to your servlet class using <%! %>tag.

Directives

  • <%@page ...%> - Affects the servlet class itself.
  • <%@include ...%> - Inserts another file into the JSP page.
  • <%@taglib ...%> - Defines tags for reuse.

The page directive

  • Defines attributes that apply to a page (attributes vary).
  • Attributes include: extends, import, session, buffer, autoFlush, info, errorPage, contentType,pageEncoding

The include directive

  • Inserts a file into the current JSP page, treated another JSP.
  • URLs are usually relative to the current file, but if starts with "/" relative to the web server's home directory.

JSP comments

  • Use special tags for comments that are not rendered in the client-side.

JavaBeans

  • Reusable components for applications. • They encapsulate business logic. • Should have constructor, methods, Serializable, etc.

Getter and setter

  • Methods for accessing and modifying bean properties (getters and setters).

JavaBeans – Example

  • Sample JavaBean implementation (e.g., Frog).

JavaBean properties

• Bound properties for notification to other components about property change events. (PropertyChangeSupport) • Vetoable properties to get vetoing functionality from changes in properties (PropertyChangeSupport).

Expression Language

• Used for expression evaluation throughout JSPs and for dynamic interaction with business logic components.

Expression language

• EL allows page authors to use simple expressions to dynamically access data from JavaBeans components. • Tasks:

  • reading data from JavaBeans,
  • writing data to JavaBeans,
  • invoking methods on JavaBeans,
  • performing arithmetic operations, etc.

Immediate and deferred evaluation syntax

• Immediate evaluation tags: uses $ {}. • Deferred evaluation tags: uses # {}.

Value Expressions

• Rvalue: read-only data retrieval. • Lvalue: capable of modification. • Can access JavaBeans components, their properties, attributes, Java SE enumerated types, and implicit objects,

Method Expressions

• Invoking arbitrary public methods on beans. • Using: . and [ ] operators. • Parameterized method calls supported in the EL.

JSP tags

  • Uses XML syntax.
  • Used to import tag libraries (e.g. JSTL - JSP Standard Tag Library).

JSP predefined tags

  • Predefined tags for use in JSP are readily available, use without directives. • <jsp:include .../>- Inserts a specified file into JSP (Execution time). • <jsp:forward .../>- Redirects the user to another page (compute). • <jsp:getProperty .../>- Provides functionality to get specific properties of an object. • <jsp:setProperty .../> - Assign values to specific properties of an object. • The <jsp:useBean .../> tag is most common, used to create an instance of a JavaBean.

JSP useBean tag

• create or receive an instance of a JavaBean • Used for creating or instantiating a bean with a specific name and scope.

References

  • Provide links for JSP

Testing – basic concepts

  • Four levels of software testing (Unit, Integration, System, Acceptance, Regression).
  • Fixture – data for repeatable testing.
  • Test case – set of tests with a specific fixture for a single unit.
  • Test suite – a collection of test cases covering a system.

Content

  • JUnit (a unit testing framework for Java)
  • Arquillian (a testing framework for integration testing)
  • Selenium (a framework for web browser automation)
  • Hudson / Jenkins (a framework for continuous integration)

Testing in Java – JUnit

  • xUnit family standard
  • JUnit 4 does not use Java Annotations
  • Example function using JUnit assertions

JUnit Fixtures, Exceptions, Timeout

  • @Before, @After - called before/after each test expected exceptions,
  • assertThrows
  • Timeout
  • examples

JUnit Assertions

  • assertEquals, assertNull, assertNotNull, assertSame, assertFalse/assertTrue,.

JUnit – Fail

  • Explicitly indicate test failure
  • Examples:fail(),fail(String message) • ExampleNumberGenerator

JUnit Test Suite

  • Define test suites with suites of test cases to run.

JUnit Test Runner

  • Example class for running the JUnit test suite.

Integration Testing

  • Test multiple components together.
  • Arquillian for integration testing of REST APIs running in a container.
  • Use ShrinkWrap
  • Example calculator-junit_arquillian

CDI (Contexts and Dependency Injection)

  • Contexts – lifecycle and interactions of stateful components.
  • Dependency Injection – injecting components. — The order of these is:
  • Container calls the bean constructor to construct the instance
  • Container initializes all the injected fields of the bean (in the same order)
  • All initializer methods are invoked
  • If any of these steps are missing or in wrong order, it is not portable and unexpected behavior may occur.

Integration Testing

• Test dependency injection, • CDI events, interceptors • @PostConstruct • @PreDestroy • Shrink Wrap example • CreateDeployment

Functional Testing

• Tests the functionality of the entire application, usually black-box testing. • Selenium for Web browser remote control • http://seleniumhq.org/

Selenium

• WebDriver – does not require selenium server • Remote Control – requires selenium server.

Continuous Integration

  • Maintaining a code repository,
  • Automating the build,
  • Making the build self-testing,
  • Supporting team development,
  • Every commit should be built and tested,
  • Everyone can see test results,
  • Initial setup time required (Hudson and Jenkins).

Jenkins

  • Easy installation, web GUI, settings build scripts, testing, reporting, Repository change support, RSS/Email/IM integration, JUnit/TestNG integration, distributed builds, plugin support.

References

  • Provide links for JUnit, Arquillian, Selenium, and Hudson.
  • Provide links for build tools.

Maven

  • Project management tool.
  • Dependency management.
  • Documentation.
  • Project lifecycle.
  • Convention over configuration
  • Common interface

Maven project structure

  • Project root (foo folder),
  • Project object model (pom.xml),
  • Project sources(src/main/java/….)
  • Test sources(src/test/java/...),
  • Build output (target/....),
  • Common directory structure

Maven project structure- web

  • Project root
  • Project object model
  • Project Java sources
  • Test sources
  • Build output
  • Output files(.war)

Project Object Model

  • Basic information (groupID, ArtifactID, etc.)
  • Dependencies
  • Build
  • Reporting

Lifecycles

  • Default lifecycle (e.g., build, testing, deployment).
  • Site lifecycle – creating documentations.
  • Clean lifecycle – removing generated stuff.

Lifecycle phases

  • List of different phases of a lifecycle (e.g., validate, compile, package, verify, etc.).

Other lifecycles

  • Site lifecycle, clean lifecycle

Maven configuration

  • MAVEN_OPTS environment variable
  • settings.xml file (local repository, servers).
  • .mvn folder

Plugins and goals

  • Plugin is a Java class with Maven specific metadata.
  • Goals can be called directly. • The phase of goals can be bound to a lifecycle phase. • Reports are used during site generation. • Examples for using Maven plugins and goals for compiling, testing, and packaging a project.

Maven repository

  • Contains downloaded dependencies.
  • By default in ~/.m2
  • Can be changed by command line argument.

Maven dependency resolution

  • Prioritization of dependencies resolution: (Local, Central, Remote).

Maven dependency scopes

  • Scope types: compile, provided, runtime, test, system, import.

Including custom library

• When the required library is not in any repository.

  • maven install command (for local installation).

Maven Archetypes

• Project templates • Provide pre-configured project structures. • Examples of how to invoke mvn archetype:generate

Creating maven project

  • Methods for creating a new Maven project from different applications.

Maven plugins

  • Custom functionality
  • Calling other plugins.

Content

  • JAX-RS • Javaâ„¢ API for (XML) RESTful Web Services • JAX-WS • Javaâ„¢ API for XML-Based Web Services

JAX-RS introduction

  • State transfer
  • HTTP architecture.
  • typical client-server model: handled by different resources.

REST (HTTP) methods

  • GET - retrieves a resource without side effects.
  • HEAD - similar to GET but does not return a body.
  • POST - creates or updates a resource.
  • PUT - creates or replaces a resource.
  • DELETE - removes a resource.

JAX-RS and Jersey

  • Java defines REST via JSR 311 (JAX-RS).
  • Jersey is an reference implementation. • Server side: • Jersey servlet predefined classes • Registration in web.xml. • Base URL (e.g., http://hostname:port/context-root/url- pattern/path-of-rest-class). • Paths specified via annotations.

Jersey DispatcherServlet

• Jersey needs to be registered as the servlet dispatcher for REST services.

  • Where to look for server classes • Root path specification • Everything is configured in web.xml.

web.xml example Jersey 2.x

  • Example of web.xml configuration for a Jersey 2.x REST application.

web.xml example Jersey 1.x

  • Example of web.xml configuration for a Jersey 1.x REST application.

JAX-RS annotations

  • @Path - sets the resource path.
  • @GET,@POST,@PUT,@DELETE - define HTTP methods.
  • @Produces - sets the response content types to MediaType.
  • @Consumes - sets the input content types.

Jersey example

  • Example of a Jersey REST resource class and its usage in a GWT RPC workflow example.

Form parameters

  • @FormParam annotation. • Needs a Form submit needed
  • Consumes APPLICATION_FORM_URLENCODED.

Matrix parameters

• GET parameters separated using ';' delimiter • Call example: • /mapping;year=1234;country=CZ;author=Me.

Path parameters

• Parameters separated by '/'. • Call example: • /mapping/2001/11/12

File upload

  • Jersey Multipart, • InputStream with file data, • FormDataContentDisposition.

File download

• Bean must return streamed content. • Example code snippet for downloading a file.

JAXB

  • Javaâ„¢ Architecture for XML Binding(JAXB)

JAXB example

  • Example code snippet using JAXB.

References

  • Provide links for JAXB, JAX-RS and Jersey.

JAX-WS Introduction

  • Java API for XML-based Web Services (JAX-WS)
  • JSR 224.
  • Extends JAX-RPC 1.0.
  • What are Web Services
  • Message or RPC oriented approach
  • SOAP
  • SOAP messages are sent via HTTP
  • Typically used for XML-based communication.

SOAP

• XML-based protocol • Envelope structure • Encoding rules • conventions for representing web service invocations and responses • Web methods (GET, POST, PUT, DELETE) • Server-side Java interface • defining methods. • Client-side proxy for invocation.

SOAP Message

• XML containing elements: • Envelope,Header,Body,Fault.

JAX-WS architecture

  • Implementations (e.g., Apache AXIS, Glassfish Metro).
  • Illustrative diagram showing the interaction between the client side and server side objects.

JAX-WS Web Integration

  • Glassfish Metro
  • Endpoint specified in sun-jaxws.xml
  • Web.xml
  • WSServletContextListner
  • WSServlet
  • @WebService
  • @WebMethod

sun-jaxws.xml

  • Example sun-jaxws.xml configuration.

web.xml

  • Example implementation of a web.xml configuration file.

JAX-WS

  • Endpoints
  • RPC (Remote Procedure Call) style web service endpoint
  • Document style web service endpoint.

JAX-WS RPC style

  • Synchronous style
  • Easy to implement
  • Poor performance
  • @WebService • @SOAPBinding(style=Style.RPC) • Accessibility on URL (named by package) • QName defines target service endpoint • Communication via service port.

JAX-WS RPC example

  • Example of a JAX-WS RPC style web service.

JAX-WS RPC Example (2)

  • Using wsimport tool to generate client code that will access the deployed web service.

JAX-WS Document style

• Asynchronous style • Greater overhead • Better for custom data types. • @WebService @SOAPBinding(style = Style.DOCUMENT, use = Use.LITERAL) • SOAP messages will include complete data type info (as opposed to just method invocation)

JAX-WS Document example

  • Example of JAX-WS Document style web service.

JAX-WS Document example (2)

  • More information on how wsgen CLI tool can be used for creating artifacts from wsdl.

JAX-WS Document example (3)

  • Example of JAX-WS Document style web service client.

JAX-WS MTOM

  • Message Transmission Optimization Mechanism supports sending binary attachments.

Web Service handlers

  • Client handlers - intercept client calls, handle authentication, etc.
  • Server interceptors - validate requests, authorize clients, etc.

Client handler

• Create the client for the web service. • Create SOAP Handler • Handler Configuration • Handler Mapping • SOAPHandler interface: implements SOAPHandler<SOAPMessageContext>.

Client handler (2)

• Intercept mapping specified in XML file. • @HandlerChain, • Examples for handler chaining and mapping.

Server handler

• Create Web Service • Create SOAP Handler, • Handler Configuration, • Handler Mapping, • SOAPHandler interface: handleMessage().

Server handler (2)

• Intercept mappings are defined in XML file.

References

• Provide links for JAX-WS.

Content

• RMI (Remote Method Invocation) • JMS (Java Message Service)

RMI

  • Remote method invocation
  • Distributed Java
  • TCP/IP transport layer
  • Client/server architecture • RMI layers: Stub, Skeleton.
  • RMI uses proxy design pattern. • A naming or directory service is usually run on a well-known host and port number (often port 1099).

RMI protocols

  • RMI uses JRMP and IIOP protocols for interoperability. • JRMP is proprietary • IIOP is CORBA’s protocol using TCP/IP as the transport.

RMI architecture

  • The interaction between clients and servers.

RMI features

  • Simplifies communication with remote application
  • Supports local method calls (on both client & server).
  • Supports security (authentication/authorization). • Layer design (stub and skeleton).

RMI principles

  • Java RMI framework usage. • naming registry (rminame registry - provides information on the location of the remote object)
  • Naming or directory service,
  • RMI includes RMI registry.

RMI Registry

• The RMI registry is a naming and directory service. • enabling remote clients to find remote object references.

RMI Naming

• Naming static class (Bind, list, lookup, rebind, unbind).

Server implementation (RMI)

• Shared proxy object • Shared proxy must be implemented. • Registry is created. -- If not already running • Service is bind to the name -- the name is used by clients for lookup

Client implementation (RMI)

Basic client usage for RMI calls

Server callback

Asynchronous calls, different port, UnicastRemoteObject. • exportObject

RMI security

  • Initialize security manager
  • Secuirity manager restricts code from network connections • Package javax.security.manager

References

  • Provide links for RMI.

JMS

  • Asynchronous message exchange • JMS implementations are called JMS providers. • Different providers are not interoperable.
  • Reliable delivery.
  • Different Providers (e.g., OpenMQ, JBossMQ, WebSphere MQ, ActiveMQ, RabbitMQ, ZeroMQ).

Messaging domains

  • P2P (Point to Point) -- Only one consumer. • Each queue can have more senders.
  • Pub/Sub -- Multiple providers and consumers.

JMS architecture

  • JMS interface specification
  • JMS Provider implementations
  • JNDI
  • Connection factories
  • Destinations

JMS programing model

• Connection factory • TopicFactory,QueueFactory • Destination − Topic − Queue • Session • Consumer, Producer

JMS messages

  • Map Message,
  • Text Message,
  • Object Message,
  • Stream Message,
  • Byte Message,

JNDI

  • Java Naming and Directory Interface
  • JMS is tightly coupled to JNDI.
  • Provider - queuing services lookup.
  • Contains a context.

JNDI association, context, system, namespace

  • JNDI objects for binding names,
  • Locating objects.

JNDI architecture

• Provides an abstraction to various directory services

  • Common API for client access, • JNDI SPI - service provider interface, • Custom naming service using JNDI SPI • Naming service may be LDAP, DNS, NIS, NDS, RMI, CORBA.

JNDI services

– Access directory services. • Common API for client access. • Directories are structured trees of information

Message consumptions

  • Asynchronous approach • A client register a message listener.
  • Synchronous approach • Subscriber or receiver explicitly calls receive method.

JMS features (additional)

  • Additional features (message acknowledgement, priorities, persitent delivery mode, control of message expiration, durable subscriptions, message transactions)

Message acknowledgements

• Auto, explicit, and lazy client acknowledgements. • Handling possible message duplication.

Persistent delivery mode

• Default mode (logged to persistent store) • Non-persistent delivery mode (not stored to a persistent store)

Priorities, expirations

• 10 levels (0-lowest, 4-default, 9-highest) • Queues and topics can be large • Expiration time (TTL) and priorities

Durable subscriptions and transactions

• Durable subscriptions survive application restarts. • Transactions group operations as atomic units (rollback).

Transactions

• Grouping of operations into an atomic unit of work. • Rollback - undo and destroy messages • Commit – all messages are sent and consumed messages acknowledged

ActiveMQ

  • How to run the broker (e.g. from https://..).
  • Default URL of the broker (usually an Application Server defined constants. )

References

  • Provide necessary resources to handle JMS.

Contents of EJB

• Enterprise bean class • Business interfaces • Other classes • Deployment descriptor (optional)

EJB

• Enterprise JavaBeans (EJB) • Execute within an EJB container. • Server side components, • Part of application server.

EJB server

• Part of an application server hosting EJB containers.

  • Several common application servers
  • GlassFish(Oracle), WebSphere(IBM), WebLogic(Oracle), WildFly(Red Hat),WebObjects(Apple), ... • EJB specification outlines EJB server functionalities (naming, transactions, security, persistence, concurrency, lifecycle, messaging, timers, etc.).
  • EJB don't interact directly with the EJB server.

EJB Container

  • Runtime environment for EJB components.
  • Transparent to the client. • Services (transaction, concurrency, pooling, security).

Multitiered Java EE Applications

• Client tier • Web tier • Business tier • EIS tier.

EJB Components

• EJB components are modular, reusable server-side components,

Enterprise Java Bean types

  • Session beans (Stateless, Statefull, Singleton).
  • Message-driven beans • Entity beans - persistent data storage.

Accessing Session Beans

• Clients access session beans via dependency injection (@EJB) or JNDI lookup.

Dependency Injection Example

  • Using dependency injection with EJB.

JNDI names

• Naming service, JNDI names used to access beans (examples for accessing using different JNDI types).

Calendar-based Timer Service

  • Annotation @Schedule.
  • Sample usage (dayOfWeek, hour, minute, second, timezone).

Asynchronous Invocation

  • Methods can be invoked asynchronously. • Return values are often Future<V>
  • Example for handling asynchronous calls.

EJB Transactions

• Container-managed (default)

  • TransactionAttributeType (REQUIRED,REQUIRES_NEW, MANDATORY etc.). • Bean-managed transactions Using a javax.transaction.UserTransaction interface.

EJB Lite

  • Subset of EJB full
  • no remote interfaces, no message-driven beans, no JMS, no web services, etc.

Embeddable Container

• Running client and EJB in the same JVM. • Support for testing.

Contents of EJB

• Enterprise bean class, business interfaces, other classes, and deployment descriptor.

Deployment Descriptors

• XML file containing deployment settings including transactional settings.

References

• Provide detailed links for JSF, Java Persistence, and EJB.

Introduction

  • GWT is a framework for building AJAX applications using Java.
  • GWT compiles Java code to JavaScript.

GWT Application Structure

• Directory structure in a typical GWT application. • Distinguish between a client side and server side components (e.g., the RPC servlet interface definition).

GWT Application Structure – Maven

• Directory structure for a Maven-based GWT project. • Distinguish between a client-side and server-side components (e.g., application module definitions).

Maven Plugin for GWT Application Structure

  • Directory structure.

Application structure (GWT)

  • Separating client-side and server-side components (with different code execution environments- host page).

HTML Host Page

• File structure • Use of JavaScript code files (hello.nocache.js, etc.) • Slots for elements to be rendered.

Hello World Entry Point (GWT)

• Main function for the entry point of the GWT app.

Modules

  • Similar to packages,
  • Bundles of GWT libraries/codes,
  • Used to manage code dependencies.

Hello World Module

  • The simplest hello world definition in a GWT module.

GWT standard modules

• Core GWT code, HTTP library, JSON library, GWT testing framework, XML creation and parsing - logical names and content.

Deployment

• Creating a WAR file, • Deploying WAR to a server, • Running the application.

Deployment in NetBeans

  • How to deploy a GWT application in a platform like NetBeans.

Development mode

  • How to start and run a GWT application in development mode.

Super development mode

• How to run Super development mode.

  • Use of a dedicated server/port.

Problems

• Common issues when running a GWT application,

  • port occupancies and bootstrap file caching, etc

Production mode

• Details of how GWT generates client-side JavaScript for the deployment mode • How to ensure that client applications can cache the compiled codes.

User Interface

  • Basic GWT UI components, such as,
  • Labels, Buttons, TextBoxes,
  • Using client-side CSS styling
  • Well-defined class hierarchy.

CSS Styling

  • How to style elements using CSS- similar to standard web development

Basic widgets

  • Typical GWT widget classes that are used in different contexts.

UI objects

  • HTML
  • Image
  • Anchor

Form Widgets

  • Label, Button, PushButton, ToggleButton, CheckBox, RadioButton, ListBox, TextBox, PasswordTextBox, TextArea, RichTextArea, FileUpload, Hidden.

Complex Widgets

  • Tree, MenuBar, DatePicker, CellTree, CellList, CellTable, CellBrowser

• MenuBar example

Layout Panels

  • Layout panel definitions and attributes

Event handling

  • Event handling functionality includes typical listening for events, such as click.

Custom Widgets

• Create custom components. • Extend classes similar to typical Java or extend Composite.

GWT UI Binder

  • Framework for separating functionality and view of UI.
  • Using XML for UI definitions and bindings.

Steps for using UI binder

  • Creating UI declaration,
  • Creating Java counterpart,
  • Binding Java UI fields and elements in code
  • Attaching CSS.

JSF Managed Beans

  • Using Managed Beans to organize data and manage the application. • Accessing session beans

Dependency Injection

  • Example on how to use dependency injection using a container like Spring

No-interface view

  • EJB 3.1 version. • No need to use interfaces anymore

Message Driven EJB

  • Message driven bean usage • Messaging model (point-to-point, pub-sub).

Types of EJB

• Session beans • Stateless • Statefull • Singleton • Message-driven beans • Entity beans

Configuring datasource

  • How to configure a database connection in Spring.

Executing SQL queries

  • Methods to execute SQL queries.

Spring Transaction Management

• Local transactions. • Global transactions • Declarative/Programmatic transactions

Spring Web MVC framework

  • Model, View, and Controller pattern.

Dispatcher servlet

  • Handles HTTP requests.
  • Consults HandlerMapper to determine which controller to use
  • DispatcherServlet does all the job. • The controller decides which method to call to get the data from the database if necessary.

Configuration

  • Declaring servlets in web.xml,
  • Specifying URL pattern,
  • Defining controller and mappings.

Defining controller

  • @Controller
  • @RequestMapping.

Creating JSP views

• Creating JSP files for Views

Spring Security

• Managing user roles • Login (default or custom appearance)

Spring security configuration (XML based)

  • Configuration structure for Spring security using XML (e.g. form login)

XML configuration from

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser