DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Curious about the future of data-driven systems? Join our Data Engineering roundtable and learn how to build scalable data platforms.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Threat Detection: Learn core practices for managing security risks and vulnerabilities in your organization — don't regret those threats!

Managing API integrations: Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

Avatar

Mohamed Sanaulla

Software Developer at Oracle

Bangalore, IN

Joined Mar 2008

About

I have been in the software development industry since 2010, working on enterprise product development using ADF. I am usually keen on learning about software design and emerging technologies. You can find me hanging around in the JavaRanch Forums where I am one of the moderators. Apart from Java, I am fascinated by the ease of use and simplicity of Ruby and Rails.

Stats

Reputation: 562
Pageviews: 2.4M
Articles: 25
Comments: 45
  • Articles
  • Comments

Articles

article thumbnail
How to Create a QR Code SVG Using Zxing and JFreeSVG in Java? [Snippet]
Create your own QR Code SVG image in Java using the Zxing code generation library.
May 8, 2019
· 17,705 Views · 5 Likes
article thumbnail
Cross-Site Scripting (XSS) Attack Remediation
Learn more about prevention and remediation after a cross-site scripting attack.
May 8, 2019
· 36,503 Views · 3 Likes
article thumbnail
Working With LocalDate, LocalTime, and LocalDateTime
Java 8 introduced a major change for date and time APIs. Let's take a look at these changes and how to implement them in your project.
September 30, 2018
· 45,630 Views · 9 Likes
article thumbnail
Launch Single-File Source-Code Programs in JDK 11
JDK 11 will allow you to run your Java source directly with the Java interpreter. Let's take a look!
July 9, 2018
· 22,822 Views · 8 Likes
article thumbnail
Spring Boot: Thymeleaf Template Decorator
In this post, we take a look at how you can reuse a header and footer across all Thymeleaf templates with some help from Spring Boot's auto-configuraiton.
November 29, 2017
· 57,176 Views · 7 Likes
article thumbnail
Deploying Spring Apps to Tomcat (Without web.xml)
For those out there who haven't made the jump to Servlet's annotations, see how to deploy a simple sample Spring app to Tomcat without a web.xml file.
November 21, 2017
· 61,466 Views · 10 Likes
article thumbnail
Using Google reCaptcha With Spring Boot Application
In this post, we take a look at how to integrate the Google reCaptcha library with a Spring Boot application. Read on for the details.
November 14, 2017
· 49,426 Views · 10 Likes
article thumbnail
Aggregate and Index Data into Elasticsearch Using Logstash and JDBC
Some of the shortcomings of Elasticsearch can be overcome using some Logstash plugins. Check out how to use them to aggregate and index data into Elasticsearch.
October 27, 2017
· 24,139 Views · 2 Likes
article thumbnail
Getting to Know java.nio.file.Path (Part 1)
Java 9 will be introducing a number of enhancements to the File API. Let's run through most of them and see how they'll simplify your work.
August 21, 2017
· 18,848 Views · 8 Likes
article thumbnail
Simple Aspect Oriented Programming (AOP) using CDI in JavaEE
we write service apis which cater to certain business logic. there are few cross-cutting concerns that cover all service apis like security, logging, auditing, measuring latencies and so on. this is a repetitive non-business code which can be reused among other methods. one way to reuse is to move these repetitive code into its own methods and invoke them in the service apis somethings like: public class myservice{ public servicemodel service1(){ isauthorized(); //execute business logic. } } public class myanotherservice{ public servicemodel service1(){ isauthorized(): //execute business logic. } } the above approach will work but not without creating code noise, mixing cross-cutting concerns with the business logic. there is another approach to solve the above requirements which is by using aspect and this approach is called aspect oriented programming (aop). there are a different ways you can make use of aop – by using spring aop, javaee aop. in this example i will try to use aop using cdi in java ee applications. to explain this i have picked a very simple example of building a web application to fetch few records from database and display in the browser. creating the data access layer the table structure is: create table people( id int not null auto_increment, name varchar(100) not null, place varchar(100), primary key(id)); lets create a model class to hold a person information package demo.model; public class person{ private string id; private string name; private string place; public string getid(){ return id; } public string setid(string id) { this.id = id;} public string getname(){ return name; } public string setname(string name) { this.name = name;} public string getplace(){ return place; } public string setplace(string place) { this.place = place;} } lets create a data access object which exposes two methods - to fetch the details of all the people to fetch the details of one person of given id package demo.dao; import demo.common.databaseconnectionmanager; import demo.model.person; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultset; import java.sql.sqlexception; import java.sql.statement; import java.util.arraylist; import java.util.list; public class peopledao { public list getallpeople() throws sqlexception { string sql = "select * from people"; connection conn = databaseconnectionmanager.getconnection(); list people = new arraylist<>(); try (statement statement = conn.createstatement(); resultset rs = statement.executequery(sql)) { while (rs.next()) { person person = new person(); person.setid(rs.getstring("id")); person.setname(rs.getstring("name")); person.setplace(rs.getstring("place")); people.add(person); } } return people; } public person getperson(string id) throws sqlexception { string sql = "select * from people where id = ?"; connection conn = databaseconnectionmanager.getconnection(); try (preparedstatement ps = conn.preparestatement(sql)) { ps.setstring(1, id); try (resultset rs = ps.executequery()) { if (rs.next()) { person person = new person(); person.setid(rs.getstring("id")); person.setname(rs.getstring("name")); person.setplace(rs.getstring("place")); return person; } } } return null; } } you can use your own approach to get a new connection. in the above code i have created a static utility that returns me the same connection. creating interceptors creating interceptors involves 2 steps: create interceptor binding which creates an annotation annotated with @interceptorbinding that is used to bind the interceptor code and the target code which needs to be intercepted. create a class annotated with @interceptor which contains the interceptor code. it would contain methods annotated with @aroundinvoke , different lifecycle annotations, @aroundtimeout and others. lets create an interceptor binding by name @latencylogger package demo; import java.lang.annotation.target; import java.lang.annotation.retention; import static java.lang.annotation.retentionpolicy.*; import static java.lang.annotation.elementtype.*; import javax.interceptor.interceptorbinding; @interceptorbinding 10 @retention(runtime) 11 @target({method, type}) public @interface latencylogger { } now we need to create the interceptor code which is annotated with @interceptor and also annotated with the interceptor binding we created above i.e @latencylogger : package demo; import java.io.serializable; import javax.interceptor.aroundinvoke; import javax.interceptor.interceptor; import javax.interceptor.invocationcontext; @interceptor @latencylogger public class latencyloggerinterceptor implements serializable{ @aroundinvoke public object computelatency(invocationcontext invocationctx) throws exception{ long starttime = system.currenttimemillis(); //execute the intercepted method and store the return value object returnvalue = invocationctx.proceed(); long endtime = system.currenttimemillis(); system.out.println("latency of " + invocationctx.getmethod().getname() +": " + (endtime-starttime)+"ms"); return returnvalue; } } there are two interesting things in the above code: use of @aroundinvoke parameter of type invocationcontext passed to the method @aroundinvoke designates the method as an interceptor method. an interceptor class can have only one method annotated with this annotation. when ever a target method is intercepted, its context is passed to the interceptor. using the invocationcontext one can get the method details, the parameters passed to the method. we need to declare the above interceptor in the web-inf/beans.xml file demo.latencyloggerinterceptor creating service apis annotated with interceptors we have already created the interceptor binding and the interceptor which gets executed. now lets create the service apis and then annotate them with the interceptor binding /* * to change this license header, choose license headers in project properties. * to change this template file, choose tools | templates * and open the template in the editor. */ package demo.service; import demo.latencylogger; import demo.dao.peopledao; import demo.model.person; import java.sql.sqlexception; import java.util.list; import javax.inject.inject; public class peopleservice { @inject peopledao peopledao; @latencylogger public list getallpeople() throws sqlexception { return peopledao.getallpeople(); } @latencylogger public person getperson(string id) throws sqlexception { return peopledao.getperson(id); } } we have annotated the service methods with the interceptor binding @latencylogger . the other way would be to annotate at the class level which would then apply the annotation to all the methods of the class. another thing to notice is the @inject annotation that injects the instance i.e injects the dependency into the class. next is to wire up the controller and view to show the data. the controller is the servlet and view is a plain jsp using jstl tags. /* * to change this license header, choose license headers in project properties. * to change this template file, choose tools | templates * and open the template in the editor. */ package demo; import demo.model.person; import demo.service.peopleservice; import java.io.ioexception; import java.sql.sqlexception; import java.util.list; import java.util.logging.level; import java.util.logging.logger; import javax.inject.inject; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; @webservlet(name = "aopdemo", urlpatterns = {"/aopdemo"}) public class aopdemoservlet extends httpservlet { @inject peopleservice peopleservice; @override public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { try { list people = peopleservice.getallpeople(); person person = peopleservice.getperson("2"); request.setattribute("people", people); request.setattribute("person", person); getservletcontext().getrequestdispatcher("/index.jsp").forward(request, response); } catch (sqlexception ex) { logger.getlogger(aopdemoservlet.class.getname()).log(level.severe, null, ex); } } } the above servlet is available at http://localhost:8080/ /aopdemo. it fetches the data and redirects to the view to display the same. note that the service has also been injected using @inject annotation. if the dependencies are not injected and instead created using new then the interceptors will not work. this is an important point which i realised while building this sample. the jsp to render the data would be hello world! id name place details for person with id=2 with this you would have built a very simple app using interceptors. thanks for reading and staying with me till this end. please share your queries/feedback as comments. and also share this article among your friends
September 5, 2014
· 14,010 Views
article thumbnail
Getting Started with Mocking in Java using Mockito
We all write unit tests but the challenge we face at times is that the unit under test might be dependent on other components. And configuring other components for unit testing is definitely an overkill. Instead we can make use of Mocks in place of the other components and continue with the unit testing. To show how one can use mocks, I have a Data access layer(DAL), basically a class which provides an API for the application to access and modify the data in the data repository. I then unit test the DAL without actually the need to connect to the data repository. The data repository can be a local database or remote database or a file system or any place where we can store and retrieve the data. The use of a DAL class helps us in keeping the data mappers separate from the application code. Lets create a Java project using maven. mvn archetype:generate -DgroupId=info.sanaulla -DartifactId=MockitoDemo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false The above creates a folder MockitoDemo and then creates the entire directory structure for source and test files. Consider the below model class for this example: package info.sanaulla.models; import java.util.List; /** * Model class for the book details. */ public class Book { private String isbn; private String title; private List authors; private String publication; private Integer yearOfPublication; private Integer numberOfPages; private String image; public Book(String isbn, String title, List authors, String publication, Integer yearOfPublication, Integer numberOfPages, String image){ this.isbn = isbn; this.title = title; this.authors = authors; this.publication = publication; this.yearOfPublication = yearOfPublication; this.numberOfPages = numberOfPages; this.image = image; } public String getIsbn() { return isbn; } public String getTitle() { return title; } public List getAuthors() { return authors; } public String getPublication() { return publication; } public Integer getYearOfPublication() { return yearOfPublication; } public Integer getNumberOfPages() { return numberOfPages; } public String getImage() { return image; } } The DAL class for operating on the Book model class is: package info.sanaulla.dal; import info.sanaulla.models.Book; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * API layer for persisting and retrieving the Book objects. */ public class BookDAL { private static BookDAL bookDAL = new BookDAL(); public List getAllBooks(){ return Collections.EMPTY_LIST; } public Book getBook(String isbn){ return null; } public String addBook(Book book){ return book.getIsbn(); } public String updateBook(Book book){ return book.getIsbn(); } public static BookDAL getInstance(){ return bookDAL; } } The DAL layer above currently has no functionality and we are going to unit test that piece of code (TDD). The DAL layer might communicate with a ORM Mapper or Database API which we are not concerned while designing the API. Test Driving the DAL Layer There are lot of frameworks for Unit testing and mocking in Java but for this example I would be picking JUnit for unit testing and Mockito for mocking. We would have to update the dependency in Maven’s pom.xml 4.0.0 info.sanaulla MockitoDemo jar 1.0-SNAPSHOT MockitoDemo http://maven.apache.org junit junit 4.10 test org.mockito mockito-all 1.9.5 test Now lets unit test the BookDAL. During the unit testing we will inject mock data into the BookDAL so that we can complete the testing of the API without depending on the data source. Initially we will have an empty test class: public class BookDALTest { public void setUp() throws Exception { } public void testGetAllBooks() throws Exception { } public void testGetBook() throws Exception { } public void testAddBook() throws Exception { } public void testUpdateBook() throws Exception { } } We will inject the mock BookDAL and mock data in the setUp() as shown below: public class BookDALTest { private static BookDAL mockedBookDAL; private static Book book1; private static Book book2; @BeforeClass public static void setUp(){ //Create mock object of BookDAL mockedBookDAL = mock(BookDAL.class); //Create few instances of Book class. book1 = new Book("8131721019","Compilers Principles", Arrays.asList("D. Jeffrey Ulman","Ravi Sethi", "Alfred V. Aho", "Monica S. Lam"), "Pearson Education Singapore Pte Ltd", 2008,1009,"BOOK_IMAGE"); book2 = new Book("9788183331630","Let Us C 13th Edition", Arrays.asList("Yashavant Kanetkar"),"BPB PUBLICATIONS", 2012,675,"BOOK_IMAGE"); //Stubbing the methods of mocked BookDAL with mocked data. when(mockedBookDAL.getAllBooks()).thenReturn(Arrays.asList(book1, book2)); when(mockedBookDAL.getBook("8131721019")).thenReturn(book1); when(mockedBookDAL.addBook(book1)).thenReturn(book1.getIsbn()); when(mockedBookDAL.updateBook(book1)).thenReturn(book1.getIsbn()); } public void testGetAllBooks() throws Exception {} public void testGetBook() throws Exception {} public void testAddBook() throws Exception {} public void testUpdateBook() throws Exception {} } In the above setUp() method I have: Created a mock object of BookDAL BookDAL mockedBookDAL = mock(BookDAL.class); Stubbed the API of BookDAL with mock data, such that when ever the API is invoked the mocked data is returned. //When getAllBooks() is invoked then return the given data and so on for the other methods. when(mockedBookDAL.getAllBooks()).thenReturn(Arrays.asList(book1, book2)); when(mockedBookDAL.getBook("8131721019")).thenReturn(book1); when(mockedBookDAL.addBook(book1)).thenReturn(book1.getIsbn()); when(mockedBookDAL.updateBook(book1)).thenReturn(book1.getIsbn()); Populating the rest of the tests we get: package info.sanaulla.dal; import info.sanaulla.models.Book; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; public class BookDALTest { private static BookDAL mockedBookDAL; private static Book book1; private static Book book2; @BeforeClass public static void setUp(){ mockedBookDAL = mock(BookDAL.class); book1 = new Book("8131721019","Compilers Principles", Arrays.asList("D. Jeffrey Ulman","Ravi Sethi", "Alfred V. Aho", "Monica S. Lam"), "Pearson Education Singapore Pte Ltd", 2008,1009,"BOOK_IMAGE"); book2 = new Book("9788183331630","Let Us C 13th Edition", Arrays.asList("Yashavant Kanetkar"),"BPB PUBLICATIONS", 2012,675,"BOOK_IMAGE"); when(mockedBookDAL.getAllBooks()).thenReturn(Arrays.asList(book1, book2)); when(mockedBookDAL.getBook("8131721019")).thenReturn(book1); when(mockedBookDAL.addBook(book1)).thenReturn(book1.getIsbn()); when(mockedBookDAL.updateBook(book1)).thenReturn(book1.getIsbn()); } @Test public void testGetAllBooks() throws Exception { List allBooks = mockedBookDAL.getAllBooks(); assertEquals(2, allBooks.size()); Book myBook = allBooks.get(0); assertEquals("8131721019", myBook.getIsbn()); assertEquals("Compilers Principles", myBook.getTitle()); assertEquals(4, myBook.getAuthors().size()); assertEquals((Integer)2008, myBook.getYearOfPublication()); assertEquals((Integer) 1009, myBook.getNumberOfPages()); assertEquals("Pearson Education Singapore Pte Ltd", myBook.getPublication()); assertEquals("BOOK_IMAGE", myBook.getImage()); } @Test public void testGetBook(){ String isbn = "8131721019"; Book myBook = mockedBookDAL.getBook(isbn); assertNotNull(myBook); assertEquals(isbn, myBook.getIsbn()); assertEquals("Compilers Principles", myBook.getTitle()); assertEquals(4, myBook.getAuthors().size()); assertEquals("Pearson Education Singapore Pte Ltd", myBook.getPublication()); assertEquals((Integer)2008, myBook.getYearOfPublication()); assertEquals((Integer)1009, myBook.getNumberOfPages()); } @Test public void testAddBook(){ String isbn = mockedBookDAL.addBook(book1); assertNotNull(isbn); assertEquals(book1.getIsbn(), isbn); } @Test public void testUpdateBook(){ String isbn = mockedBookDAL.updateBook(book1); assertNotNull(isbn); assertEquals(book1.getIsbn(), isbn); } } One can run the test by using maven command: mvn test. The output is: ------------------------------------------------------- T E S T S ------------------------------------------------------- Running info.sanaulla.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 sec Running info.sanaulla.dal.BookDALTest Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.209 sec Results : Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 So we have been able to test the DAL class without actually configuring the data source by using mocks.
February 26, 2014
· 232,758 Views · 18 Likes
article thumbnail
Creating External DSLs using ANTLR and Java
In my previous post quite sometime back I had written about Internal DSLs using Java. In the book Domain Specific Languages by Martin Fowler, he discusses about another type of DSL called external DSLs in which the DSL is written in another language which is then parsed by the host language to populate the semantic model. In the previous example I was discussing about creating a DSL for defining a graph. The advantage of using an external dsl is that any change in the graph data would not require recompilation of the program instead the program can just load the external dsl, create a parse tree and then populate the semantic model. The semantic model will remain the same and the advantage of using the semantic model is that one can make modification to the DSL without making much changes to the semantic model. In the example between Internal DSLs and external DSLs I have not modified the semantic model. To create an external DSL I am making use of ANTLR. What is ANTLR? The definition as given on the official site is: ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files. It’s widely used to build languages, tools, and frameworks. From a grammar, ANTLR generates a parser that can build and walk parse trees. The notable features of ANTLR from the above definition are: parser generator for structured text or binary files can build and walk parse trees Semantic Model In this example I will exploit the above features of ANTLR to parse a DSL and then walk through the parse tree to populate the Semantic model. To recap, the semantic model consists of Graph, Edge and Vertex classes which represent a Graph and an Edge and a Vertex of the Graph respectively. The below code shows the class definitions: public class Graph { private List edges; private Set vertices; public Graph() { edges = new ArrayList<>(); vertices = new TreeSet<>(); } public void addEdge(Edge edge){ getEdges().add(edge); getVertices().add(edge.getFromVertex()); getVertices().add(edge.getToVertex()); } public void addVertice(Vertex v){ getVertices().add(v); } public List getEdges() { return edges; } public Set getVertices() { return vertices; } public static void printGraph(Graph g){ System.out.println("Vertices..."); for (Vertex v : g.getVertices()) { System.out.print(v.getLabel() + " "); } System.out.println(""); System.out.println("Edges..."); for (Edge e : g.getEdges()) { System.out.println(e); } } } public class Edge { private Vertex fromVertex; private Vertex toVertex; private Double weight; public Edge() { } public Edge(Vertex fromVertex, Vertex toVertex, Double weight) { this.fromVertex = fromVertex; this.toVertex = toVertex; this.weight = weight; } @Override public String toString() { return fromVertex.getLabel() + " to " + toVertex.getLabel() + " with weight " + getWeight(); } public Vertex getFromVertex() { return fromVertex; } public void setFromVertex(Vertex fromVertex) { this.fromVertex = fromVertex; } public Vertex getToVertex() { return toVertex; } public void setToVertex(Vertex toVertex) { this.toVertex = toVertex; } public Double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } } public class Vertex implements Comparable { private String label; public Vertex(String label) { this.label = label.toUpperCase(); } @Override public int compareTo(Vertex o) { return (this.getLabel().compareTo(o.getLabel())); } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } } Creating the DSL Lets come up with the structure of the language before going into creating grammar rules. The structure which I am planning to come up is something like: Graph { A -> B (10) B -> C (20) D -> E (30) } Each line in the Graph block represents an edge and the vertices involved in the edge and the value in the braces represent the weight of the edge. One limitation which I am enforcing is that the Graph cannot have dangling vertices i.e vertices which are not part of any edge. This limitation can be removed by slightly changing the grammar, but I would leave that as an exercise for the readers of this post. The first task in creating the DSL is to define the grammar rules. These are the rules which your lexer and parser will use to convert the DSL into a Abstract Syntax tree/parse tree. ANTLR then makes use of this grammar to generate the Parser, Lexer and a Listener which are nothing but java classes extending/implementing some classes from the ANTLR library. The creators of the DSL must make use of these java classes to load the external DSL, parse it and then using the listener populate the semantic model as and when the parser encounters certain nodes (think of this as a variant of SAX parser for XML) Now that we know in very brief what ANTLR can do and the steps in using ANTLR, we would have to setup ANTLR i.e download ANTLR API jar and setup up some scripts for generating the parser and lexer and then trying out the language via the command line tool. For that please visit this official tutorial from ANTLR which shows how to setup ANTLR and a simple Hello World example. Grammar for the DSL Now that you have ANTLR setup let me dive into the grammar for my DSL: grammar Graph; graph: 'Graph {' edge+ '}'; vertex: ID; edge: vertex '->' vertex '(' NUM ')' ; ID: [a-zA-Z]+; NUM: [0-9]+; WS: [ \t\r\n]+ -> skip; Lets go rule: graph: 'Graph {' edge+ '}'; The above grammar rule which is the start rule says that the language should start with ‘Graph {‘ and end with ‘}’ and has to contain at lease one edge or more than one edge. vertex: ID; edge: vertex '->' vertex '(' NUM ')' ; ID: [a-zA-Z]+; NUM: [0-9]+; The above four rules say that a vertex should have atleast one character or more than one character. And an edge is defined as collection of two vertices separated by a ‘->’ and with the some digits in the ‘()’. I have named the grammar language as “Graph” and hence once we use ANTLR to generate the java classes i.e parser and lexer we will end up seeing the following classes: GraphParser, GraphLexer, GraphListener and GraphBaseListener. The first two classes deal with the generation of parse tree and the last two classes deal with the parse tree walk through. GraphListener is an interface which contains all the methods for dealing with the parse tree i.e dealing with events such as entering a rule, exiting a rule, visiting a terminal node and in addition to these it contains methods for dealing with events related to entering the graph rule, entering the edge rule and entering the vertex rule. We will be making use of these methods to intercept the data present in the dsl and then populate the semantic model. Populating the semantic model I have created a file graph.gr in the resource package which contains the DSL for populating the graph. As the files in the resource package are available to the ClassLoader at runtime, we can use the ClassLoader to read the DSL script and then pass it on to the Lexer and parser classes. The DSL script used is: Graph { A -> B (10) B -> C (20) D -> E (30) A -> E (12) B -> D (8) } And the code which loads the DSL and populates the semantic model: //Please resolve the imports for the classes used. public class GraphDslAntlrSample { public static void main(String[] args) throws IOException { //Reading the DSL script InputStream is = ClassLoader.getSystemResourceAsStream("resources/graph.gr"); //Loading the DSL script into the ANTLR stream. CharStream cs = new ANTLRInputStream(is); //Passing the input to the lexer to create tokens GraphLexer lexer = new GraphLexer(cs); CommonTokenStream tokens = new CommonTokenStream(lexer); //Passing the tokens to the parser to create the parse trea. GraphParser parser = new GraphParser(tokens); //Semantic model to be populated Graph g = new Graph(); //Adding the listener to facilitate walking through parse tree. parser.addParseListener(new MyGraphBaseListener(g)); //invoking the parser. parser.graph(); Graph.printGraph(g); } } /** * Listener used for walking through the parse tree. */ class MyGraphBaseListener extends GraphBaseListener { Graph g; public MyGraphBaseListener(Graph g) { this.g = g; } @Override public void exitEdge(GraphParser.EdgeContext ctx) { //Once the edge rule is exited the data required for the edge i.e //vertices and the weight would be available in the EdgeContext //and the same can be used to populate the semantic model Vertex fromVertex = new Vertex(ctx.vertex(0).ID().getText()); Vertex toVertex = new Vertex(ctx.vertex(1).ID().getText()); double weight = Double.parseDouble(ctx.NUM().getText()); Edge e = new Edge(fromVertex, toVertex, weight); g.addEdge(e); } } And the output when the above would be executed would be: Vertices... A B C D E Edges... A to B with weight 10.0 B to C with weight 20.0 D to E with weight 30.0 A to E with weight 12.0 B to D with weight 8.0 To summarize, this post creates a external DSL for populating the data for graphs by making use of ANTLR. I will enhance this simple DSL and expose it as an utility which can be used by programmers working on graphs. The post is very heavy on concepts and code, feel free to drop in any queries you have so that I can try to address them for benefit of others as well.
July 19, 2013
· 24,398 Views · 1 Like
article thumbnail
Strategy Pattern using Lambda Expressions in Java 8
Strategy Pattern is one of the patterns from the Design Patterns : Elements of Reusable Object book. The intent of the strategy pattern as stated in the book is: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. In this post I would like to give an example or two on strategy pattern and then rewrite the same example using lambda expressions to be introduced in Java 8. Strategy Pattern: An example Consider an interface declaring the strategy: interface Strategy{ public void performTask(); } Consider two implementations of this strategy: class LazyStratgey implements Strategy{ @Override public void performTask() { System.out.println("Perform task a day before deadline!"); } } class ActiveStratgey implements Strategy{ @Override public void performTask() { System.out.println("Perform task now!"); } } The above strategies are naive and I have kept it simple to help readers grasp it quickly. And lets see these strategies in action: public class StartegyPatternOldWay { public static void main(String[] args) { List strategies = Arrays.asList( new LazyStratgey(), new ActiveStratgey() ); for(Strategy stg : strategies){ stg.performTask(); } } } The output for the above is: Perform task a day before deadline! Perform task now! Strategy Pattern: An example with Lambda expressions Lets look at the same example using Lambda expressions. For this we will retain our Strategy interface, but we need not create different implementation of the interface, instead we make use of lambda expressions to create different implementations of the strategy. The below code shows it in action: import java.util.Arrays; import java.util.List; public class StrategyPatternOnSteroids { public static void main(String[] args) { System.out.println("Strategy pattern on Steroids"); List strategies = Arrays.asList( () -> {System.out.println("Perform task a day before deadline!");}, () -> {System.out.println("Perform task now!");} ); strategies.forEach((elem) -> elem.performTask()); } } The output for the above is: Strategy pattern on Steroids Perform task a day before deadline! Perform task now! In the example using lambda expression, we avoided the use of class declaration for different strategies implementation and instead made use of the lambda expressions. Strategy Pattern: Another Example This example is inspired from Neal Ford’s article on IBM Developer works: Functional Design Pattern-1. The idea of the example is exactly similar, but Neal Ford uses Scala and I am using Java for the same with a few changes in the naming conventions. Lets look at an interface Computation which also declares a generic type T apart from a method compute which takes in two parameters. interface Computation { public T compute(T n, T m); } We can have different implementations of the computation like: IntSum – which returns the sum of two integers, IntDifference – which returns the difference of two integers and IntProduct – which returns the product of two integers. class IntSum implements Computation { @Override public Integer compute(Integer n, Integer m) { return n + m; } } class IntProduct implements Computation { @Override public Integer compute(Integer n, Integer m) { return n * m; } } class IntDifference implements Computation { @Override public Integer compute(Integer n, Integer m) { return n - m; } } Now lets look at these strategies in action in the below code: public class AnotherStrategyPattern { public static void main(String[] args) { List computations = Arrays.asList( new IntSum(), new IntDifference(), new IntProduct() ); for (Computation comp : computations) { System.out.println(comp.compute(10, 4)); } } }public class AnotherStrategyPattern { public static void main(String[] args) { List computations = Arrays.asList( new IntSum(), new IntDifference(), new IntProduct() ); for (Computation comp : computations) { System.out.println(comp.compute(10, 4)); } } } The output for the above is: 14 6 40 Strategy Pattern: Another Example with lambda expressions Now lets look at the same example using Lambda expressions. As in the previous example as well we need not declare classes for different implementation of the strategy i.e the Computation interface, instead we make use of lambda expressions to achieve the same. Lets look at an example: public class AnotherStrategyPatternWithLambdas { public static void main(String[] args) { List> computations = Arrays.asList( (n, m)-> { return n+m; }, (n, m)-> { return n*m; }, (n, m)-> { return n-m; } ); computations.forEach((comp) -> System.out.println(comp.compute(10, 4))); } } The output for above is 14 6 40 From the above examples we can see that using Lambda expressions will help in reducing lot of boilerplate code to achieve more concise code. And with practice one can get used to reading lambda expressions.
July 3, 2013
· 44,001 Views · 5 Likes
article thumbnail
Creating Internal DSLs in Java & Java 8
Adopting Martin Fowler's approach to domain-specific language.
June 5, 2013
· 33,225 Views · 7 Likes
article thumbnail
Parsing XML in Groovy using XmlSlurper
In my previous post I showed different ways in which we can parse XML document in Java. You must have noticed the code being too much verbose. Other JVM languages like Groovy, Scala provide much better support for parsing XML documents. In this post I give you the code to parse the XML document in Groovy and one can compare the ease with which we can parse XML documents. I make use of XmlSlurper API in Groovy which loads the complete XML into a tree and this tree can be then navigated using Groovy’s version of XPath called GPath. The XML document I am using is the same one used here and also the intent is to parse the XML and create a list of Employee object. class XmlParserDemo { static void main(args){ def empList = new ArrayList(); def emp; def employees = new XmlSlurper().parse(ClassLoader. getSystemResourceAsStream("xml/employee.xml")); employees.employee.each{ node -> emp = new Employee(); emp.firstName = node.firstName emp.lastName = node.lastName emp.id = node.@id emp.location = node.location empList.add(emp) } empList.each{ empT -> println(empT)} } } class Employee{ String firstName String lastName String id String location @Override public String toString(){ return "${firstName} ${lastName}(${id}) in ${location}" } } The output is: Rakesh Mishra(111) in Bangalore John Davis(112) in Chennai Rajesh Sharma(113) in Pune And the XML is present in the “xml” package and is available in the classpath of the application. I am using the ClassLoader to load the XML resource.
May 29, 2013
· 30,193 Views
article thumbnail
Parsing XML using DOM, SAX and StAX Parser in Java
I happen to read through a chapter on XML parsing and building APIs in Java. And I tried out the different parsers on a sample XML. Then I thought of sharing it on my blog so that I can have a reference to the code as well as a reference for anyone reading this. In this post I parse the same XML in different parsers to perform the same operation of populating the XML content into objects and then adding the objects to a list. The sample XML considered in the examples is: Rakesh Mishra Bangalore John Davis Chennai Rajesh Sharma Pune And the obejct into which the XML content is to be extracted is defined as below: class Employee{ String id; String firstName; String lastName; String location; @Override public String toString() { return firstName+" "+lastName+"("+id+")"+location; } } There are 3 main parsers for which I have given sample code: DOM Parser SAX Parser StAX Parser Using DOM Parser I am making use of the DOM parser implementation that comes with the JDK and in my example I am using JDK 7. The DOM Parser loads the complete XML content into a Tree structure. And we iterate through the Node and NodeList to get the content of the XML. The code for XML parsing using DOM parser is given below. public class DOMParserDemo { public static void main(String[] args) throws Exception { //Get the DOM Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DOM Builder DocumentBuilder builder = factory.newDocumentBuilder(); //Load and Parse the XML document //document contains the complete XML as a Tree. Document document = builder.parse( ClassLoader.getSystemResourceAsStream("xml/employee.xml")); List empList = new ArrayList<>(); //Iterating through the nodes and extracting the data. NodeList nodeList = document.getDocumentElement().getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { //We have encountered an tag. Node node = nodeList.item(i); if (node instanceof Element) { Employee emp = new Employee(); emp.id = node.getAttributes(). getNamedItem("id").getNodeValue(); NodeList childNodes = node.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node cNode = childNodes.item(j); //Identifying the child tag of employee encountered. if (cNode instanceof Element) { String content = cNode.getLastChild(). getTextContent().trim(); switch (cNode.getNodeName()) { case "firstName": emp.firstName = content; break; case "lastName": emp.lastName = content; break; case "location": emp.location = content; break; } } } empList.add(emp); } } //Printing the Employee list populated. for (Employee emp : empList) { System.out.println(emp); } } } class Employee{ String id; String firstName; String lastName; String location; @Override public String toString() { return firstName+" "+lastName+"("+id+")"+location; } } The output for the above will be: Rakesh Mishra(111)Bangalore John Davis(112)Chennai Rajesh Sharma(113)Pune Using SAX Parser SAX Parser is different from the DOM Parser where SAX parser doesn’t load the complete XML into the memory, instead it parses the XML line by line triggering different events as and when it encounters different elements like: opening tag, closing tag, character data, comments and so on. This is the reason why SAX Parser is called an event based parser. Along with the XML source file, we also register a handler which extends the DefaultHandler class. The DefaultHandler class provides different callbacks out of which we would be interested in: startElement() – triggers this event when the start of the tag is encountered. endElement() – triggers this event when the end of the tag is encountered. characters() – triggers this event when it encounters some text data. The code for parsing the XML using SAX Parser is given below: import java.util.ArrayList; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXParserDemo { public static void main(String[] args) throws Exception { SAXParserFactory parserFactor = SAXParserFactory.newInstance(); SAXParser parser = parserFactor.newSAXParser(); SAXHandler handler = new SAXHandler(); parser.parse(ClassLoader.getSystemResourceAsStream("xml/employee.xml"), handler); //Printing the list of employees obtained from XML for ( Employee emp : handler.empList){ System.out.println(emp); } } } /** * The Handler for SAX Events. */ class SAXHandler extends DefaultHandler { List empList = new ArrayList<>(); Employee emp = null; String content = null; @Override //Triggered when the start of tag is found. public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { switch(qName){ //Create a new Employee object when the start tag is found case "employee": emp = new Employee(); emp.id = attributes.getValue("id"); break; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { switch(qName){ //Add the employee to list once end tag is found case "employee": empList.add(emp); break; //For all other end tags the employee has to be updated. case "firstName": emp.firstName = content; break; case "lastName": emp.lastName = content; break; case "location": emp.location = content; break; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { content = String.copyValueOf(ch, start, length).trim(); } } class Employee { String id; String firstName; String lastName; String location; @Override public String toString() { return firstName + " " + lastName + "(" + id + ")" + location; } } The output for the above would be: Rakesh Mishra(111)Bangalore John Davis(112)Chennai Rajesh Sharma(113)Pune Using StAX Parser StAX stands for Streaming API for XML and StAX Parser is different from DOM in the same way SAX Parser is. StAX parser is also in a subtle way different from SAX parser. The SAX Parser pushes the data but StAX parser pulls the required data from the XML. The StAX parser maintains a cursor at the current position in the document allows to extract the content available at the cursor whereas SAX parser issues events as and when certain data is encountered. XMLInputFactory and XMLStreamReader are the two class which can be used to load an XML file. And as we read through the XML file using XMLStreamReader, events are generated in the form of integer values and these are then compared with the constants in XMLStreamConstants. The below code shows how to parse XML using StAX parser: import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; public class StaxParserDemo { public static void main(String[] args) throws XMLStreamException { List empList = null; Employee currEmp = null; String tagContent = null; XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader( ClassLoader.getSystemResourceAsStream("xml/employee.xml")); while(reader.hasNext()){ int event = reader.next(); switch(event){ case XMLStreamConstants.START_ELEMENT: if ("employee".equals(reader.getLocalName())){ currEmp = new Employee(); currEmp.id = reader.getAttributeValue(0); } if("employees".equals(reader.getLocalName())){ empList = new ArrayList<>(); } break; case XMLStreamConstants.CHARACTERS: tagContent = reader.getText().trim(); break; case XMLStreamConstants.END_ELEMENT: switch(reader.getLocalName()){ case "employee": empList.add(currEmp); break; case "firstName": currEmp.firstName = tagContent; break; case "lastName": currEmp.lastName = tagContent; break; case "location": currEmp.location = tagContent; break; } break; case XMLStreamConstants.START_DOCUMENT: empList = new ArrayList<>(); break; } } //Print the employee list populated from XML for ( Employee emp : empList){ System.out.println(emp); } } } class Employee{ String id; String firstName; String lastName; String location; @Override public String toString(){ return firstName+" "+lastName+"("+id+") "+location; } } The output for the above is: Rakesh Mishra(111) Bangalore John Davis(112) Chennai Rajesh Sharma(113) Pune With this I have covered parsing the same XML document and performing the same task of populating the list of Employee objects using all the three parsers namely: DOM Parser SAX Parser StAX Parser
May 28, 2013
· 98,068 Views · 2 Likes
article thumbnail
Train Wreck Pattern – A much improved implementation in Java 8
venkat subramaniam at a talk today mentioned about cascade method pattern or train wreck pattern which looks something like: someobject.method1().method2().method3().finalresult() few might associate this with the builder pattern , but its not the same. anyways lets have a look at an example for this in java with out the use of lambda expression: public class trainwreckpattern { public static void main(string[] args) { new mailer() .to("to@example.com") .from("from@exmaple.com") .subject("some subject") .body("some content") .send(); } } class mailer{ public mailer to(string address){ system.out.println("to: "+address); return this; } public mailer from(string address){ system.out.println("from: "+address); return this; } public mailer subject(string sub){ system.out.println("subject: "+sub); return this; } public mailer body(string body){ system.out.println("body: "+body); return this; } public void send(){ system.out.println("sending ..."); } } i have taken the same example which venkat subramaniam took in his talk. in the above code i have a mailer class which accepts a series of values namely: to, from, subject and a body and then sends the mail. pretty simple right? but there is some problem associated with this: one doesn’t know what to do with the mailer object once it has finished sending the mail. can it be reused to send another mail? or should it be held to know the status of email sent? this is not known from the code above and lot of times one cannot find this information in the documentation. what if we can restrict the scope of the mailer object within some block so that one cannot use it once its finished its operation? java 8 provides an excellent mechanism to achieve this using lambda expressions . lets look at how it can be done: public class trainwreckpatternlambda { public static void main(string[] args) { mailer.send( mailer -> { mailer.to("to@example.com") .from("from@exmaple.com") .subject("some subject") .body("some content"); }); } } class mailer{ private mailer(){ } public mailer to(string address){ system.out.println("to: "+address); return this; } public mailer from(string address){ system.out.println("from: "+address); return this; } public mailer subject(string sub){ system.out.println("subject: "+sub); return this; } public mailer body(string body){ system.out.println("body: "+body); return this; } public static void send(consumer maileroperator){ mailer mailer = new mailer(); maileroperator.accept(mailer); system.out.println("sending ..."); } } in the above implementation i have restricted the instantiation of the mailer class to the send() method by making the constructor private. and then the send() method now accepts an implementation of consumer interface which is a single abstract method class and can be represented by a lambda expression. and in the main() method i pass a lambda expression which accepts a mailer instance and then configures the mailer object before being used in the send() method. the use of lambda expression has created a clear boundary for the use of the mailer object and this way its much ore clearer for someone reading the code as to how the mailer object has to be used. let me know if there is something more that i can improve in this example i have shared.
May 15, 2013
· 10,934 Views
article thumbnail
Template Method Pattern- Using Lambda Expressions, Default Methods
Template Method pattern is one of the 23 design patterns explained in the famous Design Patterns book by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. The intent of this pattern is stated as: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. TemplateMethod lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. To explain in simple terms, consider the following scenario: Assume there is a workflow system in which 4 tasks have to be performed in the given order so as to successfully complete the workflow. Some of the tasks out of the 4 tasks can be customised by different workflow system implementation. Template Method pattern can be applied to above scenario by encapsulating the workflow system into an abstract class with few of the tasks out of the 4 tasks implemented. And leave the implementation of remaining tasks to the subclasses of the abstract class. So this is what you see when the above description is implemented: /** * Abstract Workflow system */ abstract class WorkflowManager2{ public void doTask1(){ System.out.println("Doing Task1..."); } public abstract void doTask2(); public abstract void doTask3(); public void doTask4(){ System.out.println("Doing Task4..."); } } /** * One of the extensions of the abstract workflow system */ class WorkflowManager2Impl1 extends WorkflowManager2{ @Override public void doTask2(){ System.out.println("Doing Task2.1..."); } @Override public void doTask3(){ System.out.println("Doing Task3.1..."); } } /** * Other extension of the abstract workflow system */ class WorkflowManager2Impl2 extends WorkflowManager2{ @Override public void doTask2(){ System.out.println("Doing Task2.2..."); } @Override public void doTask3(){ System.out.println("Doing Task3.2..."); } } Let me just go ahead and show how these workflow implementations are used: public class TemplateMethodPattern { public static void main(String[] args) { initiateWorkFlow(new WorkflowManager2Impl1()); initiateWorkFlow(new WorkflowManager2Impl2()); } static void initiateWorkFlow(WorkflowManager2 workflowMgr){ System.out.println("Starting the workflow ... the old way"); workflowMgr.doTask1(); workflowMgr.doTask2(); workflowMgr.doTask3(); workflowMgr.doTask4(); } } and the output would be... Starting the workflow ... the old way Doing Task1... Doing Task2.1... Doing Task3.1... Doing Task4... Starting the workflow ... the old way Doing Task1... Doing Task2.2... Doing Task3.2... Doing Task4... So far so good. But the main intent of this post is not to create yet another blog post on Template Method pattern, but to see how we can leverage Java 8 Lambda Expression and Default Methods. I have already written before, that only interfaces which have Single Abstract Methods can be written as lambda expressions. What this translates to in this example is that, the WorkflowManager2 can only have one abstract/customizable task out of the 4 tasks. So restricting to one abstract method is a major restriction and may not be applicable in many realtime scenarios. I dont wish to reiterate the same old Template Method pattern examples, instead my main intention of writing this is to show how lambda expressions and default methods can be leveraged in scenarios where you are dealing with abstract classes with single abstract methods. If you are left wondering what these lambda expressions in java mean and also these default methods in java, then please spend some time to read about lambda expressions and default methods before proceeding further. Instead of an abstract class we would use an interface with default methods, so our workflow system would look like: interface WorkflowManager{ public default void doTask1(){ System.out.println("Doing Task1..."); } public void doTask2(); public default void doTask3(){ System.out.println("Doing Task3..."); } public default void doTask4(){ System.out.println("Doing Task4..."); } } Now that we have the workflow system with customisable Task2, we will go ahead and initiate some customised workflows using Lambda expressions… public class TemplateMethodPatternLambda { public static void main(String[] args) { /** * Using lambda expression to create different * implementation of the abstract workflow */ initiateWorkFlow(()->System.out.println("Doing Task2.1...")); initiateWorkFlow(()->System.out.println("Doing Task2.2...")); initiateWorkFlow(()->System.out.println("Doing Task2.3...")); } static void initiateWorkFlow(WorkflowManager workflowMgr){ System.out.println("Starting the workflow ..."); workflowMgr.doTask1(); workflowMgr.doTask2(); workflowMgr.doTask3(); workflowMgr.doTask4(); } } This is in a small way lambda expressions can be leveraged in the Template Method Pattern.
April 25, 2013
· 12,380 Views
article thumbnail
Predicate and Consumer Interface in java.util.function package in Java 8
Here's how to properly use the Predicate and Consumer interfaces in Java 8.
April 11, 2013
· 38,906 Views · 16 Likes
article thumbnail
Function Interface- A Functional Interface in the java.util.function Package in Java 8
I had previously written about functional interfaces and their usage. If you are exploring the APIs to be part of Java 8 and especially those APIs which support lambda expressions you will find few interfaces like- Function, Supplier, Consumer, Predicate and others which are all part of the java.util.function package, being used extensively. These interfaces have one abstract method, which is overridden by the lambda expression defined. In this post I will pick Function interface to explain about it in brief and it is one of the interfaces present in java.util.function package. Function interface has two methods: R apply(T t) – Compute the result of applying the function to the input argument default ‹V› Function‹T,V› – Combine with another function returning a function which performs both functions. In this post I would like to write about the apply method, creating APIs which accept these interfaces and parameters and then invoke their corresponding methods. We will also look at how the caller of the API can pass in a lambda expression in place of an implementation of the interface. Apart from passing a lambda expression, the users of the API can also pass method references, about which I havent blogged yet. Function interface is uses in cases where you want to encapsulate some code into a method which accepts some value as an input parameter and then returns another value after performing required operations on the input. The input parameter type and the return type of the method can either be same or different. Lets look at an API which accepts an implementation of Function interface: public class FunctionDemo { //API which accepts an implementation of //Function interface static void modifyTheValue(int valueToBeOperated, Function function){ int newValue = function.apply(valueToBeOperated); /* * Do some operations using the new value. */ System.out.println(newValue); } } Now lets look at the code which invokes this API: public static void main(String[] args) { int incr = 20; int myNumber = 10; modifyTheValue(myNumber, val-> val + incr); myNumber = 15; modifyTheValue(myNumber, val-> val * 10); modifyTheValue(myNumber, val-> val - 100); modifyTheValue(myNumber, val-> "somestring".length() + val - 100); } You can see that the lambda expressions being created accept one parameter and return some value. I will update soon about the various APIs which use this Function interface as a parameter. Meanwhile the complete code is: public class FunctionDemo { public static void main(String[] args) { int incr = 20; int myNumber = 10; modifyTheValue(myNumber, val-> val + incr); myNumber = 15; modifyTheValue(myNumber, val-> val * 10); modifyTheValue(myNumber, val-> val - 100); modifyTheValue(myNumber, val-> "somestring".length() + val - 100); } //API which accepts an implementation of //Function interface static void modifyTheValue(int valueToBeOperated, Function function){ int newValue = function.apply(valueToBeOperated); /* * Do some operations using the new value. */ System.out.println(newValue); } } and the output is: 30 150 -85 -75 In the coming posts I will try to explore the other interfaces present in java.util.function package. Note: The above code was compiled using the JDK downloaded from here and Netbeans 8 nightly builds.
April 6, 2013
· 11,990 Views
article thumbnail
Introduction to Functional Interfaces – A Concept Recreated in Java 8
Any Java developer around the world would have used at least one of the following interfaces: java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable. There is some common feature among the stated interfaces and that feature is they have only one method declared in their interface definition. There are lot more such interfaces in JDK and also lot more created by java developers. These interfaces are also called Single Abstract Method interfaces (SAM Interfaces). And a popular way in which these are used is by creating Anonymous Inner classes using these interfaces, something like: public class AnonymousInnerClassTest { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println("A thread created and running ..."); } }).start(); } } With Java 8 the same concept of SAM interfaces is recreated and are called Functional interfaces. These can be represented using Lambda expressions, Method reference and constructor references(I will cover these two topics in the upcoming blog posts). There’s an annotation introduced- @FunctionalInterface which can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface. Lets try to have a look at a simple functional interface with only one abstract method: @FunctionalInterface public interface SimpleFuncInterface { public void doWork(); } The interface can also declare the abstract methods from the java.lang.Object class, but still the interface can be called as a Functional Interface: @FunctionalInterface public interface SimpleFuncInterface { public void doWork(); public String toString(); public boolean equals(Object o); } Once you add another abstract method to the interface then the compiler/IDE will flag it as an error as shown in the screenshot below: Interface can extend another interface and in case the Interface it is extending in functional and it doesn’t declare any new abstract methods then the new interface is also functional. But an interface can have one abstract method and any number of default methods and the interface would still be called an functional interface. To get an idea of default methods please read here. @FunctionalInterface public interface ComplexFunctionalInterface extends SimpleFuncInterface { default public void doSomeWork(){ System.out.println("Doing some work in interface impl..."); } default public void doSomeOtherWork(){ System.out.println("Doing some other work in interface impl..."); } } The above interface is still a valid functional interface. Now lets see how we can use the lambda expression as against anonymous inner class for implementing functional interfaces: /* * Implementing the interface by creating an * anonymous inner class versus using * lambda expression. */ public class SimpleFunInterfaceTest { public static void main(String[] args) { carryOutWork(new SimpleFuncInterface() { @Override public void doWork() { System.out.println("Do work in SimpleFun impl..."); } }); carryOutWork(() -> System.out.println("Do work in lambda exp impl...")); } public static void carryOutWork(SimpleFuncInterface sfi){ sfi.doWork(); } } And the output would be … Do work in SimpleFun impl... Do work in lambda exp impl... In case you are using an IDE which supports the Java Lambda expression syntax(Netbeans 8 Nightly builds) then it provides an hint when you use an anonymous inner class as used above This was a brief introduction to the concept of functional interfaces in java 8 and also how they can be implemented using Lambda expressions.
March 29, 2013
· 211,566 Views · 18 Likes
article thumbnail
Introduction to Default Methods (Defender Methods) in Java 8
We all know that interfaces in Java contain only method declarations and no implementations and any non-abstract class implementing the interface had to provide the implementation. Lets look at an example: public interface SimpleInterface { public void doSomeWork(); } class SimpleInterfaceImpl implements SimpleInterface{ @Override public void doSomeWork() { System.out.println("Do Some Work implementation in the class"); } public static void main(String[] args) { SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl(); simpObj.doSomeWork(); } } Now what if I add a new method in the SimpleInterface? public interface SimpleInterface { public void doSomeWork(); public void doSomeOtherWork(); } and if we try to compile the code we end up with: $javac .\SimpleInterface.java .\SimpleInterface.java:18: error: SimpleInterfaceImpl is not abstract and does not override abstract method doSomeOtherWork() in SimpleInterface class SimpleInterfaceImpl implements SimpleInterface{ ^ 1 error And this limitation makes it almost impossible to extend/improve the existing interfaces and APIs. The same challenge was faced while enhancing the Collections API in Java 8 to support lambda expressions in the API. To overcome this limitation a new concept is introduced in Java 8 called default methods which is also referred to as Defender Methods or Virtual extension methods. Default methods are those methods which have some default implementation and helps in evolving the interfaces without breaking the existing code. Lets look at an example: public interface SimpleInterface { public void doSomeWork(); //A default method in the interface created using "default" keyword default public void doSomeOtherWork(){ System.out.println("DoSomeOtherWork implementation in the interface"); } } class SimpleInterfaceImpl implements SimpleInterface{ @Override public void doSomeWork() { System.out.println("Do Some Work implementation in the class"); } /* * Not required to override to provide an implementation * for doSomeOtherWork. */ public static void main(String[] args) { SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl(); simpObj.doSomeWork(); simpObj.doSomeOtherWork(); } } and the output is: Do Some Work implementation in the class DoSomeOtherWork implementation in the interface This is a very brief introduction to default methods. One can read in depth about default methods here.
March 28, 2013
· 27,356 Views
article thumbnail
Extracting the Elements of the Java Collection- The Java 8 Way
We all have extensively used Collection classes like List, Map and their derived versions. And each time we used them we had to iterate through them to either find some element or update the elements or find different elements matching some condition. Consider a List of Person as shown below: List personList = new ArrayList<>(); personList.add(new Person("Virat", "Kohli",22)); personList.add(new Person("Arun", "Kumar",25)); personList.add(new Person("Rajesh", "Mohan", 32)); personList.add(new Person("Rahul", "Dravid", 35)); To find out all the Person instances with age greater than 30, we would do: List olderThan30OldWay = new ArrayList<>(); for ( Person p : personList){ if ( p.age >= 30){ olderThan30OldWay.add(p); } } System.out.println(olderThan30OldWay); and this gives me the output as: [Rajesh Mohan, 32, Rahul Dravid, 35] The code is easy to write, but is it not a bit more verbose, especially the iteration part? Why would we have to iterate? Would it not be cool if there was an API which would iterate the contents and give us the end result i.e we give the source List and use a series of method calls to get us the result List we are looking for? Yes, this is possible in other languages like Scala, Groovy which support passing closures and also support internal iteration. But is there a solution for Java developers? Yes, this exact problem is being solved by introducing support for Lambda Expressions(closures) and a enhanced Collection API to leverage the lambda expression support. The sad news is that it’s going to be part of Java 8 and will take some time to be into mainstream development. Leveraging the Java 8 enhancements to the above scenario As I said before the Collections API is being enhanced to support the use of Lambda Expression and more about it can be read here. Instead of adding all the new APIs to the Collection class the JDK team created a new concept called “Stream” and added most of the APIs in that class. “Stream” is a sequence of elements obtained from the Collection from which it is created. To read more about the origin of Stream class please refer to this document. To implement the example I started with using the enhancements in Java 8 we would be using few new APIs namely: stream(), filter(), collect(), Collectors.toCollection(). stream(): Uses the collection on which this API is called to create an instance of Stream class. filter():This method accepts a lambda expression which takes in one parameter and returns a boolean value. This lambda expression is written as a replacement for implementing the Predicate class. collect(): There are 2 overloaded versions of this method. The one I am using here takes an instance of Collector. This method takes the contents of the stream and constructs another collection. This construction logic is defined by the Collector. Collectors.toCollection(): Collectors is a factory for Collector. And the toCollection() takes a Lambda expression/Method reference which should return a new instance of any derivatives of Collection class. With brief introduction to the APIs used, let me show the code which is equivalent to the first code sample: List olderThan30 = //Create a Stream from the personList personList.stream(). //filter the element to select only those with age >= 30 filter(p -> p.age >= 30). //put those filtered elements into a new List. collect(Collectors.toCollection(() -> new ArrayList())); System.out.println(olderThan30); The above code uses both Internal iteration and lambda expressions to make it intuitive, concise and soothing to the eye. If you are not familiar with the idea of Lambda Expressions, check out my previous entry which covers in brief about Lambda expressions.
March 23, 2013
· 77,323 Views · 2 Likes
article thumbnail
Using Lambda Expression to Sort a List in Java 8 using NetBeans Lambda Support
As part of JSR 335Lambda expressions are being introduced to the Java language from Java 8 onwards and this is a major change in the Java language.
March 21, 2013
· 345,343 Views · 6 Likes
article thumbnail
Using JAXB to Generate Java Objects from XML Document
Quite sometime back I had written about Using JAXB to generate XML from the Java, XSD. And now I am writing how to do the reverse of it i.e generating Java objects from the XML document. There was one comment mentioning that JAXB reference implementation and hence in this article I am making use of the reference implementation that is shipped with the JDK. Firstly the XML which I am using to generate the java objects are: Sanaulla Seagate External HDD August 24, 2010 6776.5 Benq HD Monitor August 24, 2012 15000 And the XSD to which it conforms to is: The XSD has already been explained and one can find out more by reading this article. I create a class: XmlToJavaObjects which will drive the unmarshalling operation and before I generate the JAXB Classes from the XSD, the directory structure is: I go ahead and use the xjc.exe to generate JAXB classes for the given XSD: $> xjc expense.xsd and I now refresh the directory structure to see these generated classes as shown below: With the JAXB Classes generated and the XML data available, we can go ahead with the Unmarshalling process. Unmarshalling the XML: To unmarshall: We need to create JAXContext instance. Use JAXBContext instance to create the Unmarshaller. Use the Unmarshaller to unmarshal the XML document to get an instance of JAXBElement. Get the instance of the required JAXB Root Class from the JAXBElement. Once we get the instance of the required JAXB Root class, we can use it to get the complete XML data in Java objects. The code to unmarshal the XML data is given below: package problem; import generated.ExpenseT; import generated.ItemListT; import generated.ItemT; import generated.ObjectFactory; import generated.UserT; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class XmlToJavaObjects { /** * @param args * @throws JAXBException */ public static void main(String[] args) throws JAXBException { //1. We need to create JAXContext instance JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); //2. Use JAXBContext instance to create the Unmarshaller. Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); //3. Use the Unmarshaller to unmarshal the XML document to get an instance of JAXBElement. JAXBElement unmarshalledObject = (JAXBElement)unmarshaller.unmarshal( ClassLoader.getSystemResourceAsStream("problem/expense.xml")); //4. Get the instance of the required JAXB Root Class from the JAXBElement. ExpenseT expenseObj = unmarshalledObject.getValue(); UserT user = expenseObj.getUser(); ItemListT items = expenseObj.getItems(); //Obtaining all the required data from the JAXB Root class instance. System.out.println("Printing the Expense for: "+user.getUserName()); for ( ItemT item : items.getItem()){ System.out.println("Name: "+item.getItemName()); System.out.println("Value: "+item.getAmount()); System.out.println("Date of Purchase: "+item.getPurchasedOn()); } } } And the output would be: Do drop in your queries/feedback as comments and I will try to address them at the earliest.
January 29, 2013
· 168,889 Views

Comments

Using Google reCaptcha With Spring Boot Application

Jun 27, 2018 · Duncan Brown

Integrating with Captcha is independent of Spring Security. So your API that verifies the captcha need not be protected by Spring security.

Deploying Spring Apps to Tomcat (Without web.xml)

Nov 21, 2017 · Mike Gates

It would have been quite simple. But I wanted to do it without using Spring boot and try it out. And moreover not all of them would want to move to spring boot

Aggregate and Index Data into Elasticsearch Using Logstash and JDBC

Nov 03, 2017 · Sarah Davis

Billions of records I don't honk. But you wouldn't want to index billions of records from db. So you should think of better alternatives.

Getting to Know java.nio.file.Path (Part 1)

Aug 24, 2017 · Mike Gates

Which JDK version are u using? Its a new API added in Java 7 and its not deprecated so far even in Java 9 (http://download.java.net/java/jdk9/docs/api/java/nio/file/Path.html)

Getting to Know java.nio.file.Path (Part 1)

Aug 23, 2017 · Mike Gates

The text right under the heading - this is added by DZone. My original article never had that (https://sanaulla.info/2017/08/09/getting-to-know-about-java-nio-file-path-1/)


Sorry I didn't notice it.

Getting to Know java.nio.file.Path (Part 1)

Aug 23, 2017 · Mike Gates

Thanks a lot. I will update the same with your notes.

Getting to Know java.nio.file.Path (Part 1)

Aug 22, 2017 · Mike Gates

Nowhere does the introduction say "Java 9 will be introducing". The introductory paragraph says Java has changed over the versions 7,8 and 9.

And then in the subsequent paragraph, I mention that one of the new features introduced in Java 7.

Getting to Know java.nio.file.Path (Part 1)

Aug 22, 2017 · Mike Gates

Its Java 7 to be specific. :) But there is not much awareness about these utility APIs added in Java 7 to support File handling.

Creating Internal DSLs in Java & Java 8

Jun 05, 2013 · James Sugrue

I am not very proficient with Groovy and hence I picked Java for my examples. Down the line once I am familiar with it, I might port the same to Groovy and may be compare the two.

Creating Internal DSLs in Java & Java 8

Jun 05, 2013 · James Sugrue

I am not very proficient with Groovy and hence I picked Java for my examples. Down the line once I am familiar with it, I might port the same to Groovy and may be compare the two.

Data filtering with PHP's Filter extension

Jun 05, 2013 · Mr B Loid

I am not very proficient with Groovy and hence I picked Java for my examples. Down the line once I am familiar with it, I might port the same to Groovy and may be compare the two.

Data filtering with PHP's Filter extension

Jun 05, 2013 · Mr B Loid

I am not very proficient with Groovy and hence I picked Java for my examples. Down the line once I am familiar with it, I might port the same to Groovy and may be compare the two.

Structured Data Event Stream Processing with Smooks v1.1

May 28, 2013 · Tom Fennelly

Great! Will try out and post my experiences. Will also check out the code.

Parsing XML using DOM, SAX and StAX Parser in Java

May 28, 2013 · mitchp

I have covered it in different posts.

Train Wreck Pattern – A much improved implementation in Java 8

May 15, 2013 · James Sugrue

Agree, and documentation is what we fail to do most of the times.

Using Tatoo as front end of javac

May 15, 2013 · Mr B Loid

Agree, and documentation is what we fail to do most of the times.

Using Tatoo as front end of javac

May 15, 2013 · Mr B Loid

Agree, and documentation is what we fail to do most of the times.

Train Wreck Pattern – A much improved implementation in Java 8

May 15, 2013 · James Sugrue

Agree, and documentation is what we fail to do most of the times.

Lorem ipsum django page

May 15, 2013 · Alexander Artemenko

Cool! May be I should add it to my post. Can I?

Lorem ipsum django page

May 15, 2013 · Alexander Artemenko

Cool! May be I should add it to my post. Can I?

Lorem ipsum django page

May 14, 2013 · Alexander Artemenko

Agree that we can put it in an Util.

I got another approach using Google Guava as a comment on my blog.

Lorem ipsum django page

May 14, 2013 · Alexander Artemenko

Agree that we can put it in an Util.

I got another approach using Google Guava as a comment on my blog.

Lorem ipsum django page

May 14, 2013 · Alexander Artemenko

I never thought of this. Really cool. Thanks for sharing it!

Lorem ipsum django page

May 14, 2013 · Alexander Artemenko

I never thought of this. Really cool. Thanks for sharing it!

RESTful .NET

May 12, 2013 · Alvin Ashcraft

the support for lambda expressions should have been there in the language quite sometime back- may be in the anonymous inner class time frame. But functional programming had not gone mainstream. But off late there has been a lot of focus on functional programming and lot of the concepts in functional programming help in writing good concurrent code.

Its always important to identify where to fit in the feature and how to use it. The Java 8 release was delayed due to the importance given to the security fixes. Apart from lambda expressions there are quite a lot features in Java 8 which I am not aware of. And I am sure there would be performance related features aiming the quality of the product.

RESTful .NET

May 12, 2013 · Alvin Ashcraft

the support for lambda expressions should have been there in the language quite sometime back- may be in the anonymous inner class time frame. But functional programming had not gone mainstream. But off late there has been a lot of focus on functional programming and lot of the concepts in functional programming help in writing good concurrent code.

Its always important to identify where to fit in the feature and how to use it. The Java 8 release was delayed due to the importance given to the security fixes. Apart from lambda expressions there are quite a lot features in Java 8 which I am not aware of. And I am sure there would be performance related features aiming the quality of the product.

Easy Python Decorators with the decorator decorator

Mar 24, 2013 · Mr B Loid

The reply for this would be same as the one posted here. New languages being introduced learn from the past languages and keep evolving. But something coming into Java would be useful for enterprises who have their investment in Java. And convincing such enterprises to use Scala is not always an easy. For that matter enterprises picking Java 8 for immediate development is another thing that is not possible.

Easy Python Decorators with the decorator decorator

Mar 24, 2013 · Mr B Loid

The reply for this would be same as the one posted here. New languages being introduced learn from the past languages and keep evolving. But something coming into Java would be useful for enterprises who have their investment in Java. And convincing such enterprises to use Scala is not always an easy. For that matter enterprises picking Java 8 for immediate development is another thing that is not possible.

Extracting the Elements of the Java Collection- The Java 8 Way

Mar 24, 2013 · James Sugrue

The reply for this would be same as the one posted here. New languages being introduced learn from the past languages and keep evolving. But something coming into Java would be useful for enterprises who have their investment in Java. And convincing such enterprises to use Scala is not always an easy. For that matter enterprises picking Java 8 for immediate development is another thing that is not possible.

Easy Python Decorators with the decorator decorator

Mar 24, 2013 · Mr B Loid

The reply for this would be same as the one posted here. New languages being introduced learn from the past languages and keep evolving. But something coming into Java would be useful for enterprises who have their investment in Java. And convincing such enterprises to use Scala is not always an easy. For that matter enterprises picking Java 8 for immediate development is another thing that is not possible.

Extracting the Elements of the Java Collection- The Java 8 Way

Mar 24, 2013 · James Sugrue

The reply for this would be same as the one posted here. New languages being introduced learn from the past languages and keep evolving. But something coming into Java would be useful for enterprises who have their investment in Java. And convincing such enterprises to use Scala is not always an easy. For that matter enterprises picking Java 8 for immediate development is another thing that is not possible.

Extracting the Elements of the Java Collection- The Java 8 Way

Mar 24, 2013 · James Sugrue

The reply for this would be same as the one posted here. New languages being introduced learn from the past languages and keep evolving. But something coming into Java would be useful for enterprises who have their investment in Java. And convincing such enterprises to use Scala is not always an easy. For that matter enterprises picking Java 8 for immediate development is another thing that is not possible.

Extracting the Elements of the Java Collection- The Java 8 Way

Mar 24, 2013 · James Sugrue

Really cannot compare with the likes of Groovy and Scala as those concepts were part of the language since their inception. But adding such a huge functionality in an already well established language is a really tasking and risky move. But hats off to the engineers who worked on it to give Java developers something to atleast fancy about.
Easy Python Decorators with the decorator decorator

Mar 24, 2013 · Mr B Loid

Really cannot compare with the likes of Groovy and Scala as those concepts were part of the language since their inception. But adding such a huge functionality in an already well established language is a really tasking and risky move. But hats off to the engineers who worked on it to give Java developers something to atleast fancy about.
Easy Python Decorators with the decorator decorator

Mar 24, 2013 · Mr B Loid

Really cannot compare with the likes of Groovy and Scala as those concepts were part of the language since their inception. But adding such a huge functionality in an already well established language is a really tasking and risky move. But hats off to the engineers who worked on it to give Java developers something to atleast fancy about.
Extracting the Elements of the Java Collection- The Java 8 Way

Mar 24, 2013 · James Sugrue

Really cannot compare with the likes of Groovy and Scala as those concepts were part of the language since their inception. But adding such a huge functionality in an already well established language is a really tasking and risky move. But hats off to the engineers who worked on it to give Java developers something to atleast fancy about.
Top 20 Java Websites You Should Know

May 12, 2012 · Yong Mook Kim

Sites like Roseindia, Java2S and the like are not the goto sites for learning Java. And JavaRanch began much before and not 2004 as mentioned in the article. I dont think one would require 20 sources. Websites like InnoQ dont feature.
Computers will never take the place of books

Mar 29, 2012 · Ahmad Mushtaq

Yes this was a very obvious example, as pointed in my other comment there has been lot of research put in this and there by a tool was developed (an eclipse plugin) as an implementation of the research.

The research done on this is a pretty good read

Computers will never take the place of books

Mar 29, 2012 · Ahmad Mushtaq

Yes this was a very obvious example, as pointed in my other comment there has been lot of research put in this and there by a tool was developed (an eclipse plugin) as an implementation of the research.

The research done on this is a pretty good read

Computers will never take the place of books

Mar 29, 2012 · Ahmad Mushtaq

Yes this was a very obvious example, as pointed in my other comment there has been lot of research put in this and there by a tool was developed (an eclipse plugin) as an implementation of the research.

The research done on this is a pretty good read

Computers will never take the place of books

Mar 29, 2012 · Ahmad Mushtaq

There's lot of research involved in how JDeodrant identifies the code smells. They have research papers linked from their project site. I was going through 1 (about Extract method) and its more of what we do manually which is being automated. I havent got time to read other papers on this.

I am not sure how much of industry applicable it can be, I was curious as to how they would do the refactoring ( also driven by the fact that I was reading Martin Fowlers Refactoring ;) ) so thought of trying out the tool. As pointed out a better example would have been much useful and also the fact that other options for refactoring were not tried.

Computers will never take the place of books

Mar 29, 2012 · Ahmad Mushtaq

There's lot of research involved in how JDeodrant identifies the code smells. They have research papers linked from their project site. I was going through 1 (about Extract method) and its more of what we do manually which is being automated. I havent got time to read other papers on this.

I am not sure how much of industry applicable it can be, I was curious as to how they would do the refactoring ( also driven by the fact that I was reading Martin Fowlers Refactoring ;) ) so thought of trying out the tool. As pointed out a better example would have been much useful and also the fact that other options for refactoring were not tried.

Computers will never take the place of books

Mar 29, 2012 · Ahmad Mushtaq

There's lot of research involved in how JDeodrant identifies the code smells. They have research papers linked from their project site. I was going through 1 (about Extract method) and its more of what we do manually which is being automated. I havent got time to read other papers on this.

I am not sure how much of industry applicable it can be, I was curious as to how they would do the refactoring ( also driven by the fact that I was reading Martin Fowlers Refactoring ;) ) so thought of trying out the tool. As pointed out a better example would have been much useful and also the fact that other options for refactoring were not tried.

Top 20 Highly Useful Google APIs For Developers And Designers

Aug 05, 2011 · Vashu Singh

this gives a list of all the available (active) google apis, might have been more filtered.
The Big Learning Scala List

Jun 17, 2011 · Dev Stonez

not much of a different reading list though.

User has been successfully modified

Failed to modify user

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: