Saturday, April 27, 2019

Client-side Development

 The main elements of client-side application components 

•Distributed systems use client-side elements for users to interact with
•These client-side elements include

•Views –  what users see (mainly GUIs) 
                  •Controllers –  contain event handers for the Views 
•Client-model –  Business logic and data


•Browser-based clients’ Views comprises two main elements

Content –  HTML 
 Formatting –  CSS


HTML

HTML uses different types of elements to define content 

Structural elements
     • header, footer, nav, aside, article 

Text elements 

    Headings :-  <h1>Heading 1</h1>
Headings are defined with the <h1> to <h6> tags.

    Paragraph  :-  HTML paragraphs are defined with the <p> tag

<p>This is a paragraph.</p>


    Line break  :-  <br>
HTML elements with no content are called empty elements.

<br> is an empty element without a closing tag (the <br> tag defines a line break)

    Images  :-  <img src="pic_trulli.jpg" alt="Italian Trulli">
Images can improve the design and the appearance of a web page

    Hyperlinks  :-  <a href="https://www.w3schools.com/html/">Visit our HTML tutorial</a>
Links allow users to click their way from page to page.

• Data representational elements
    Lists :-  An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
                 The list items will be marked with bullets (small black circles) by default

                  <ul style="list-style-type:disc;">
          <li>Coffee</li>
          <li>Tea</li>
          <li>Milk</li>
        </ul>

    Tables :-   An HTML table is defined with the <table> tag.

Each table row is defined with the <tr> tag. A table header is defined with the <th> tag. By default, table headings are bold and centered. A table data/cell is defined with the <td> tag.

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>

• Form elements

    Input  :- <input type="text"> defines a one-line text input field

<form>
  First name:<br>
  <input type="text" name="firstname"><br>
  Last name:<br>
  <input type="text" name="lastname">
</form>



    Radio buttons :- <input type="radio"> defines a radio button.
Radio buttons let a user select ONLY ONE of a limited number of choices 

<form>
  <input type="radio" name="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
</form>

    Check boxes :- <input type="checkbox"> defines a checkbox.
Checkboxes let a user select ZERO or MORE options of a limited number of choices.

<form>
  <input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle2" value="Car"> I have a car 
</form>


    Buttons :- <input type="button"> defines a button

<input type="button" onclick="alert('Hello World!')" value="Click Me!">


CSS

• Used to Decorate and Format content 


There are 3 main selectors use in CSS

•Element selector 
•ID selector 
•Class selector





Inline Styles

An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.



Internal Style Sheet
An internal style sheet may be used if one single page has a unique style.
Internal styles are defined within the <style> element, inside the <head> section of an HTML page



External Style Sheet
With an external style sheet, you can change the look of an entire website by changing just one file.
Each page must include a reference to the external style sheet file inside the <link> element. The <link> element goes inside the <head> section:




New features of CSS 3

CSS3 is the latest evolution of the Cascading Style Sheets language and aims at extending CSS2.1. It brings a lot of new features and additions, like rounded corners, shadows, gradients, transitions or animations, as well as new layouts like multi-columns, flexible box or grid layouts.


Drop Shadows

CSS3 provides the ability to add drop shadows to elements using the box-shadow property. This property lets you specify the color, height, width, blur, and offset of one or multiple inner and/or outer drop shadows on your elements.



Text shadow

text-shadow adds shadows to individual characters in text nodes. Prior to CSS 3, this would be done by either using an image or duplicating a text element and then positioning it.


Linear Gradients

W3C added the syntax for generating linear gradients with CSS3.



Multiple Background Images

In CSS3, there’s no need to include an element for every background image; it provides us with the ability to add more than one background image to any element, even to pseudo-elements.




Media Queries

Media queries can be used to check many things, such as:
  • width and height of the viewport
  • width and height of the device
  • orientation (is the tablet/phone in landscape or portrait mode?)
  • resolution
Using media queries are a popular technique for delivering a tailored style sheet to desktops, laptops, tablets, and mobile phones (such as iPhone and Android phones).

One way to use media queries is to have an alternate CSS section right inside your style sheet.




Inline CSS

Pros:

Testing: Many web designers use Inline CSS when they begin working on new projects, this is because its easier to scroll up in the source, rather than change the source file. Some also using it to debug their pages, if they encounter a problem which is not so easily fixed.

Quick-fixes: There are times where you would just apply a direct fix in your HTML source, using the style attribute, but you would usually move the fix to the relevant files when you are either able, or got the time.

Smaller Websites: The website such as Blogs where there are only limited number of pages, using of Inline CSS helps users and service provider.

Lower the HTTP Requests: The major benefit of using Inline CSS is lower HTTP Requests which means the website loads faster than External CSS.



Cons:

Overriding: Because they are the most specific in the cascade, they can over-ride things you didn’t intend them to.

Every Element: Inline styles must be applied to every element you want them on. So if you want all your paragraphs to have the font family “Arial” you have to add an inline style to each <p> tag in your document. This adds both maintenance work for the designer and download time for the reader.

Pseudo-elements: It’s impossible to style pseudo-elements and classes with inline styles. For example, with external and internal style sheets, you can style the visited, hover, active, and link color of an anchor tag. But with an inline style all you can style is the link itself, because that’s what the style attribute is attached to.


Internal CSS

Pros:

Cache Problem: Internal styles will be read by all browsers unless they are hacked to hide from certain ones. This removes the ability to use media=all or @import to hide styles from old, crotchety browsers like IE4 and NN4.

Pseudo-elements: It’s impossible to style pseudo-elements and classes with inline styles. With Internal style sheets, you can style the visited, hover, active, and link color of an anchor tag.
One style of same element: Internal styles need not be applied to every element. So if you want all your paragraphs to have the font family “Arial” you have to add an Inline style <p> tag in Internal Style document.

No additional downloads: No additional downloads necessary to receive style information or we have less HTTP Request.


Cons:

Multiple Documents: This method can’t be used, if you want to use it on multiple web pages.
Slow Page Loading: As there are less HTTP Request but by using the Internal CSS the page load slow as compared to Inline and External CSS.

Large File Size: While using the Internal CSS the page size increases but it helps only to Designers while working offline but when the website goes online it consumers much time as compared to offline.


External CSS

Pros:

Full Control of page structure: CSS allows you to display your web page according to W3C HTML standards without making any compromise with the actual look of the page. Google is the leading search Engine and major source of traffic. Google gives very little value to the web pages that are well-organized, since the value is little thus many Designers ignore it. But by taking small value may drive much traffic to the website.

Reduced file-size: By including the styling of the text in a separate file, you can dramatically decrease the file-size of your pages. Also, the content-to-code ratio is far greater than with simple HTML pages, thus making the page structure easier to read for both the programmer and the spiders. With CSS you can define the visual effect that you want to apply to images, instead of using images per say. The space you gain this way can be used for text that is relevant for spiders (i.e. keywords), and you will also lower the file-size of the page.

Less load time:  Using external CSS has reduced the page load timing. when you first visited the website, it has downloaded all the contents + external CSS and while downloading external CSS, it has marked the CSS with the time stamp with the time stamp of the web server. Now when you hit F5, it again starts working but this time the browser compare the time stamps of downloaded CSS with Web Server CSS and due to same time stamp, it doesn’t downloaded the CSS external file from server and using the already downloaded time, which make the Web Page Loading time faster as com paired to first time.

Higher page ranking :  CSS will help you create highly readable pages, rich in content, which will prove extremely helpful in your SEO campaign. As you very well know, better site ranking means better visibility on the web, and this can translate into more visitors and, ultimately, into increased sales or number of contracts. For more details lets use some code to understand:



View Development Tools

jQuery – A JS library, but can be seen a framework too. Itwraps the complexity of pure JS. There are lots of JSframeworks, libraries, and plugins built using jQuery. Good forDOM processing.

