Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, May 28, 2014

Websockets in Java EE 7 with wildfly

In the past few weeks I've trying the websockets technology introduced in JEE 7 and I would like to share you how to develop a simple example of it, for those who don't know what is about websockets, here is a brief introduction.

Wikipedia says "WebSocket is a protocol providing full-duplex communications channels over a single TCP connection", this means that in a client-server communication the client as the server can send a message leaving behind the request-response protocol, where the exchange is always initiated by the client (usually a browser) and the server cannot send any data without the client requesting it first.

It also says "WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application", websockets was introduced in the clients or browsers since the html5 specification, and in the Java servers since the JEE 7 version and the specification  JSR 356.

If you want to know more about websockets refer to the following links:

I'm going to use the wildfy 8 as server the open source version of jboss, you can download it from here http://wildfly.org/downloads/, and as for the IDE I'm going to use JBoss tools, you can download it from here http://tools.jboss.org/downloads/ .

To set up wildfly with eclipse you can use the following link for instructions:  http://planet.jboss.org/post/getting_started_with_jboss_tools_and_wildfly_tech_tip_5

Once you have everything installed and integrated lets start creating a websocket application.
lets create a new project, select new project and from the options presented choose dynamic web project, set the name of the project as websockets and the target runtime to wildfy 8.

The Java API for WebSocket consists of the following packages.

  • The javax.websocket.server package contains annotations, classes, and interfaces to create and configure server endpoints.
  • The javax.websocket package contains annotations, classes, interfaces, and exceptions that are common to client and server endpoints.

Now lets create a new server endpoint class, this class will receive the messages from the client and also it could send messages to the client.


From the class above notice the @ServerEndpoint annotation, it indicates the class will be a socket endpoint, it takes a string ("example") as parameter this will be the URI of the endpoint.

The methods of the class are annotated with @OnOpen, @OnMessage, @OnClose annotations, these indicate the lifecycle of endpoint here is a brief description of them:

AnnotationEventExample
OnOpenConnection opened
@OnOpen
public void open(Session session, 
                 EndpointConfig conf) { }
OnMessageMessage received
@OnMessage
public void message(Session session, 
                    String msg) { }
OnErrorConnection error
@OnError
public void error(Session session, 
                  Throwable error) { }
OnCloseConnection closed
@OnClose
public void close(Session session, 
                  CloseReason reason) { }




The endpoint now is ready to start a conversation so deploy it in wildfy and lets create a html client to communicate with this endpoint.


In the previous html file the only thing to notice is the simple script that creates a connection to the endpoint, from the url "ws://localhost:8080/websockets/example" used check the name of the application and the URI of the endpoint.

If you open the html file on browser that supports web sockets you should see the message "Web Socket is connected!!" and in the server you should see in console the message "Open session:...". This indicates that the communication has been established between the client and the server.

To now more about the WebSocket javascript interface the following link will help:
http://www.w3.org/TR/2011/WD-websockets-20110419/

Let's create a message and send it from the client to the server. To do this let's just add the following function in the javascript section of the html file.


With this function the ws variable calls the sends() method and sends the message to the server.
To call this function just add a html link and call it.


Let's test it click on the link and you should see the following message on server's console: "Received : Message to server from client, session:..."

Now to simulate a request-response communication lets return a message from the @OnMessage method in the websocket endpoint in the server.


Deploy it and test it, you should get the following sequence of messages:

  1. Browser displays "Web sockect is connected".
  2. After calling send(), server console diplays: Received : Message to server from client, session:
  3. Browser displays "Received, Response from the server"
To demonstrate full duplex communication lets send messages from the server without any request from the client. To do this, lets add and asynchronous task to send messages.



Notice that the @Stateless annotation has been added to the endpoint, it is required to send messages asynchronously, with this now the endpoint is also an EJB, also the endpoint makes use of the ManagedExecutorService resource, it takes runnables and executes them, this is done on the @OnOpen method so when the conversation starts the runnables are set.
In the runnable we wait for 10 seconds and then sends a message to the client this is done without receiving any previous message and this is repeated 3 times so during 30 seconds, your browser should be receiving the message "Received, Message from server".

With this is demonstrated the full-duplex communication this is a message can be sent without any prior message or request.

Well this is basically a simple example that demonstrates how web sockets work, in further post I will keep showing more of their functionality.  





Monday, January 20, 2014

RESTful web services with jetty and jersey

Recently I was thinking if there is a way to start a web server in java just as easy as it is in node.js, if you don't know node.js you can check this link nodejs.org, so in node you just write a few lines and you have a server like this:


I thought that with something like this you can easily test your code without the burden of deploy it, and also saving some resources. 

So I start looking if there is something similar in java and I found several projects to start a web server or a minimal server, but I decided to go with jetty www.eclipse.org/jetty, so I'm going to show you how to run some restful web services using jetty. 

Also I'm going to use jersey jersey.java.net which simplifies the development of RESTful Web services and their clients in Java.

So you can download the jars from these projects or configure them through maven to your project to start using them, in these links www.eclipse.org/jetty , jersey.java.net you can check the instructions to do it.

So to create a web server with jetty is as easy as the following code:


If you run the code and check the http://localhost:8080/hello url you can see that your servlet is running, so basically in the code you create a Server object and set the port the Servlets and the servlets to run and that's it.

With jetty you can do much more than this, but for the purpose of this blog I will no go further, you can check the jetty documentation.

The following would be to create and deploy the RESTful web services, now we will use jersey to this.

The first thing to do is to create the services that we will deploy, for the example I will create two services one using JSON and other using XML, I will create two objects used to transfer the data.



In the classes above you can see two classes Employee with a nested class Address and Student, the only thing to notice from these classes are the annotations @XmlRootElement and @XmlAttribute, these annotations are used to do the parsing from object to the protocol used (XML, JSON) and from protocol to object.

The following would be to create the classes for the services.




The classes above use the standard Java EE specification for RESTful web services they use the @Path annotation at the top level to set the service path and each method use the @GET, @POST annotations to describe the type of service and the @Produces annotation to set the type of protocol to use.

The method getStudent of the class XMLStudentSvc has also the @Path("/student/{name}")  this specifies a path for this method, also note that it receives a parameter named "name" through the path and this parameter will be mapped to the parameter of the method.
For more about how define RESTful web services check the specification https://jcp.org/en/jsr/detail?id=311

Another thing to notice is that both classes are in a package called "rest", so the following to do would be to deploy these services in jetty as long as the jersey configuration.

This is the class for the server:



See in the class above all what it needs to configure jersey, a ServletHolder object is created to set the parameters, note that is indicated the package where the services are located and jersey will automatically deploy them. The ServletHolder object is passed to a ServletContextHandler object, and that's it with this the services should be up and running.

The last thing to do is to create a client for our services, for the client I will use jersey to help.

This is the client for the JSON service:


The client will call two methods, the first will be to the GET method and it uses the url with the path specified for this method ("http://localhost:9999/employee/getEmployee"), this method returns a response in JSON, then this response is unmarshal to a object with the call to "response.getEntity(Employee.class)".

If the JSON response is needed instead of the actual object all what is need to do is change the type to String in the unmarshal "response.getEntity(Employee.class)".

The other method specified in this client is the POST method this call doesn't return a thing,  it uses the url with the path specified for this method ("http://localhost:9999/employee/postEmployee") and it sends back the same object the client is receiving, you should see an output in the server since the service method is printing the object it is receiving.

This is the client for the XML service:


It is almost the same as the JSON client, the only difference is that a parameter is include in the url "http://localhost:9999/xmlServices/student/James", because the service is expecting it.

After running these examples I notice how easy and fast is to run the services and the few resources that required, I'm using at most 30Mb of memory.

Monday, January 6, 2014

JDK 7 securtiy issues with web start

With the latest updates java increased its security and new features were added to the web start applications, so basically if you have a web start application and is not properly signed it will not run over the latest version of the JVM (1.7.45), giving  you a warning like the following, and more errors.



This is what happened to me and I will explain what I had to do to get over this new security requirements and kept your application running.

The first step is get a code signing certificate with an certificate authority (CA), there are different CA and here are some of them:
The process to get the certificate is the following:

First you will have to request the CA for a certificate, and for this you will need a Keystore and a Certificate Signing Request (CSR), these are generated with the keytool.

For generate the keystore use the following command:

keytool -genkey -alias Alias -keyalg RSA -keysize 2048 -keystore Keysotre.jks

And for generate the CSR use the following command:

keytool -certreq -alias Alias  -file Cert.csr -keystore Keysotre.jks 

Each command will ask you for a password, after generating these files you will send the CSR file to the CA.

After the CA generates the certificate, it will send you the certificate, it is a file with probably one of the following extensions: PEM, DER, P7B, PFX, depending in the type of certificate, you can find more about the certificate types in this link: www.sslshopper.com/ssl-converter.html

Once you have the certificate with you, you will have to import it using the keytool, with the following command:

keytool -import -trustcacerts -alias Alias -file CAcert.p7b -keystore Keysotre.jks

Make sure you use the same keystore file used in the generation of the CSR file. You can find more information of the keytool command in the following link:

With this the jars files can be signed using the jarsigner command:

jarsigner -keystore Keysotre.jks -storepass password file.jar Alias

With these steps the jar file gets signed, but there is much more about this process of signing a jar.

Before the new features that were added in the latest releases of the JVM (1.7.XX) this was all you have to do to meet the security requirements for a web start application just sign the jars of the application.

These are some of the new features:

The META-INF/MANIFEST.MF file of the jar files must have the following attributes to grant permissions

Manifest-Version: 1.0
Permissions: all-permissions
Codebase: https://example.com

In this link you can find the new attributes of the Manifest file http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/manifest.html


Another feature is to sign the JNLP file, the oracle documents says the following in order to sign a JNLP file: 

"To create a signed JNLP file you don't sign the JNLP file itself, but you include the JNLP file inside the directory structure before the JAR file is created and then signed. The JNLP file must be named APPLICATION.JNLP and is included in the JNLP-INF subdirectory. The JAR file is then created and signed in the usual manner. When a web start application is started, the JNLP file used must be identical to the JNLP file in the signed JAR in order for the application to run".

You can find more information about signing JNLP files in the following link: http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/signedJNLP.html

Well these are some of the new requirements in order to run properly a web start application, I hope with this blog you can now have an idea of what to do if your web start application does not run because of security issues.



Monday, August 19, 2013

JAVA EE SERVERS

JAVA EE SERVERS

I recently notice that Jboss changed the name of its community server version from JBoss AS to Wildfly. It took me some time to understand what was all the fuzz about, first I thought it was a new server but then I finally get it, Red hat was just making a bigger distinction between the JBoss supported (Jboss EAP) and community (now Wildfly) version nothing else, just like red hat and fedora.
You can find more information about it in the following link:

With this I realized that there are plenty versions of JEE servers in the market and is hard to understand for a non expert or a newbie which one does what and what is the difference between all of them, so I decided to write a post about the JEE Servers that are available, just to list some of its features and not a benchmark because that would require expertise in each server and I don't have that.

Before getting into serves here is a list of the specifications that a full Java EE 7 server should have, I will refer to it in a future as figure 1.







































Apache Tomcat 


Apache tomcat is an open source web server, it has many years in the market and is very common to find implementations using it.
Tomcat is a web server because it supports the Java Servlet and JavaServer Pages and others related to them, the table below shows the specification version supported by the tomcat version.

Tomcat home page: http://tomcat.apache.org/



Jetty


Jetty is a open source web container, it an Eclipse project and is hosted entirely at the Eclipse Foundation. It is known for be a lightweight server and be easily embedded in devices, tools, frameworks, application servers, and clusters. It has support for SPDY, WebSocket, OSGi, JMX, JNDI, JAAS and many other integrations.

The specifications that jetty has support are:
















More information about jetty can be found in the following link:


Apache TomEE




Apache TomEE is an open source Java EE 6 Web Profile server, it is based on Tomcat with EE features, that's the reason of its name “TomEE” pronounced as "Tommy”. It is practically new its first release came out in April of 2012, but it is gaining popularity and it has the support of the apache community.

TomEE server supports more JEE specifications than tomcat such as Enterprise JavaBeans, Java Persistence API (JPA), and others. It comes in different packages each with different specifications, the following table shows a comparison of the different packages.



















TomEE uses other project to provide the specifications:
  • CDI - Apache OpenWebBeans
  • EJB - Apache OpenEJB
  • JPA - Apache OpenJPA
  • JSF - Apache MyFaces
  • JSP - Apache Tomcat
  • JSTL - Apache Tomcat
  • JTA - Apache Geronimo Transaction
  • Servlet - Apache Tomcat
  • Javamail - Apache Geronimo JavaMail
  • Bean Validation - Apache BVal
  • JAX-RS - Apache CXF
  • JAX-WS - Apache CXF
  • JMS - Apache ActiveMQ
  • Connector - Apache Geronimo Connector


Use the following link for more information:


Glassfish


Glassfish is an open source Java EE application server sponsored by Oracle, it works as a reference implementation of the latest Java EE specifications. Its latest version Glassfish 4 supports the Java EE 7 specifications, so it should support all the specifications shown in figure 1.

 It makes use of some others opens source projects to implement the specifications:












Also Oracle provides a commercial version of this server which offers support. The following links will provide more information.



Geronimo



Apache Geronimo is an open source server, it is Java EE 6 certified and it is based in OSGI offering a more modular design.

Geronimo also uses other source projects to implement the specifications:
  • OpenEJB
  • OpenJPA
  • ActiveMQ
  • Tomcat
  • Jetty
  • TranQL


In the following link you can find a list of all the components or projects used in geronimo:

Geronimo home page:





JBoss Wildfly and Jboss AS



Wildfly formerly JBoss AS is an open source Java EE server now sponsored by Red Hat. Wildfly is still in alpha version but it would've be the Jboss AS 8 version. It supports the Java EE 7 specifications shown in “figure 1”, and it is based in OSGI offering a more modular design.

It makes use of some others opens source projects to implement the specifications, such as:


Red hat also offers a commercial version of Wildfly named JBoss EAP and it has all the benefits of a commercial product such as support, extra tools and many others. Its fees are not cheap it will probably cost tens of thousand of dollar, so be careful at the time of choosing a commercial server, the following link is a calculator from RED HAT so you can get an idea about the fees http://www.redhat.com/promo/eap_calculator/

Some of the links where you can find more information about Jboss are:



Weblogic



Oracle WebLogic Server is a commercial Java EE application server, its latest version is weblogic 12 is a Java EE 6 Full Profile, so the Java EE 6 specifications are supported. The following image shows the platforms supported by Weblogic.


















As it is commercial counterpart from redhat, oracle provides support and many tools for maintain the server, but is not a cheap server it will probably cost tens of thousand of dollar also. The following link is a pdf about the costs so you can get an idea about the fees:

Some of the links where you can find more information about Weblogic are:


Websphere 


IBM WebSphere Application Server is a commercial Java EE application server, its latest version is WebSphere 8, it is JEE6 certified based in OSGI offering a more modular design, some of the features they include are:

● Enterprise JavaBeans (EJB) 3.1
● Java Servlet 3.0
● Contexts and Dependency Injection for Java (CDI) 1.0
● Bean Validation 1.0
● Java Architecture for XML Binding (JAXB) 2.2
● Enterprise Web Services 1.3
● Java API for XML-Based Web Services (JAX-WS) 2.2

The Operative Systems supported are:




















As it is commercial as Weblogic and JBoss EAP, it comes with all the benefits from a commercial product but also its fees, the following image shows how much could it cost to have Webshpere:








In the following link more information about websphere can be found:

FUJITSU

FUJITSU Software Interstage Application Server is a commercial server and support standards such as Java EE, Web Service, and CORBA. Interstage Application Server component technologies and development frameworks.

It has support for the following features:
























The OS supported are:
  • Microsoft Windows Server 2008 R2
  • Microsoft Windows Server 2008
  • Microsoft Windows Server 2003 R2
  • Microsoft Windows Server 2003
  • Windows Azure Guest OS 1.18~(4)
  • Windows Azure Guest OS 2.6~(4)
  • Red Hat Enterprise Linux 6
  • Red Hat Enterprise Linux 5
  • Solaris 11
  • Solaris 10

For more information about fujitsu server go to the following links:

JEUS

TmaxSoft's JEUS is a commercial Java EE certified application server. It supports the following specifications:



















JEUS offer support for clustering, load balancing and has tools for the development and administration process.

For more information about JEUS go to the following link:




JONAS


OW2 Jonas is an open source Java EE application server, it is Java EE 5 certified and has a Java EE 6 preview version, is based in OSGI offering a more modular design.

Jonas use other opens source projects to implement the specifications, and since it is based on osgi different options and you can choose what project to use:















OW2 do not offer a commercial version of Jonas server but it offers a support subscription for professional support and training, it has tools for managing and clustering but they are for free.

In the following link more information about JONAS can be found:



Resin 


Resin is a commercial Java application server by Caucho, it supports the Java EE 6 Web Profile. It supports Servlet, JSP, JSTL, EJB, Candi (Java CDI), JSF, JPA, and more. It is a lightweight server designed with CDI.It has Java monitoring and OS monitoring facilities available via built-in console or third party applications via JMX and REST



















