of software and specs developed by Sun and later acquired by Oracle • Java SE for Desktop • JRE does not come bundled with Windows or Mac OS X. In Linux, it depends on the distribution. • Java EE for Enterprise • Solid platform for developing backend services • Good compability with legacy systems • Web servers, application servers • Java ME for Mobile • Android uses Java language, but does not support Java ME! • Support today....? 2
SE • Provides APIs and environment for "large-scale, multi-tiered, reliable and secure network applications". • Largely modular components running on application server • Uses heavily annotations • Also XML configurations can be used 3
specifications • Some provider implements an API that meets this specification and can declare it's API as Java EE compliant • Several specifications • RMI, E-mail, Web services, EJBs, Servlets, JSPs .. • Java EE App Server handles securitys, scalability etc so developer can concentrate on business logic 4
and Java Servlet container • GlassFish is a full-blown Java EE app server, including the servlet container • Tomcat is more lightweight, easier to admin • GlassFish is a reference implementation of Java EE specification so it should contain all the latest features 8
choice between IDEs. Also it's possible to work in CLI! • There is no "best" IDE • Some IDEs • Eclipse • Netbeans • IntelliJ IDEA • IBM Rational Developer • Oracle JDeveloper 9
that handles HTTP Requests • extend HttpServlet • It will be instantiated it when needed, and removed from memory when it’s convenient • Server automatically runs servlet as threaded 11
bytecode (Servlets, JavaBeans) in WEB-INF/classes folder • JSP pages • HTML pages • Images (gif, jpeg, png) • JavaScript and CSS stylesheeets • Configuration files in WEB-INF/ folder • Any extra libraries in WEB-INF/lib folder • All these are packaged together by your tool to a single package file with .war extension • .war files may be used as is or packaged into .ear file • Both .war and .ear can be then deployed in any compatible application server – to update just deploy a new .war on top of the old one 13
of the Web • Hypertext Transfer Protocol • Delivers resources on the WWW • Usually delivered by TCP/IP • HTTP client sends a request to HTTP server • Default port is 80 • Resource can be a file or dynamically generated query result 18
• Format • an initial line, • zero or more header lines, • a blank line, • optional message body (this is the resource) • Example <initial line, different for request and response> Header1: value1 Header2: value2 <optional message body> 19
for the request than response. • Request line has three parts • method name, local path to resource, version of http • Example • GET /path/to/file/index.html HTTP/1.0 • Method name can be GET, POST, PUT, DELETE... 20
called the status line • Typical status lines • HTTP/1.0 200 OK • HTTP/1.0 404 Not Found • Status code (200, 404) is computer-readable, reason phrase is human-readable • Status codes • 1xx, information message • 2xx, success • 3xx, redirect • 4xx, client error • 5xx, server error • See all status codes • http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 21
request and response • Header-name: value • HTTP 1.0 provides 16 headers, HTTP 1.1 provides 46 headers • For example client should tell who is making the request • User-Agent: ... • Server should identify • Server: ... 22
Usually the message body includes header lines • Content-type: • MIME type of the resource, for example text/html, image/gif • Content-length • bytes 23
Host: localhost:8080 User-Agent: curl/7.49.1 Accept: */* Content-type: text/plain Content-Length: 9 Some data HTTP/1.1 200 OK Server: GlassFish Server Open Source Edition 4.1.1 X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1.1 Java/Oracle Corporation/1.8) Content-Type: text/plain;charset=ISO-8859-1 Date: Tue, 10 Jan 2017 10:39:58 GMT Content-Length: 10 Some data 25
loads the servlet class • Creates an instance of the class • Calls init – method • Invokes service – method which invokes doGet, doPost ... • Only one instance of the object is created! • When several clients come, several threads are created • When container needs to remove the servlet, it calls destroy-method 26
HTTP GET requests • doPost • for HTTP POST requests • doPut • for HTTP PUT requests • doDelete • for HTTP DELETE requests • init and destroy • to manage resources that are held for the life of the servlet • getServletInfo, which the servlet uses to provide information about itself 28
• To get Form and / or Url parameters • getParameter and getParameterValues • Http Headers can be accessed via getHeader/getHeaders methods • Some of these have own methods • getRemoteUser(), getRequestURI(), getContentLength(), getContentType(), getLocale(), getLocales(), etc • See the API reference for more details 35
can write headers: • addHeader(String name, String value) • To write stuff to client: • getWriter() or getOutputStream() depending on if you want to print encoded text or raw bytes • Remember to set content type! • Also possibility to set error codes 37
character set response.setContentType("text/html; charset=iso-8859-1"); // Create PrintWriter for printing text or OutputStream for bytes PrintWriter out = response.getWriter() ; OutputStream os = response.getOutputStream(); // Redirect browser to immediately load a new page response.sendRedirect("http://www.somecompany.com/") ; 38
Content-Types that are acceptable Accept: text/plain Accept-Charset Character sets that are acceptable Accept-Charset: utf-8 Accept-Encoding Acceptable encodings. See HTTP compression. Accept-Encoding: <compress | gzip | deflate | sdch | identity> Accept-Language Acceptable languages for response Accept-Language: en-US Authorization Authentication credentials for HTTP authentication Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== Cache-Control Used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain Cache-Control: no-cache Connection What type of connection the user-agent would prefer Connection: close Cookie an HTTP cookie previously sent by the server with Set-Cookie (below) Cookie: $Version=1; Skin=new; Content-Length The length of the request body in octets (8-bit bytes) Content-Length: 348 Content-Type The mime type of the body of the request (used with POST and PUT requests) Content-Type: application/x-www-form-urlencoded Pragma Implementation-specific headers that may have various effects anywhere along the request-response chain. Pragma: no-cache Referer[sic] This is the address of the previous web page from which a link to the currently requested page was followed. (The word “referrer” is misspelled in the RFC as well as in most implementations.) Referer: http://en.wikipedia.org/wiki/Main_Page Refresh Used in redirection, or when a new resource has been created. This refresh redirects after 5 seconds. This is a proprietary, non-standard header extension introduced by Netscape and supported by most web browsers. Refresh: 5; url=http://www.w3.org/pub/WWW/People.html User-Agent The user agent string of the user agent User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) Via Informs the server of proxies through which the request was sent. Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) Warning A general warning about possible problems with the entity body. Warning: 199 Miscellaneous warning 40
of data sent from a website and stored on the user's computer • can be used to remember the state of web application, such as shopping cart in an online store. • Session cookie • Destroyed when browser is closed • Persistent cookie • Specific date when expires • Cookies are stored in browser • Structure is really simple: name, value and attributes (expiration date) 43
Host: localhost:8080 User-Agent: curl/7.49.1 Accept: */* Content-type: text/plain Content-Length: 9 Some data HTTP/1.1 200 OK Server: GlassFish Server Open Source Edition 4.1.1 X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1.1 Java/Oracle Corporation/1.8) Content-Type: text/plain;charset=ISO-8859-1 Date: Tue, 10 Jan 2017 10:39:58 GMT Content-Length: 10 Some data 49
type="text" name="name" placeholder="Name" size="40"/> <input type="text" name="email" placeholder="Email" size="40"/> <button type="submit" class="pure-button pure-button-primary">Send</button> </fieldset> </form> Use either get or post The url where servlet is 51
layers 1. Presentation (HTML) 2. Business Logic (Servlet, Java-classes) 3. Database • Layer 1 may validate user input • For example HTML5 Forms, JavaScript etc • Layer 2 always has to do validation • Before entering anything to database, check that user has given valid format. For example "school grade" could be a number between 4 – 10. • Layer 3 should do simple validation • By declaring column types to tables, you create very simple validation to the database 60
"userfeedback" placeholder = "Is this a good course?" pattern = "Yes|Excellent|Magnificent" title = "Feedback must be Yes, Excellent or Magnificent"><br> <input type="submit" value="Save Feedback"> </form> 61
Filter dangerous characters away, for example < and > might be dangerous because of html • If user gives <, replace it with <. And > for > • Watch out for SQL Injection • Use Regex for more advanced validation 62
SQL – statement, you may run into trouble • String sql = "SELECT * FROM Customers WHERE UserId = " + userInput; • If user gives input • "1; DROP TABLE Customers" • Then we will have following SQL: • SELECT * FROM Customers WHERE UserId = 1; DROP TABLE Customers • Solution • Filter unwanted characters – may be not a very good idea • Use SQL parameters (JDBC: Prepared statements) 64
in UNIX environment • Easy way to find a pattern in a string and/or replace it if you want • Very powerful tool • There are several different versions of Regex • Java Regex is very similar to regex found in Perl 65
Pattern can hold • Normal characters • Start and end indicators as ^ and $ • Count indicators like +, - , ? • Logical operators, like | • Grouping with {}, (), [] • Example (Perl-compatible) • /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/ 66
single character /a.c/ matches "abc" or "afc" [ ] Single character that is contained within the brackets /[abc]/ matches "a", or "b" or "c" ^ Find from the beginning of the string /^a/ matches "aku ankka" $ Find from the end of the string /a$/ matches "aku ankka" | OR /cat|dog/ matches "dog" or "cat" ^ NOT (when used in middle of pattern) /a^aa/ matches "aba" {n,m} Matches min n, max m /a{1,3}/ matches "a", or "aa", or "aaa" * Matches 0-n /a*/ ? Matches 0-1 /(hello)?/ + Matches 1-n /a+/ 68
to reuse it • String has also matches(String regex) method but it will create the regex each time • Example public class RegexExample { public static void main(String[] args) { if("tomaattihellurei".matches("tomaatti.*")) { System.out.println("We found it!"); } else { System.out.println("nope"); } } } 81
1.1 • Platform independent, Database independen • Wide range of data sources possible: • SQL, spreadsheets, flat files • JDBC API • Estabish a connection to database • Execute SQL • Process the results 85
try { // 1. Register driver. Driver String is given to you by the driver // documentation. Driver (.jar) must be in classpath! Class.forName("com.mysql.jdbc.Driver"); // 2. Connect to database. Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test"); // 3. Some SQL Magic. Statement statement = conn.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM Clients"); // 4. Handle Result while (rs.next()) { result += rs.getString("Firstname") + "<br>"; } // 5. Close the connection rs.close(); statement.close(); conn.close(); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } return result; } 87
a feature used to execute the same or similar database statements repeatedly with high efficiency • Simple way to protect against SQL injection String sql = "UPDATE table1 set one = ?, two = ?"; PreparedStatement preStmt = con.prepareStatement(sql); preStmt.setInt(1, 123); preStmt.setString(2, "myNewValue2"); preStmt.executeUpdate();
App), opening when loading, closing when destroying • Problem: one connection is reserved for the whole lifespan of the app, what if you have multiple web apps doing the same thing? • In Servlet init and destroy – methods • Problem: one connection is reserved for the whole lifespan of the servlet, what if you have multiple servlets doing the same thing? • In doGet or doPost • Problem: creating and destroying the connection is expensive • Solution: Connection Pooling 98
you by the app server (Glassfish) • You will have to create new connection pool and set a JNDI name for it • Java Naming and Directory (JNDI) service allow to look up services • Connection Pool is a service • App connects to JNDI and JDNI connects to the connection pool • It's possible to configure the connection pool and the app does not know about it! • To configure the 1) connection pool and 2) jndi – name, use glassfish admin web page or cli • Note: in Glassfish 4.1.1 the web admin is broken, use 4.1.0 or Payara 99
that describes management of relational data in apps using Java • The reference implementation for JPA is EclipseLink • http://www.eclipse.org/eclipselink/#jpa • Basic idea is simple, save objects to relational database 107
under your classes/ dir • This file declares for example what database (derby, mysql, ...) you are accessing 2. Annotate your POJO – class so that it JPA knows which table is used for storing the objects from this class 3. Implement the saving / retrieving using javax.persistence classes 108
em.getTransaction().begin(); Person p = new Person(); p.setFirstname("Mickey"); p.setLastname("Mouse"); // p.setId(7); em.persist(p); em.getTransaction().commit(); em.close(); 111
will create a table for the entity • By default table name is class name • You can change this by using @Table annotation • Instances of the class will be a row in the table • All entity classes must define a primary key • You can auto-generate the primary key in the database using @GeneratedValue annotation 112
// Each pojo will have a primary // key which you annotate // by using @Id @Id @Column(name = "id") private int id; @Column(name = "firstname") private String firstName; @Column(name = "lastname") private String lastName; 113
// Each pojo will have a primary key which // you annotate // by using @Id @Id // Define strategy how to save this to db // IDENTIFY allow auto increment on demand in Derby/MySQL @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "firstname") private String firstName; @Column(name = "lastname") private String lastName; 114
defined in JPA specification • Based on SQL syntax • You work with classes and objects instead of records and fields • Template • SELECT ... FROM ... WHERE ... ORDER BY ... • Minimal JPQL Query • Select object FROM Employee as object • The FROM clause specifies query variable (like loop variable in programming) 115
code, EntityManager was declared as an attribute • When several threads are accessing the EntityManager at the same time, thing can go wrong • Usually the architecture is following • jsp (view) -> servlet (controller) -> EJB/JPA (Model) -> DB • When using the JPA in EJB, attributes are thread safe and you don't have to worry about it. Also transactions are handled for you. • In servlet, you will have to look up the EntityManager 121
in 2000 by Roy Fielding in his theses: • http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_s tyle.htm • Way of providing interoperability between computer systems • Does not restrict communication to a particular protocol • Http Web Service API that follows REST principals are called RESTful APIs
2. Stateless 3. Cacheable 4. Layered system 5. Code on demand (optional) 6. Uniform Interface 1. Identification of resources 2. Manipulation of resources through representations 3. Self-descriptive messages 4. Hypermedia as the engine of application state
stateless in nature • No session data stored on the server • Each request from client to server must contain all the information necessary to understand the request
multiple architecture layers • Restrict knowledge of the system to one layer • Client -> Cache -> middleware -> server -> db • For example the middleware can be a cache • Client cannot tell if it's connected to end server or middleware
1. Identication of resources • Every resource has unique URI 2. Manipulation of resources through representations • Representation can be in various formats and is de-coupled from the identification 3. Self-descriptive messages • Each message has enough information to describe how to process the message, for example by using content-type 4. Hypermedia as the engine of application state (HATEOAS) • Server respondes with a set of links what other actions are available
own unique URI • http://company.com/employees/ • URI is an identifier • Result is the resource • Notice that resource is not 'storage object', it's entity • Resources are just some item that can be accessed
various formats, like HTML, XML, JSON, SVG, PNG • RESTful apps can send accept header where it defines what kind of data it can handle • Server can send Content-type where it defines the type of the resource • De-coupling the representation of the resource from the URI is key aspect of REST
is a message • Message should be self-descriptive • Message contains the body and metadata • In Restful, you use HTTP GET, PUT and HTTP Headers for this
for the API • Include links to the responses • What other • REST client needs no prior information about the service • REST client enters app by simplex fixed URI • All future actions may be discovered within the response • Nearly ALL popular WEB APIs violate HATEOAS
URI to each resource • Categorize if resources are needed to view and/or update • All HTTP Get should be side-effect free • Put hyperlinks to resource representation to enable clients to drill down for more information • Specify the format of response data • Create documentation how to use the service
just use browser • For more complicated services, you can use tools called cURL: http://curl.haxx.se/ • Via command line you can create HTTP GET, POST, DELETE, PUT commands: • curl GET http://localhost:8080/rest/cars • curl POST –d "{brand: 'skoda'}" http://localhost:8080/rest/cars • curl DELETE http://localhost:8080/rest/cars/0
like ticket, user or group • Identify what actions can user apply to them • GET /employees/ • GET /employees/1 • POST /employees • PUT /employees/1 • DELETE /employees/1 • Use plurals in the endpoint name! • So do not: employee/1 vs employees/ • person / people vs goose / geese
updated resource to the client • In case of HTTP POST, return 201 and include Location Header that points to the URL of the resource • In case of HTTP DELETE • 204: no response body • 200: response body with the deleted resource
Created (HTTP POST) • 204 No Content (For example Delete) • 400 Bad Request • 401 Unauthorized • 403 Forbidden • 404 Not Found • 405 Method not found (when method is not allowed for authenticated user) • 409 Conflict • 410 Gone (older apis) • 429 Too many requests
indentation and whitespaces it's hard to detect the structure of the response • Extra cost is data transfer, but it is really small cost if you use gzip
Filtering • GET /employees?firstname=jack • Sorting • GET /employees?sort=firstname • Searching • GET /employees?q=jack • Combining • GET /employees?q=jack&sort=salary
should not depend on cookies or sessions • Each request should have some sort of authentication • By using SSL, you can send access token via HTTP Basic auth
• Well if you have really good API you don't need documentation (HATEOAS) • See GitHub • https://developer.github.com/v3/gists/#list-gists • See TAMK Open Data • http://avoindata.tamk.fi/en/
• Can be included in URL or in Header • Stripe uses version in URL and in header • curl https://api.stripe.com/v1/charges \ -u sk_test_BQokikJOvBiI2HlWgH4olfQ2: \ -H "Stripe-Version: 2017- 01-27" • https://stripe.com/docs/upgrades#api-changelog
can tell that the client has send too many requests in a given amount of time • Send headers like • X-Rate-Limit – number of allowed requests in current period • X-Rate-Remaining – number of remaining requests in the curren period • X-Rate-Limit-Reset – number of seconds left in the period
creating REST services • Uses annotations, introduces in Java SE 5 • Simplifies the process of implementing the services • JAX-RS 1.0 is a official part of Java EE 6 • JAX-RS 2.0 is a official part of Java EE 7 • In Glassfish no need to install anything • Can be downloaded separately (Jersey)
the reference implementation from Oracle • http://jersey.java.net/ • RESTEasy, JBoss's implementation • http://www.jboss.org/resteasy • Apache CXF, an open source Web service framework • http://cxf.apache.org/docs/restful-services.html • Restlet, created by Jerome Louvel, a pioneer in REST frameworks • http://www.restlet.org/ • Apache Wink, Apache Software Foundation Incubator project, the server module implements JAX-RS • http://incubator.apache.org/wink/
Java source code • Built-in annotations • @Override, @Deprecated .. • Possible to create custom annotations • @CustomAnnotation("someString") • Annotation are often used by frameworks by giving special behaviour to your code • Annotation are parsed using annotation processors • These can create for example additional Java code from the annotations
and plain old Java object (pojo) can be transformed to an resource that is accessed from URL • @Path • @GET, @PUT, @POST, @DELETE • @Produces • @Consumes
Java class will be hosted at the URI path "/helloworld" @Path("/helloworld") public class HelloWorldResource { // The Java method will process HTTP GET requests @GET // The Java method will produce content identified by the MIME Media // type "text/html" @Produces("text/html") public String doSomething() { String result = "<html><head><title></title></head><body><h1>Hello!</h1></body></html>"; return result; } }
each new request • Life-cycle of root resource classes is per-request • Very natural programming model where constructors and fields can be utilized without concern for multiple concurrent requests to the same resource • Possible to change the life cycle to for example @Singleton • Only one instance per jax-rs application
http://localhost:8080/TestApp/rest/helloworld @ApplicationPath("/rest") public class MyApplication extends ResourceConfig { public MyApplication() { // Scanning packages for resources! packages("fi.company.resources"); } }
-X GET http://localhost:8080/Lab03/rest/users @GET @Produces("application/json") public String getUsers() { return "{result: 'HTTP GET all'}"; } // curl -X GET http://localhost:8080/Lab03/rest/users/1 @GET @Path("/{id}") @Produces("application/json") public String getUser(@PathParam("id") int id) { return "{result: 'HTTP GET with id ='" + id + "'}"; } // curl -X DELETE http://localhost:8080/Lab03/rest/users/1 @DELETE @Path("/{id}") @Produces("application/json") public String deleteUser(@PathParam("id") int id) { return "{result: 'HTTP DELETE with id ='" + id + "'}"; } }
a data exchange format widely used in web services and other connected applications • JSR 353 provides an API to parse, transform, and query JSON data • There are several libraries for JSON parsing, but JSR 353 is preinstalled in Java EE • Also JAXB for automatic conversion between POJO and JSON
and arrays • An object is a set of name-value pairs {} • An array is a list of values [] • JSON is often used as a common format to serialize and deserialize data in applications • RESTful web services use JSON extensively as the format for the data inside requests and responses • The HTTP header used to indicate that the content of a request or a response is JSON data is • Content-Type: application/json
methods to create JSON readers, writers, builders, and their factory objects. JsonGenerator Writes JSON data to a stream one value at a time. JsonReader Reads JSON data from a stream and creates an object model in memory. JsonObjectBuilder JsonArrayBuilder Create an object model or an array model in memory by adding values from application code. JsonWriter Writes an object model from memory to a stream. JsonValue JsonObject JsonArray JsonString JsonNumber Represent data types for values in JSON data.
JSON directly to generic objects, and requires reading document at once • If documents are large, or efficiency is the key, might be better to use Streaming API • Create a JsonParser, and parse a stream or String, • You can pull one event at time • Events are basically data structures, and you can do different handling based on data field name • When you need more events, you can say parser.next() • You can also write data using JsonGenerator
'{"id": 1, "name": "jack"}' http://localhost:8080/TestProject/rest/test/json {"id":1,"name":"jack"} > curl -H "Content-Type: application/json" -X POST -d 'THIS IS NOT JSON' http://localhost:8080/TestProject/rest/test/json exception The Content-Type entity- header field indicates the media type of the entity- body sent to the recipient
write XML from Java? • Java API for XML Processing (JAXP) • Simple API for XML (SAX) • Event driven, only read • DOM Object Model (DOM) • Creates tree object in memory, read and manipulate • Java Architecture for XML Binding (JAXB) • Unmarshal xml file to Java objects • Marshal Java objects to xml file • JAXB available in Java SE 6 ->
class ClientApp { public static void main(String [] args) { Book book = new Book("Tuntematon Sotilas"); sendToServer(book); } } <book> <title> Java 8 new features </title> </book> Client Computer ClientApp.java Book.java
Java developers • marshal Java objects to XML • unmarshal XML back to Java objects • JAXB is part of Java SE • Implementation is done by using annotations • Package: javax.xml.bind.annotation.*; • @XmlRootElement, @XmlElement • Separate tools available • xjc -> schema to classes • schemagen -> classes to schema
MOXy library • In Glassfish this is bundled! • In Desktop you can use • jaxbMarshaller.setProperty("eclipse.media-type", "application/json" ); • But usually you don't need to because of JAX-RS Client API that handles automatic conversion of JSON to POJO and back.
and back • http://www.eclipse.org/eclipselink/#moxy • JSON mapping differentiates datatypes • 1 => int, "hello" => String, true => boolean • JSON does not use attributes, @XmlAttribute is marshalled as an element • No Root element • See: • http://www.eclipse.org/eclipselink/documentation/2.4/moxy/json 003.htm
*;q=0.8 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8,fi;q=0.6 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36 HTTP GET Request for a file books.xml
Response to a succesful GET, PUT or DELETE 201 Created Response to a POST that results a creation 204 No Content Succesful request that won't return a body, like for example DELETE (DELETE can be 204 or 200) 404 Not Found Response when entity not found 400 Bad Request Response when request is incorrect 500 Internal Server Error Response when for example database connection fails
text/plain Date: Tue, 24 May 2016 07:36:51 GMT Server: GlassFish Server Open Source Edition 4.1 X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1 Java/Oracle Corporation/1.8) We failed to look for the entity.
29 May 2016 09:04:16 GMT Location: http://.../rest/test/response/1 Server: GlassFish Server Open Source Edition 4.1 X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1 Java/Oracle Corporation/1.8)
returned in responses from an HTTP server under two circumstances: • Ask a web browser to load different web page (URL Redirect). HTTP Status code should be 3xx redirection • Provide information about newly created resource. Http Status code should be 201
State, is a constraint for REST • REST client enters app using fixed URL • All future actions can be discovered within resource representations • JAX-RS 2.0 provides Link classes for the links provided by the server
elements, at root level (class definition) or in method level • Class definition needs to have path, method definitions may have extra path to add • Paths are added to web app root context • http://server/webapp/resource/helloworld • Path may contain URI path templates, containing parameters • @Path("/users/{username}")
• Can have more than one value: paramA=val1,val2 • No encoding and decoding & in XML • Can be anywhere in url, not just end • More readable? • Disadvantages • When submitting a FORM, query param is generated
the MIME media types of representations a resource can produce and send back to the client • Can be defined at class level as default, or method level to override • Legal values are any mime types your implementation supports, typical choices are text/html, text/xml, text/plain
on the internet • IANA official authority for th standardization • Composed of • type/subtype; optional parameters • Example • text/html; charset=UTF-8 • text/xml • text/plain • application/json • Top-level types: • application, audio, example, image, message, model, multipart, text, video
http://www.ietf.org/rfc/rfc4627.txt • For XML, use either text/xml or application/xml • http://www.rfc-editor.org/rfc/rfc3023.txt • "If an XML document -- that is, the unprocessed, source XML document -- is readable by casual users, text/xml is preferable to application/xml. " • "application/xml is preferable when the XML MIME entity is unreadable by casual users. "
ServletContext context; @GET @Path("/image") @Produces("image/png") public byte[] getImage() { try { File configFile = new File(context.getRealPath("image.png")); return Files.readAllBytes(configFile.toPath()); } catch(Exception e) { e.printStackTrace(); throw new WebApplicationException(404); } } ... JAX-RS provides @Context for injecting variety of resources in REST By using the ServletContext, we can get a real path to a image file New I/O api introduces in Java 7 Serve 404 if not found