jQuery UI – Focus on GUI development

Bootstrap – to rapidly design and develop responsive webpages and templates.

Angular – a JS framework/platform to build frontendapplications.

React – a JavaScript library for building user interfaces (and
the application, which uses that UI)



_____________________________________________________

JavaScript 6

New features 
  • JavaScript let
           The let statement allows you to declare a variable with block scope.

var x = 10;
// Here x is 10
  let x = 2;
  // Here x is 2}
// Here x is 10


  • JavaScript const
    The const statement allows you to declare a constant (a JavaScript variable with a constant value).
Constants are similar to let variables, except that the value cannot be changed.


  • Exponentiation (**)

          The exponentiation operator (**) raises the first operand to the power of the second operand.


  • Default parameter values
        ES6 allows function parameters to have default values.

function myFunction(x, y = 10) {
  // y is 10 if not passed or undefined  return x + y;
}
myFunction(5); // will return 15



  • Array.find() Method
        The find() method returns the value of the first array element that passes a test function.


  • Array.findIndex() Method
        The findIndex() method returns the index of the first array element that passes a test function.


  • Number.isInteger() Method
        The Number.isInteger() method returns true if the argument is an integer.


  • Number.isSafeInteger() Method
           A safe integer is an integer that can be exactly represented as a double precision number.
The Number.isSafeInteger() method returns true if the argument is a safe integer.


  • isFinite() Method
        The global isFinite() method returns false if the argument is Infinity or NaN.
Otherwise it returns true.

  • isNaN() Method
        The global isNaN() method returns true if the argument is NaN. Otherwise it returns false.



  • Arrow functions
       Arrow functions allows a short syntax for writing function expressions.
You don't need the function keyword, the return keyword, and the curly brackets.



Component Development

Top JS frameworks/Libraries

jQuery: Basic and simple. Cover the complexity of JS and
provides cross-browser compatibility.

React: powers Facebook, Ease of Learning, DOM Binding,
Reusable Components, Backward Compatibility.

Angular: Support for Progressive Web Applications, Build
Optimizer, Universal State Transfer API and DOM, Data
Binding and MVVM.

Vue: lightweight , with a much-needed speed and accuracy.

___________________________________________________________

References

Friday, April 12, 2019

Data Persistence

The role of Data in information systems

In computing, data is information that has been translated into a form that is efficient for movement or processing. Relative to today's computers and transmission media, data is information converted into binary digital form. It is acceptable for data to be used as a singular subject or a plural subject. Raw data is a term used to describe data in its most basic digital format.

Persistence is "the continuance of an effect after its cause is removed". In the context of storing data in a computer system, this means that the data survives after the process with which it was created has ended. In other words, for a data store to be considered persistent, it must write to non-volatile storage.
•Information systems process data and convert them into information
•The data should persist for later use
•To maintain the status
• For logging purposes
•To further process and derive knowledge (data science)



Data


Information in raw or unorganized form (such as alphabets, numbers, or symbols) that refer to, or represent, conditions, ideas, or objects.



Database


A database is a collection of information that is organized so that it can be easily accessed, managed and updated.


Database Server

Database server is the term used to refer to the back-end system of a database application using client/server architecture. The back-end, sometimes called a database server, performs tasks such as data analysis, storage, data manipulation, archiving, and other non-user specific tasks.



Database Managment System

A database management system (DBMS) is system software for creating and managing databases. The DBMS provides users and programmers with a systematic way to create, retrieve, update and manage data.
A DBMS makes it possible for end users to create, read, update and delete data in a database. The DBMS essentially serves as an interface between the database and end users or application programs, ensuring that data is consistently organized and remains easily accessible.
________________________________________________________________________________________



Pros and Cons of  File System vs Database