It has support for clustering and tools for application deployment, distributed caching, load balancing and messaging, and so on.

Resin can be used with Amazon Web Services for cloud deployment. More information about resin and amazon can be found in the following link:

The prices of the licenses of resin can be found in the following link:

Resin has an open source version http://resin.caucho.com/ , the differences between the open source and the commercial version, is the amount of tools offered by the commercial version, in the following link a comparison between the two versions can be found:

For more information about resin go to the following link:

Well these are the most known options that can be found for a JEE server, I try to list some of its features and useful links. As I said before this is not a benchmark, but for choosing one server first you have to check if you want a commercial option or open source option, then check what options are among between your budget and then evaluate these options, its features, the support, if it is open source the community support, the documentation and so on.

And finally here is a link where you can find which servers are compatible with each JEE profile:


Sunday, August 4, 2013

Java Collections Framework Part 7 - Collections Utility

Collections Utility class
The java.util.Collections class is an utility class, an utility class defines a set of static methods that perform common operations, all the methods of Collections are public and static.

The java API says about the Collection class “This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends”.

The Collections class has methods for changing the order of lists:

void reverse(List<?> list): Reverses the order of the elements
void rotate(List<?> list, int distance): Rotates the elements in the specified list by the specified distance.
void shuffle(List<?> list): Randomly permutes the list elements
void shuffle(List<?> list, Random rnd): Randomly permutes the list using the randomness source rnd
<T extends Comparable<? super T>> void sort(List<T> list): Sorts the supplied list using natural ordering
<T> void sort(List<T> list, Comparator<? super T> c): Sorts the supplied list using the supplied ordering
void swap(List<?> list, int i, int j): Swaps the elements at the specified positions

It has methods for changing the contents of a list, the copy() transfers elements from the source list into an initial a the destination list, the fill() replaces every element of a list with a specified object and replaceAll() replaces every occurrence of one value in a list with another.

<T> void copy(List<? super T> dest, List<? extends T> src): Copies all of the elements from one list into another
<T> void fill(List<? super T> list, T obj): Replaces every element of list with obj
<T> boolean replaceAll(List<T> list, T old, T new): Replaces all occurrences of old in list with new.

It has methods for finding elements in ordered collections:

<T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll): Returns the maximum element using natural ordering.
<T> T max(Collection<? extends T> coll, Comparator<? super T> comp): Returns the maximum element using the supplied comparator
<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll): Returns the minimum element using natural ordering
<T> T min(Collection<? extends T> coll, Comparator<? super T> comp): Returns the minimum element using the supplied comparator
<T> int binarySearch(List<? extends Comparable<? super T>> list, T key): Searches for key using binary search
<T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c): Searches for key using binary search
int indexOfSubList(List<?> source, List<?> target): Finds the first sublist of source which matches target
int lastIndexOfSubList(List<?> source, List<?> target): Finds the last sublist of source which matches target

Some methods require that the collection should be ordered before using them otherwise their outcome will make no sense, this is the case of the binarySearch(), if the list is not ordered then the binarySearch() will return a wrong value, Example:


In the example you can see how the collection is ordered before using the binarySearch() method.

Some methods are overloaded with a version that takes a Comparator, in this case the type of the Collection doesn't have to implement the Comparable interface, Example:


In the example you can see that the List is of type Person and it doesn't implements the Comparable interface but at the time to order the collection and search it, a Comparator instance is used it.

The Collections class has methods for creating collections:

<T> List<T> emptyList(): Returns the empty list (immutable)
<K,V> Map<K,V> emptyMap(): Returns the empty map (immutable)
<T> Set<T> emptySet(): Returns the empty set (immutable)

These methods can be used to indicate there are no values, the collections returned by this methods are immutable, this means no elements can be added to them.

Example:

The previous example will throw a java.lang.UnsupportedOperationException at the time the new element was added.

There are also methods for creating collections containing only a single element.

<T> Set<T> singleton(T o): Returns an immutable set containing only the specified object.
<T> List<T> singletonList(T o): Returns an immutable list containing only the specified object.
<K,V> Map<K,V> singletonMap(K key, V value): Returns an immutable map, mapping only the key K to the value V

The collections returned by this methods are also immutable and no elements can be added to them.

Example:


The previous example will throw a java.lang.UnsupportedOperationException at the time the new element was added.