Pros of the File system:
  • Performance can be better than doing it in db. To justify this, If you store large files in db then it may slow down the performance because a simple query to retrieve the list of files or filename will also load the file data if you used Select * in your query. While Files system accessing a file is quite simple and light weight.
  • Saving the files and downloading them in the file system is much simpler than database since a simple Save as function will help you out. Downloading can be done by addressing an URL with the location of the saved file.
  • Migrating the data is an easy process here. You can just copy and paste the folder to your desired destination while ensuring that write permissions are provided to your destination.
  • Cost effective as It is Economical in most of the cases to expand your web server rather than paying for certain Databases.
  • Easy to migrate it to Cloud storage like Amazon S3 or CDNs etc in the future.


Cons of the File system:
  • Loosely packed. No ACID (Atomicity, Consistency, Isolation, Durability) operations relational mapping which mean there is no guarantee. Consider a scenario if your files are deleted from the location manually or by some hacking dudes, you might not know whether the file exists or not.
  • Low Security. Since your files can be saved in a folder where you should have provided write permissions, it is prone to safety issues and invites troubles like hacking. So it is best to avoid saving in fs if you cannot afford to compromise in terms of security.



Pros of Database:
  • ACID consistency which includes a rollback of an update that is complicated when the files are stored outside the database.
  • Files will be in sync with the database so cannot be orphaned from it which gives you an upper hand in tracking transactions.
  • Backups automatically include file binaries.
  • More Secure than saving in a File System.


Cons of Database:

  • You may have to convert the files to blob in order to store it in db.
Database Backups will become more hefty and heavy.

  • Memory ineffective. To add more, often RDBMS’s are RAM driven. So all data has to go to RAM first. Yeah, that’s right. Had you ever thought about what happens when an RDBMS has to find and sort data? RDBMS tracks each data page even lowest amount of data read/written, and it has to track if it’s in memory or if it’s on disk if it’s indexed or sorted physically etc.
________________________________________________________________________________


Data arrangement


Unstructured Data

Unstructured data files often include text and multimedia content. Examples include e-mail messages, word processing documents, videos, photos, audio files, presentations, webpages and many other kinds of business documents. Note that while these sorts of files may have an internal structure, they are still considered "unstructured" because the data they contain doesn't fit neatly in a database.


Semi-structured

Semi-structured data is information that doesn't reside in a relational database but that does have some organizational properties that make it easier to analyze. Examples of semi-structured data might include XML documents and NoSQL databases.


_______________________________________________________________________________


Big Data vs Data Warehouses







_______________________________________________________________________________

ORM Tools

Irwsoft Data Framework

Irwsoft Data Framework is a lightweight ORM that integrates directly with Visual Studio to generate table, view, function and procedure classes directly from a database.


LLBLGen Pro

A sort of uber-ORM you might want to evaluate for more complex development situations is LLBLGen Pro, which provides both data model development and ORM functionality in one package.


nHydrate ORM Modeler

Inspired by NHibernate is an open source ORM solution for mapping relational databases to .NET objects. nHydrate now uses Entity Framework as its internal data access layer and provides a visual modeler of data relationships.


ORMapster

ORMapster for Visual Studio 2013 is a simple ORM data mapper and code generator extension that does one thing: iI reads your data source and creates a data access layer with LINQ self-tracking entities. That's it. The resulting data entities can then be used in your projects, including WCF, ASP.NET MVC, Web Forms, Windows Forms and so on.


________________________________________________________________________________


NoSQL

Benefits of NoSQL 

• When compared to relational databases, NoSQL databases are more scalable and provide superior performance, and their data model addresses several issues that the relational model is not designed to address.

 • Large volumes of rapidly changing structured, semi-structured, and unstructured data. 

Agile sprints, quick schema iteration, and frequent code pushes

Object-oriented programming that is easy to use and flexible

Geographically distributed scale-out architecture instead of expensive, monolithic architecture


NoSQL Database Types

Document databases pair each key with a complex data structure known as a document. Documents can contain many different key-value pairs, or key-array pairs, or even nested documents.

Graph stores are used to store information about networks of data, such as social connections. Graph stores include Neo4J and Giraph.
    Key-value stores are the simplest NoSQL databases. Every single item in the database is stored as an attribute name (or 'key'), together with its value. Examples of key-value stores are Riak and Berkeley DB. Some key-value stores, such as Redis, allow each value to have a type, such as 'integer', which adds functionality.

    Wide-column stores such as Cassandra and HBase are optimized for queries over large datasets, and store columns of data together, instead of rows.

________________________________________________________________________________

Hadoop

The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, the library itself is designed to detect and handle failures at the application layer, so delivering a highly-available service on top of a cluster of computers, each of which may be prone to failures.

________________________________________________________________________________

Thursday, March 21, 2019

Server-side Development II


Message-Oriented Communication

Message-oriented communication is a way of communicating between processes. Messages, which correspond to events, are the basic units of data delivered. Tanenbaum and Steen classified message-oriented communication according to two factors---synchronous or asynchronous communication, and transient or persistent communication. In synchronous communication, the sender blocks waiting for the receiver to engage in the exchange. Asynchronous communication does not require both the sender and the receiver to execute simultaneously. So, the sender and recipient are loosely-coupled. The amount of time messages are stored determines whether the communication is transient or persistent. Transient communication stores the message only while both partners in the communication are executing. If the next router or receiver is not available, then the message is discarded. Persistent communication, on the other hand, stores the message until the recipient receives it.


________________________________________________________________________________

Representational State Transfer


Representations in REST style

Representations are how resources get manipulated and presented. Part of the resource state is transferred between client and server

Suppose a client makes a GET request to /programmers/Namespacinator and gets back this JSON response:

{
    "nickname": "Namespacinator",
    "powerLevel": 5
}
This is just a representation of the programmer resource. It happens to be in JSON, but the server could have represented the programmer in other ways, like in XML, HTML or even in JSON with a different format.


Constraints

Client-server
• The REST is for explicitly for networked distributed systems, which are based on the client-server style.


Layered System
• A client doesn’t need to know whether it is connected directly to the end server, or to an intermediary along the way.
• Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches.
• Layers may also enforce security policies.


Stateless
• One client can send multiple requests to the server.
• Each request is independent.
• Every request must contain all the necessary information so that the server can understand it and process it accordingly.
• The server must not hold any information about the client state.
• Any state information must stay on client – such as sessions.


Cacheable
• As many clients access the same server, often they may request the same resources.
• it is necessary that these responses might be cached, avoiding unnecessary processing, which may affect performance.


Code-On-Demand (Optional)
• This allows the customer to run some code on demand, that is, extend part of server logic to the client, either through an applet or scripts.


Uniform Interface
•Defines the interface between clients and servers.
• It simplifies and decouples the architecture, which enables each part to evolve independently
• REST is defined by four interface constraints:
                                             • identification of resources
                                             • manipulation of resources through representations
                                             • self-descriptive messages
                                             • hypermedia as the engine of application state


ELEMENTS OF REST STYLE


Components

•Software that interacts with one another.
•Communicate by transferring representations of resources through a standard interface rather than operating directly upon there source itself.
•Used to access, provide access to, or mediate access to resources.






Connector

• represent activities involved in accessing resources and transferring representations.
•REST encapsulates different activities of accessing and transferring representations into different connector types.
•connectors are abstract interfaces for component communication, enhancing simplicity by hiding
the underlying implementation of resources and communication mechanisms.






Data
• key aspect of REST is the state of the data elements, its components communicate by transferring
representations of the current or desired state of data elements.
•REST manages data in the following ways:
                        • render the data(traditional client-server style) where it is
                          located and send a fixed-format image to the recipient,
                        • encapsulate the data(mobile object style) with a rendering
                          engine and send both to the recipient or,
                        • send the raw data to the recipient along with metadata
                          that describes the data type, so that the recipient can
                          choose their own rendering engine.













RESTful API


A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.

A RESTful API -- also referred to as a RESTful web service -- is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.


REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology because REST leverages less bandwidth, making it more suitable for internet usage. An API for a website is code that allows two software programs to communicate with each another . The API spells out the proper way for a developer to write a program requesting services from an operating system or other application.


The REST used by browsers can be thought of as the language of the internet. With cloud use on the rise, APIs are emerging to expose web services. REST is a logical choice for building APIs that allow users to connect and interact with cloud services. RESTful APIs are used by such sites as Amazon, Google, LinkedIn and Twitter.
How RESTful APIs work

A RESTful API breaks down a transaction to create a series of small modules. Each module addresses a particular underlying part of the transaction. This modularity provides developers with a lot of flexibility, but it can be challenging for developers to design from scratch. Currently, the models provided by Amazon Simple Storage Service, Cloud Data Management Interface and OpenStack Swift are the most popular.

A RESTful API explicitly takes advantage of HTTP methodologies defined by the RFC 2616 protocol. They use GET to retrieve a resource; PUT to change the state of or update a resource, which can be an object, file or block; POST to create that resource ; and DELETE to remove it.


Request = URL + HTTP Verbs (GET,POST,PUT,DELETE)
• URL is the key technique in RESTful communication
• The API of the RESTful service is a set of URLs
• The resource is determined by the URL segments
• The CRUD operations are determined by the HTTP verb


Operation = Read , Verb = GET
•Collection
•SLIIT.com/students/
•SLIIT.com/students/DS
•SLIIT.com/students/DS/IT123456/posts

•Single item
•SLIIT.com/students/IT123456
•Blog.com/posts/pid15948

•Multiple items
•SLIIT.com/students/IT123456;IT456456;IT998877


Operation = Create , Verb = POST
•Single item (single item in the payload)
•SLIIT.com/students/
•SLIIT.com/students/DS
•SLIIT.com/students/DS/IT123456/posts

•Multiple items
•Same URL, items will be in the payload


Operation = Update , Verb = PUT
•Collection (data in the payload)
•SLIIT.com/students/
•SLIIT.com/students/DS
•SLIIT.com/students/DS/IT123456/posts

•Single item
•SLIIT.com/students/IT123456
•Blog.com/posts/pid15948

•Multiple items
•SLIIT.com/students/IT123456;IT456456;IT998877


Operation = Delete , Verb = DELETE
•Collection
•SLIIT.com/students/
•SLIIT.com/students/DS
•SLIIT.com/students/DS/IT123456/posts

•Single item
•SLIIT.com/students/IT123456
•Blog.com/posts/pid15948

•Multiple items
•SLIIT.com/students/IT123456;IT456456;IT998877


With REST, networked components are a resource you request access to -- a black box whose implementation details are unclear. The presumption is that all calls are stateless; nothing can be retained by the RESTful service between executions.

Because the calls are stateless, REST is useful in cloud applications. Stateless components can be freely redeployed if something fails, and they can scale to accommodate loadchanges. This is because any request can be directed to any instance of a component; there can be nothing saved that has to be remembered by the next transaction. That makes REST preferred for web use, but the RESTful model is also helpful in cloud services because binding to a service through an API is a matter of controlling how the URL is decoded. Cloud computing and microservices are almost certain to make RESTful API design the rule in the future.


When you are designing REST API services, you have to pay attention to resources, those are defined by URIs.

Each resource in a service or services you are building will have at least one URI identifying it. It's best when that URI makes sense and adequately describes the resource. URIs should follow a predictable, hierarchical structure to enhance understandability and, therefore, usability: predictable in the sense that they're consistent, hierarchical in the sense that data has structure—relationships.



MVC with RESTful web service Development


























________________________________________________________________________________

JAX-RS




JAX-RS is nothing more than a specification, a set of interfaces and annotations offered by Java EE. And then, of course, we have the implementations; some of the more well known are RESTEasy and Jersey.

Also, if you ever decide to build a JEE-compliant application server, the guys from Oracle will tell you that, among many other things, your server should provide a JAX-RS implementation for the deployed apps to use. That’s why it’s called Java Enterprise Edition Platform.