There is a method that creates a list containing a number of copies of a given object.

<T> List<T> nCopies(int n, T o): Returns an immutable list containing n references to the object o

Sometimes a collection implementation is not synchronized, in order to make a collection thread safe the Collections class provides methods for this purpose:

<T> Collection<T> synchronizedCollection(Collection<T> c);
<T> Set<T> synchronizedSet(Set<T> s);
<T> List<T> synchronizedList(List<T> list);
<K, V> Map<K, V> synchronizedMap(Map<K, V> m);
<T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s);
<K, V> SortedMap<K, V> synchronizedSortedMap(SortedMap<K, V> m);

Basically this last post is a summary of the java.util.Collections class, but if I was doing a tutorial about collections I had to add it. So with this I finish the tutorial and I hope you can find a quick reference to the collections API and learn something new.




Saturday, July 27, 2013

Java Collections Framework Part 6 - Queues

This is the sixth part of the tutorial, and this link goes to the previous post java collections framework part 5

Queues

A queue is a collection that implements the interface java.util.Queue , usually a queue is an ordered collection that follows the FIFO (First-In, First-Out) rule, but the queue implementations allow other ways to order the collection as well, such as LIFO or based on priority and so on.



The Queue interface defines the following methods:

boolean add(E e): Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
E element(): Retrieves, but does not remove, the head of this queue.
Boolean offer(E e): Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
E peek(): Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
E poll(): Retrieves and removes the head of this queue, or returns null if this queue is empty.
E remove(): Retrieves and removes the head of this queue.

Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.

PriorityQueue

The class java.util.PriotiyQueue is an implementation of the Queue interface, it is an ordered collection and allows duplicates, it works as a “Priority-In, Priority-Out” collection, its elements are ordered by priority and its default priority is given by its natural order, it can be defined another priority order with an instance of a Comparator.

Example


The previous example should print the elements in the collection according to its priority, in this case it should print 1 2 3 4 5 6 7 8 9, this means they priority is the natural order.

To specify a different priority an instance of a Comparator should be used:

Example

The previous example should print its elements according to the new priority specified at the time the collection was created, this new priority is the inverse of the natural order and the example should print 9 8 7 6 5 4 3 2 1

Deque

The java.util.Deque interface extends the Queue interface, the deque name means “double-ended queue”. In a double-ended queue elements can be inserted and removed at both ends of the queue, unlike queue that elements only can be inserted at the tail and removed at the head.
With this a deque can also act as a LIFO collection or Stack.



The Deque interface defines new methods besides the ones defined in the Queue interface:

void addFirst(E e) : Inserts e at the head if there is enough space
void addLast(E e): Inserts e at the tail if there is enough space
void push(E e): Inserts e at the head if there is enough space
boolean removeFirstOccurrence(Object o): Removes the first occurrence of o
boolean removeLastOccurrence(Object o): Removes the last occurrence of o
Iterator<E> descendingIterator(): Gets an iterator that returns the elements in reverse order
boolean offerFirst(E e): Inserts e at the head if the deque has space
boolean offerLast(E e): Inserts e at the tail if the deque has space
E peekFirst(): Gets but do not removes the first element
E peekLast(): Gets but do not removes the last element
E pollFirst(): Gets and removes the first element
E pollLast(): Gets and removes the last element
E getFirst(): Gets but do not removes the first element
E getLast(): Gets but do not removes the last element
E removeFirst(): Gets and removes the first element
E removeLast(): Gets and removes the last element
E pop(): Gets and removes the first element

Example


In the previous example a deque collection was created and elements were added in different ways, first the elements were added at the head so the collection final order was:

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

The the elements were added to the tail the collection final order was:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

And this is also the default behavior for adding elements, in the example were used methods for querying the head and the tail of the collection. The example should print:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
9
0

LinkedList

The class java.util.LinkedList besides being a List also implements the Deque interface, this class is very popular because with one class many different behaviors can be implemented.

Go to part 7




Sunday, July 21, 2013

Java Collections Framework Part 5 - Maps

This is the sixth part of the tutorial, and this link goes to the previous post java collections framework part 4

Maps

A Map implements the java.util.Map interface, this interface doesn't extends from the Collection interface. A map is a collection of key-value mappings, they don't allow duplicate keys and like Sets, maps rely on the equals() method to determine whether two keys are the same or different.

Maps do not have order but some implementations are sorted like the TreeMap.