Deployables can and should be very thin, letting the application server provide the needed libraries. This applies when developing a RESTful API as well: the final artifact should not contain any information about the used JAX-RS implementation.



If you want to start playing with JAX-RS, the shortest path is: have a Maven webapp project with the following dependency in the pom.xml:
1
2
3
4
5
6
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>
We’re using JavaEE 7 since there are already plenty of application servers implementing it. That API jar contains the annotations that you need to use, located in package javax.ws.rs. Why is the scope “provided”? Because this jar doesn’t need to be in the final build either – we need it at compile time and it is provided by the server for the run time.
After the dependency is added, we first have to write the entry class: an empty class which extends javax.ws.rs.core.Application and is annotated with javax.ws.rs.ApplicationPath:
1
2
3
@ApplicationPath("/api")
public class RestApplication extends Application {
}
We defined the entry path as being /api. Whatever other paths we declare for our resources, they will be prefixed with /api.
Next, let’s see a resource:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Path("/notifications")
public class NotificationsResource {
    @GET
    @Path("/ping")
    public Response ping() {
        return Response.ok().entity("Service online").build();
    }
    @GET
    @Path("/get/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getNotification(@PathParam("id") int id) {
        return Response.ok()
          .entity(new Notification(id, "john", "test notification"))
          .build();
    }
    @POST
    @Path("/post/")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response postNotification(Notification notification) {
        return Response.status(201).entity(notification).build();
    }
}
We have a simple ping endpoint to call and check if our app is running, a GET and a POST for a Notification (this is just a POJO with attributes plus getters and setters).
Deploy this war on any application server implementing JEE7 and the following commands will work:
1
2
3
4
5
6
7
curl http://localhost:8080/simple-jaxrs-ex/api/notifications/ping/
curl http://localhost:8080/simple-jaxrs-ex/api/notifications/get/1
curl -X POST -d '{"id":23,"text":"lorem ipsum","username":"johana"}'
  http://localhost:8080/simple-jaxrs-ex/api/notifications/post/
  --header "Content-Type:application/json"
Where simple-jaxrs-ex is the context-root of the webapp.
This was tested with Glassfish 4.1.0 and Wildfly 9.0.1.Final. Please note that the last two commands won’t work with Glassfish 4.1.1, because of this bug. It is apparently a known issue in this Glassfish version, regarding the serialization of JSON (if you have to use this server version, you’ll have to manage JSON marshaling on your own)

Just keep in mind that JAX-RS is a powerful API and most (if not all) of the stuff that you need is already implemented by your web server. No need to turn your deployable into an unmanageable pile of libraries.
This write-up presents a simple example and things might get more complicated. For instance, you might want to write your own marshalers. When that’s needed, look for tutorials that solve your problem with JAX-RS, not with Jersey, Resteasy or other concrete implementation. It’s very likely that your problem can be solved with one or two annotations.


Annotations in JAX-RS





@GET  :-   The @GET annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests.

@Produces :-  specifies the type of output this method (or web service) will produce.

@Path :-  specify the URL path on which this method will be invoked.

@PathParam :-  Bind REST-style URL parameters to method arguments.

@QueryParam  :-  Request parameters in query string can be accessed.

@POST :-  The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests.

@Consumes :-  used to specify the MIME media types a REST resource can consume.

@FormParam :-  read parameters sent in POST requests directly.

@PUT :-  The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP PUT requests.

@DELETE  :-  The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests.


________________________________________________________________________________


References

https://symfonycasts.com/screencast/rest/rest

http://www.techferry.com/articles/RESTful-web-services-JAX-RS-annotations.html

https://www.baeldung.com/jax-rs-spec-and-implementations

https://searchmicroservices.techtarget.com/definition/RESTful-API



Client - side Development II - RiWAs

Key features of RiWAs Direct interaction:  In RiWAs, users can interact directly with page elements through editing or drag-and-drop too...