Maps like the Collection interface have methods for adding and removing elements, querying collection contents, and providing different views of the contents of a collection, and some of this methods are:

V put(K key, V value): Add or replace a key-value association, returns the old value (may be null) if the key was present; otherwise returns null.
void putAll(Map<? extends K,? extends V> m): Adds each of the key-value associations in the supplied map into the receiver.
void clear(): Removes all associations from this map.
V remove(Object key): Removes the association, if any, with the given key; returns the value with which it was associated, or null.
V get(Object k): Returns the value corresponding to k, or null if k is not present as a key.
boolean containsKey(Object k): Returns true if k is present as a key.
boolean containsValue(Object v): Return true if v is present as a value.
int size(): Returns the number of mappings.
boolean isEmpty(): Returns true if there are no mappings.
Set<Map.Entry<K, V>> entrySet(): Returns a Set view of the associations.
Set<K> keySet(): Return a Set view of the keys
Collection<V> values(): Return a Collection view of the values

The java.util.HashMap class is an implementation of the Map interface. HashMap it keeps its elements unsorted and unordered.

You should know that HashMap allows one null key and multiple null values in a collection.


Example:


In the previous example a HashMap of Integers as keys and Strings as values was created, five elements were added and then an element was added again replacing its previous value. The output of the example should be:

Map:{[1, one] [2, two] [3, three-again] [4, four] [5, five] }

The java.util.Hashtable class is also an implementation of the Map interface and it is almost identical
to the HashMap class but it is synchronized so it performs slower than HashMap and another difference is that Hashtable doesn't let you have anything that's null.

The java.util.LinkedHashMap class extends from the HashMap class and therfore is an Implementation of the Map interface, and as the LinkedHashSet class the LinkedHashMap it maintains insertion order (or, optionally, access order). Access ordered is defined by the argument of of the constructor:

public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)

A value false will give an insertion-ordered map, if order constructor is used to create the LinkedHashMap by default it would be an insertion-ordered map.

Example:


The output of the example should be the following:
Map { [1-1] [2-2] [3-3] [4-4] [5-5] }

Changing the the iteration order for an access order in the previous example:


Notice that after adding the elements an access to the element “1” is done with this the iteration order is changed and the output should be the following:
Map Keys { [2] [3] [4] [5] [1] }
Also notice that the output format has changed and now just the keys are printed, this is because if the element is obtained inside the iteration loop a ConcurrentModificationException would arise because the iteration order is changed , and this can not be done while the map is iterated. So be careful when the Map is in this mode.

TreeMap

The class java.util.TreeMap is an implementation of the Map interface, it also implements the
java.util.NavigableMap and java.util.SortedMap interfaces. This collection is pretty similar to TreeSet, it is an sorted collection and guarantees that the keys will be in ascending order, according to their natural order, or by a Comparator provided at map creation time, depending on which constructor is used.

The TreeMap class implements methods that help navigate the map, and some of these methods are:

K ceilingKey(key): Returns the lowest key >= key
K higherKey(key): Returns the lowest key > key
K floorKey(key): Returns the highest key <= key
K lowerKey(key): Returns the highest key < key
Map.Entry<K,V> pollFirstEntry(): Returns and removes the first key-value pair
Map.Entry<K,V> pollLastEntry(): Returns and removes the last key-value pair
NavigableMap<K,V> descendingMap(): Returns a NavigableMap in reverse order
NavigableSet<K> descendingKeySet(): Returns a reverse-order key set
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive):Returns a part of the map whose keys range from fromKey to toKey.
NavigableMap<K,V> headMap(K toKey, boolean inclusive):Returns a part of the map whose keys are less than toKey.
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive):Returns a part of the map whose keys are greater than or equal to fromKey.

Example:


The example should print in console the following:
keys: [1, 2, 3, 4, 5]
Ceiling: 3
Higher: 4
Floor: 3
Lower: 2
Descending keys: [5, 4, 3, 2, 1]
Head map: {1=one, 2=two}
Tail map: {1=one, 2=two}
Poll first: 1=one
Poll last: 5=five
keys: [2, 3, 4]

You can notice how the elements in the map are printed in ascending order, but the map can also be iterated in descending order with the method descendingKeySet().
The sub maps obtained with the methods headMap(), tailMap() and others are backed maps ant hey behave just like any other backed collection this is if submap is modified then also the map is modified
and viceversa.