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

The Latest Languages Topics

article thumbnail
Changing MySQL Binary Log Files Location to Another Directory
What is the Default? Usually in most installations, binary log files are located in the MySQL default directory (/var/lib/mysql) just next to the data files. Why Should I Move the Binary Logs to Another Directory? Each data modification (INSERT, UPDATE, DELETE...) and data definition (ALTER, ADD, DROP...) statement that you perform in your server are recorded in the Log files. Therefore, each time you make any of these statements, you actually update both your data files and your log files. The result is high IO utilization that is focused on a specific disk area. A common recommendation in the database field is to separate these files to two different disks in order to get a better performance. How to Perform it? Change the log-bin variable in the my.cnf to log-bin=/path/to/new/directory/mysql-bin Purge as many files as you can (PURGE BINLOG...) in order to minimize the number of moved files (see stop 4). Stop the master (service mysql stop). Move the files to the new directory: mv /var/lib/mysql/mysql-bin.* /path/to/new/directory Start the master again (service mysql start). Bottom Line Few steps and your server is ready for more traffic and data. Keep Performing, Moshe Kaplan
June 30, 2013
by Moshe Kaplan
· 49,193 Views
article thumbnail
Jax-RS 2 and LongPolling based Chat Application
longpolling ; also known as reverse ajax or comet, is a push method that operates seamlessly in javascript aided web browsers. although advanced push techniques such as sse and websocket with html 5 are already available, either these technologies are still in the process of development or they are not supported entirely by web browsers, longpolling and similar techniques be in demand. in longpolling technique, the web browser makes a request to the server, and this request is suspended on the server until a ready response ( resource ) is founded. the pending http request is sent back to the available source web browser when a response is obtained. the web browser transmits a new polling message as soon as it gets the http response, and this process repeats itself until a new http response is ready.. from time to time, the failure of the pending polling request originating from server, web browser or current network environment can also be a matter. in this case, web browser takes the error information from the server, sent a request once more and then the polling starts again. in longpolling technique, xmlhttprequest object which is a javascript object can be used on the web browser side. forthcoming asyncronousresponse objects with jax-rs 2 can be used on the server side in terms of flexibility and convenience. now, i would like to share with you a chat application instance that contains the association of longpolling technique and jax-rs 2 within java ee 7 . dependent library chat application can easily operate on a servlet container, but available container environment must comply with the standard servlet 3 because jax-rs 2 uses forthcoming asynchronous handlers together with servlet 3 on the container. org.glassfish.jersey.containers jersey-container-servlet 2.0 note: jersey is the reference implementer library of the standard jax-rs. http://jersey.java.net/ jetty 9 or tomcat 7 can be used for the servlet 3 support . entry point of the chat application (rest endpoint) @applicationpath("app") public class app extends application { @override public set> getclasses() { set> sets=new hashset<>(); sets.add(chat.class); return sets; } } the above application class type object that is wrapped with @applicationpath notation contains the entry point of the chat application. the defined chat class into the hashset is described as a rest resource belonging to the chat application. chat resource @path("/chat") public class chat { final static map waiters = new concurrenthashmap<>(); final static executorservice ex = executors.newsinglethreadexecutor(); @path("/{nick}") @get @produces("text/plain") public void hangup(@suspended asyncresponse asyncresp, @pathparam("nick") string nick) { waiters.put(nick, asyncresp); } @path("/{nick}") @post @produces("text/plain") @consumes("text/plain") public string sendmessage(final @pathparam("nick") string nick, final string message) { ex.submit(new runnable() { @override public void run() { set nicks = waiters.keyset(); for (string n : nicks) { // sends message to all, except sender if (!n.equalsignorecase(nick)) waiters.get(n).resume(nick + " said that: " + message); } } }); return "message is sent.."; } } asyncresponse type parameter that is found as a parameter on hangup(..) method defines the longpolling response object which will be suspended on the server. while asyncresponse type objects can be provided from jax-rs environment automatically, these suspended objects can be submitted to the user (web browser) as a response at any time. the second parameter [ @pathparam("nick") string nick ] found on the hangup(..) method obtains the user nick name which is sent to the method on the url. the information about suspended asyncresponse objects belong to which user is needed subsequently. concurrenthashmap that is a structure of a concurrent map can be used for this purpose. in this way,each nick -> asyncresponse object that is sent to thehangup(..) method will be kept under record. the second method of the chat class sendmessage(..) can be accessed with http /post method and operates as restful method which derives chat messages from the web browser. when users submit a chat message with the knowledge of nick name to the server, sendmessage(..) restful method obtains this information from the method parameters, and this information is being transacted as asynchronous through the executorservice object. of course a simple thread can be used instead of executorservice object that is used in here. just as new thread( new runnable(){ … } ).start(); . the key issue here is the running of the sent message at the background and to prevent the interruption of default /post request, more precisely, to prevent the waiting of message information made push to all users. the nick -> asyncresponse pair that is filled in the previous hangup(..) method in the concurrenthashmap is consumed into the runnable task object which is found in the sendmessage(..) method, and this chat message is transmitted to all suspended asyncresponse objects except the user itself. the resume() method included in the asyncresponse objects allows the @suspended response object to respond. that is to say, ( suspend ) before, and then ( resume ) when chat message resource become ready. html components nick:message: post in the above html page, there are a nick input object, a text area object where the message will be entered and an html button where the message will be sent and these are lined in an html table object. the textarea is made as disabled initially because it is expected to enter the nick name firstly from the user when the application is started. when the user sends the first request (nick name), unchangeable state of this field is modified and is made message writable. also, when nick name is sent to the server (i.e. when the first polling request is made), html table row element which is a class type ( ) is hidden. chat application is required to provide xmlhttprequest objects and http requests as asynchronous. in this application we will benefit from jquery ajax library which facilitates these operations and uses xmlhttprequest objects in the background. in addition to jquery dependence, there is a chat.js script that was written by us in the project. chat.js // the polling function must be called once, //it will call itself recursively in case of error or performance. var poolit = function () { $.ajax({ type: "get", url: "/app/chat/" + $("#nick").val(), // access to the hangup(..) method datatype: "text", // incoming data type text success: function (message) { // the message is added to the element when it is received. $("ul").append("" + message + ""); poolit(); // link to the re-polling when a message is consumed. }, error: function () { poolit(); // start re-polling if an error occurs. } }); } // when the submit button is clicked; $("button").click(function () { if ($(".nick").css("visibility") === "visible") { // if line is visible; $("textarea").prop("disabled", false); // able to enter data $(".nick").css("visibility", "hidden"); // make line invisible; $("span").html("chat started.."); // information message // polling operation must be initiated at a time poolit(); } else // if it is not the first time ; $.ajax({ type: "post", // http post request url: "/app/chat/" + $("#nick").val(),// access to the sendmessage(..) method. datatype: "text", // incoming data type -> text data: $("textarea").val(), // chat message to send contenttype: "text/plain", // the type of the sent message success: function (data) { $("span").html(data); // it writes [message is sent..] if successful. // blink effect $("span").fadeout('fast', function () { $(this).fadein('fast'); }); } }); }); testing the application because the jetty 9.0.0.rc2 plugin is included in the pom.xml configuration file of the application, the application can be easily run with > mvn jetty:run-war command. the application can be accessed at http://localhost:8080/ after above goal run. you can access source code and live example follow the next url => http://en.kodcu.com/2013/06/jax-rs-2-and-longpolling-based-chat-application/
June 28, 2013
by Altuğ Altıntaş
· 7,742 Views
article thumbnail
Add, Delete & Get Attachment from a PDF Document in Java Applications
This technical tip shows how to Add, Delete & Get Attachment in a PDF Document using Aspose.Pdf for Java. In order to add attachment in a PDF document, you need to create a FileSpecification object with the file, which needs to be added, and the file description. After that the FileSpecification object can be added to EmbeddedFiles collection of Document object using add(..) method of EmbeddedFiles collection. The attachments of the PDF document can found in the EmbeddedFiles collection of the Document object. In order to delete all the attachments, you only need to call the delete(..) method of the EmbeddedFiles collection and then save the updated file using save method of the Document object. //Add attachment in a PDF document. //open document com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("input.pdf"); //setup new file to be added as attachment com.aspose.pdf.FileSpecification fileSpecification = new com.aspose.pdf.FileSpecification("sample.txt", "Sample text file"); //add attachment to document's attachment collection pdfDocument.getEmbeddedFiles().add(fileSpecification); // Save updated document containing table object pdfDocument.save("output.pdf"); //Delete all the attachments from the PDF document. //open document com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("input.pdf"); //delete all attachments pdfDocument.getEmbeddedFiles().delete(); //save updated file pdfDocument.save("output.pdf"); //Get an individual attachment from the PDF document. //open document com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("input.pdf"); //get particular embedded file com.aspose.pdf.FileSpecification fileSpecification = pdfDocument.getEmbeddedFiles().get_Item(1); //get the file properties System.out.printf("Name: - " + fileSpecification.getName()); System.out.printf("\nDescription: - " + fileSpecification.getDescription()); System.out.printf("\nMime Type: - " + fileSpecification.getMIMEType()); // get attachment form PDF file try { InputStream input = fileSpecification.getContents(); File file = new File(fileSpecification.getName()); // create path for file from pdf file.getParentFile().mkdirs(); // create and extract file from pdf java.io.FileOutputStream output = new java.io.FileOutputStream(fileSpecification.getName(), true); byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = input.read(buffer))) output.write(buffer, 0, n); // close InputStream object input.close(); output.close(); } catch (IOException e) { e.printStackTrace(); } // close Document object pdfDocument.dispose();
June 27, 2013
by Sheraz Khan
· 3,818 Views
article thumbnail
QuartzDesk - Advanced Java Quartz Scheduler Management And Monitoring UI
Hi, I'm excited to announce the release of our QuartzDesk product. QuartzDesk is an advanced Java Quartz scheduler management and monitoring GUI / tool with many powerful and unique features. To name just a few: Support for Quartz 1.x and 2.x schedulers. Persistent job execution history. Job execution log message capturing. Notifications (email, all popular IM protocols, web-service). Interactive execution statistics and charts. REST API for job / trigger / scheduler monitoring. QuartzAnywhere web-service to manage / monitor Quartz schedulers from applications. and more To keep this announcement short, I kindly refer you to the QuartzDesk Features page for details and screenshots. The product is aimed at Java developers and system administrators. Jan Moravec (Founder) & The QuartzDesk Team
June 26, 2013
by Jan Moravec
· 5,841 Views
article thumbnail
Recreating "Snake" using HTML5 Canvas and KineticJS
in the beginning, before you start making a new game, you need to prepare the concept (logic) of the game. you need to have a clear idea about it. you need to develop a high level of understanding, without going into the fine details. in the first phase, we find the answer "what" we want to create, and we reserve the answers to "how to do" for the upcoming stages. let me illustrate this method with an example. let’s develop the popular game "snake". this game was popular long ago, even on consoles and old cell phones with text user interfaces. concept of the game initially a small sized snake appears on the screen which keeps running for the rest of the game like endless runner. player can change the direction only. speed of the snake increases with time. length of the snake also increases after eating randomly appearing food. increasing length and speed of the snake adds difficulty to the game over time. we can use storyboard technique to graphically represent our idea. according to wikipedia: "storyboards are graphic organizers in the form of illustrations or images displayed in sequence for the purpose of pre-visualizing a motion picture, animation, motion graphic or interactive media sequence." here is our storyboard: for your convenience i am adding the description of each storyboard screen: screen 1: snake (square) waiting for a key-press to start moving. circle is shown as food item. screen 2: after eating (hitting) food item the snake’s length increases and food item appears at another random location. screen 3: snake can re-enter the playing area from the opposite edge after leaving it from an edge. screen 4: snake dies after biting itself here, uml statechart diagram may also help to understand different "states" of the snake during a game. according to wikipedia: "a state diagram is a type of diagram used in computer science and related fields to describe the behavior of systems. state diagrams require that the system described is composed of a finite number of states; sometimes, this is indeed the case, while at other times this is a reasonable abstraction. many forms of state diagrams exist, which differ slightly and have different semantics." here is our statechart diagram: in the diagram, edges represent the actions and the ovals represent the states a snake is in after the specific action. game starts with an idle snake. you can move snake in all four directions using arrow keys. while moving in any direction when a key is pressed, the snake goes to "deciding" state to determine which key was pressed and then again goes to the respective direction. snake eats food when encountered while moving. there is also a "dead" state if snake hits itself while moving. you may also want to add more state diagrams for prominent objects to clarify. there are other uml diagrams which may help you describe your game project. these diagrams are not only helpful for yourself but also helps if you are working in a team making team communication easy and unambiguous. structure of the game the play area in virtually divided into a 200?200-pixel grid having 10?10-pixel cells. the initgrid() function prepares the grid. as you can guess from the code that the snake’s width and height is also 10?10 pixels. so as a programming trick, i used the height and width of the snake to represent the dimensions of a single cell. function initgrid() { //*****initialize grid ... cell = {"col":col*snakeheight, "row":row*snakewidth}; ... } you are right if you are thinking about the usage of this virtual grid. in fact, during the initialization of the game structure, this grid helps us to identify the places (cells…to be precise) where we can put the snake and food randomly. a random number generator function randomcell(cells) gives us a random number which we use as an index to the grid array and get the coordinates stored against that specific index. here is the random number generator function… function randomcell(cells) { return math.floor((math.random()*cells)); } math.random and math.floor are both javascript functions. the following code shows the usage of grid and random number generator function… var initsnakeposition = randomcell(grid.length - 1); //pass number of cells var snakepart = new kinetic.rect({ name: 'snake', x: grid[initsnakeposition].col, y: grid[initsnakeposition].row, width: snakewidth, height: snakeheight, fill: 'black', }); kinetic.rect constructor constructs the initial single rectangle to represent the snake. later, when the snake would grow after eating the food, we would be adding more rectangles. each rectangle is assigned a number to represent its actual position in the snake array. as there is only one rectangle at the moment, we assign it position 1. snakepart.position = snakeparts; snakeparts is a counter which keeps counting the number of parts in the snake array. you might be wondering that we have not created any array of snakepart objects but we are talking about array? in fact if you keep the value of name: property same for all the snakepart objects, kineticjs would return all those objects as an array if you ask like this… var snakepartsarray = stage.get('.snake'); you will see the usage of this feature in action later in the code. snakepart.position shows how you can add custom properties to kinetic.rect object dynamically, or to any other object. why we need the position when kineticjs can return indexed array? please don’t bother yourself with this question at the moment, you will find the answer if you keep reading. two more identifications are required to make the job more easy to manage the snake actions and movements, snake head and tail. there is only one snake-part (rectangle) to begin with therefore both head and tail pointers point to the same rectangle. var snaketail; var snakehead; ... snakehead = snakepart; snaketail = snakepart; we are done with setting up the snake. to construct the food which is a simple circle of radius 5 see the following code… var randomfoodcell = randomcell(grid.length - 1); var food = new kinetic.circle({ id: 'food', x:grid[randomfoodcell].col+5, y:grid[randomfoodcell].row+5, radius: 5, fill: 'black' }); kinetic.circle constructs the food for our snake game. here adding +5 to x and y coordinates to place the circle exactly in the centre of a 10?10 cell provided that the radius of the circle is 5. after we are done with the creation of basic shapes for our game and their positions on the game area/grid we need to add those shapes to a kinetic.layer and then add that layer to the kinetic.stage. // add the shapes (sanke and food) to the layer var layer = new kinetic.layer(); layer.add(snakepart); layer.add(food); // add the layer to the stage stage.add(layer); the ‘stage’ object used in the cod above has already been created in the beginning using the following code snippet… //stage var stagewidth = 200; var stageheight = 200; var stage = new kinetic.stage({ container: 'container', width: stagewidth, height: stageheight }); container property of stage needs to know the id of the div where we want to show our html5 canvas. initial screen of the game looks like this once our structure is complete… after setting up the environment/structure let’s deal with the user stories / use cases one by one. the main game loop executing after a set interval var gameinterval = self.setinterval(function(){gameloop()},70); setinterval is a javascript function which makes a function called asynchronously that is passed as an argument, after the set intervals. in our case gameloop() is the function which drives the whole game. have a look at it… function gameloop() { if(checkgamestatus()) move(where); else { clearinterval(gameinterval);//stop calling gameloop() alert('game over!'); } } well, the behaviour of gameloop() is pretty obvious. it moves the snake according to the arrow key pressed. and if snake hits himself then display a game over message to the player and also stop the asynchronous calls by calling a javascript clearinterval() method. to capture the arrow keys i have used the jquery’s keydown event handler to respond to the keys pressed. it sets a variable ‘where’ that is eventually used by gameloop() to pass the code to actual move() function. $( document ).ready(function() { $(document).keydown(function(e) { switch(e.keycode) { // user pressed "up" arrow case up_arrow: where = up_arrow; break; // user pressed "down" arrow case down_arrow: where = down_arrow; break; // user pressed "right" arrow case right_arrow: where = right_arrow; break; // user pressed "left" arrow case left_arrow: where = left_arrow; break; } }); }); as you might have guessed already that move() function is actual brain of this game and kinetic.animation handles the actual movement of the objects. all you have to do is to set new locations for your desired objects and then call start() method. to prevent the animation from running infinitely call stop() method immediately after start(). try removing the stop() method and see what happens yourself. function move(direction) { //super hint: only move the tail var foodhit = false; switch(direction) { case down_arrow: foodhit = snakeeatsfood(direction); var anim2 = new kinetic.animation(function(frame) { if(foodhit) { snakehead.sety(snakehead.gety()+10); growsnake(direction); if(snakehead.gety() == stageheight) snakehead.sety(0); relocatefood(); } else { snaketail.sety(snakehead.gety()+10); snaketail.setx(snakehead.getx()); if(snaketail.gety() == stageheight) snaketail.sety(0); reposition(); } }, layer); anim2.start(); anim2.stop(); break; case up_arrow: ... ... move the snake snake is divided into small 10?10-pixels squares. the square on the front is head and the back most square is tail. the technique to move the snake is simple. we pick the tail and put it before the head except when there is only one snake part. the position number assigned to each part of the snake is out of sequence now. head and tail pointers are pointing towards wrong parts. we need to reposition the pointers and position numbers. it is done by calling reposition(). it works as shown in the diagram below… grow the snake when it eats food snake eats food when snake’s head is on the food. once this condition is met, food is relocated to some other cell of the grid. the decision is made inside snakeeatsfood() function. the algorithm used is commonly known as bounding box collision detection for 2d objects. to grow the snake, head moves one step ahead by leaving an empty cell behind. a new rectangle is created at that empty cell to give the impression of the growth of the snake. //grow snake length after eating food function growsnake(direction) { switch(direction) { case down_arrow: var x, y; x = snakehead.getx(); y = snakehead.gety()-10; resetpositions(createsnakepart(x,y)); break; ... ... resetpositions() is almost identical to reposition(), see the detils under "move the snake" heading. assign the food a new location once the snake eats the food, the food is assigned a new location on the grid. relocatefood() performs this function. it prepares a new grid skipping all the positions occupied by the snake. after creating a new grid array, random number generator function generates a number which is used as an index to the grid and eventually we get the coordinates where we can place the food without overlapping the snake. re-enter the snake from the opposite edge when it meets and passes an edge this is really simple. we let snake finish its move, then we check if the head is out of boundary. if it is, we assign it new coordinates to make it appear from the opposite end. the code given below works when snake is moving down, for example… if(snakehead.gety() == stageheight) snakehead.sety(0); end the game when snake hits himself or it occupies the whole ground after each move, checkgamestatus() is called by gameloop() to check if snake has hit himself or not. logic is fairly simple. the same bounding box collision detection method for 2d objects is used here. if coordinates of head matches the coordinates of any other part of the snake, the snake is dead – game end! live demo download in package today we prepared another one good tutorial using kineticjs and html5. i hope you enjoyed our lesson. good luck and welcome back.
June 26, 2013
by Andrei Prikaznov
· 8,322 Views
article thumbnail
3 Ways to Optimize for Paging in MySQL
Lots and lots of web applications need to page through information. From customer records, to the albums in your itunes collection. So as web developers and architects, it’s important that we do all this efficiently. Start by looking at how you’re fetching information from your MySQL database. We’ve outlined three ways to do just that. 1. Paging without discarding records Ultimately we’re trying to avoid discarding records. After all if the server doesn’t fetch them, we save big. How else can we avoid this extra work. How about remember the last name. For example: select id, name, address, phone FROM customers WHERE id > 990 ORDER BY id LIMIT 10; Of course such a solution would only work if you were paging by ID. If you page by name, it might get messier as there may be more than one person with the same name. If ID doesn’t work for your application, perhaps returning paged users by USERNAME might work. Those would be unique: SELECT id, username FROM customers WHERE username > '[email protected]' ORDER BY username LIMIT 10; Paging queries can be slow with SQL as they often involve the OFFSET keyword which instructs the server you only want a subset. However it typically scans collects and then discards those rows first. With deferred join or by maintaining a place or position column you can avoid this, and speedup your database dramatically. 2. Try using a Deferred Join This is an interesting trick. Suppose you have pages of customers. Each page displays ten customers. The query will use LIMIT to get ten records, and OFFSET to skip all the previous page results. When you get to the 100th page, it’s doing LIMIT 10 OFFSET 990. So the server has to go and read all those records, then discard them. SELECT id, name, address, phone FROM customers ORDER BY name LIMIT 10 OFFSET 990; MySQL is first scanning an index then retrieving rows in the table by primary key id. So it’s doing double lookups and so forth. Turns out you can make this faster with a tricky thing called a deferred join. The inside piece just uses the primary key. An explain plan shows us “using index” which we love! SELECT id FROM customers ORDER BY name LIMIT 10 OFFSET 990; Now combine this using an INNER JOIN to get the ten rows and data you want: SELECT id, name, address, phone FROM customers INNER JOIN ( SELECT id FROM customers ORDER BY name LIMIT 10 OFFSET 990) AS my_results USING(id); That’s pretty cool! 3. Maintain a Page or Place column Another way to trick the optimizer from retrieving rows it doesn’t need is to maintain a column for the page, place or position. Yes you need to update that column whenever you (a) INSERT a row (b) DELETE a row ( c) move a row with UPDATE. This could get messy with page, but a straight place or position might work easier. SELECT id, name, address, phone FROM customers WHERE page = 100 ORDER BY name; Or with place column something like this: SELECT id, name, address, phone FROM customers WHERE place BETWEEN 990 AND 999 ORDER BY name;
June 25, 2013
by Sean Hull
· 21,249 Views
article thumbnail
How To Compare Strings In PHP
During any sort of programming you will always get situations where you need to compare values with each other, if the values are boolean or integers then the comparison is simple. But if you want to compare strings or parts of strings then there can be more to the comparison such as case of the string you are comparing. In this tutorial we are going to look at all the different ways you can compare strings in PHP using a number of built in PHP functions. == operator The most common way you will see of comparing two strings is simply by using the == operator if the two strings are equal to each other then it returns true. if('string1' == 'string1') { echo ' Strings match. '; } else { echo ' Strings do not match. '; } This code will return that the strings match, but what if the strings were not in the same case it will not match. If all the letters in one string were in uppercase then this will return false and that the strings do not match. if('string1' == 'STRING1') { echo ' Strings match. '; } else { echo ' Strings do not match. '; } This means that we can't use the == operator when comparing strings from user inputs, even if the first letter is in uppercase it will still return false. So we need to use some other function to help compare the strings. strcmp Function Another way to compare strings is to use the PHP function strcmp, this is a binary safe string comparison function that will return a 0 if the strings match. if(strcmp('string1', 'string1') == 0) { echo ' Strings match. '; } else { echo ' Strings do not match. '; } This if statement will return true and echo that the strings match. But this function is case sensitive so if one of the strings has an uppercase letter then the function will not return 0. strcasecmp Function The previous examples will not allow you to compare different case strings, the following function will allow you to compare case insensitive strings. if(strcasecmp('string1', 'string1') == 0) { echo ' Strings match. '; } else { echo ' Strings do not match. '; } if(strcasecmp('string1', 'String1') == 0) { echo ' Strings match. '; } else { echo ' Strings do not match. '; } if(strcasecmp('string1', 'STRING1') == 0) { echo ' Strings match. '; } else { echo ' Strings do not match. '; } All of these if statements will return that the strings match, which means that we can use this function when comparing strings that are input by the user.
June 25, 2013
by Paul Underwood
· 80,950 Views
article thumbnail
Integrating Chart JS Library With Java
"Chart JS Library" provides API for drawing different charts. Drawing is based on HTML CANVAS Element. Download Link:- http://www.chartjs.org/ In this Demo, "We will draw a Radar Chart .The Student input data is JSON in nature.The Servlet returns the JSON data when called by Jquery Ajax method.The Student Java class object is converted to JSON representation using GSON Library". The Java web project structure, The Student Servlet StudentJsonDataServlet.java , package com.sandeep.chartjs.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.sandeep.chartjs.data.Student; @WebServlet("/StudentJsonDataServlet") public class StudentJsonDataServlet extends HttpServlet { private static final long serialVersionUID = 1L; public StudentJsonDataServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List listOfStudent = getStudentData(); Gson gson = new Gson(); String jsonString = gson.toJson(listOfStudent); response.setContentType("application/json"); response.getWriter().write(jsonString); } private List getStudentData() { List listOfStudent = new ArrayList(); Student s1 = new Student(); s1.setName("Sandeep"); s1.setComputerMark(75); s1.setMathematicsMark(26); s1.setGeographyMark(91); s1.setHistoryMark(55); s1.setLitratureMark(36); listOfStudent.add(s1); return listOfStudent; } } The HTML markup chartjs-demo.html, The java script file for radar chart ts-chart-script.js, var TUTORIAL_SAVVY ={ /*Makes the AJAX calll (synchronous) to load a Student Data*/ loadStudentData : function(){ var formattedstudentListArray =[]; $.ajax({ async: false, url: "StudentJsonDataServlet", dataType:"json", success: function(studentJsonData) { console.log(studentJsonData); $.each(studentJsonData,function(index,aStudent){ formattedstudentListArray.push([aStudent.mathematicsMark,aStudent.computerMark,aStudent.historyMark,aStudent.litratureMark,aStudent.geographyMark]); }); } }); return formattedstudentListArray; }, /*Crate the custom Object with the data*/ createChartData : function(jsonData){ console.log(jsonData); return { labels : ["Mathematics", "Computers", "History","Literature", "Geography"], datasets : [ { fillColor : "rgba(255,0,0,0.3)", strokeColor : "rgba(0,255,0,1)", pointColor : "rgba(0,0,255,1)", pointStrokeColor : "rgba(0,0,255,1)", /*As Ajax response data is a multidimensional array, we have 'student' data in 0th position*/ data : jsonData[0] } ] }; }, /*Renders the Chart on a canvas and returns the reference to chart*/ renderStudenrRadarChart:function(radarChartData){ var context2D = document.getElementById("canvas").getContext("2d"), myRadar = new Chart(context2D). Radar(radarChartData,{ scaleShowLabels : false, pointLabelFontSize : 10 }); return myRadar; }, /*Initalization Student render chart*/ initRadarChart : function(){ var studentData = TUTORIAL_SAVVY.loadStudentData(); chartData = TUTORIAL_SAVVY.createChartData(studentData); radarChartObj = TUTORIAL_SAVVY.renderStudenrRadarChart(chartData); } }; $(document).ready(function(){ TUTORIAL_SAVVY.initRadarChart(); }); The response Json data format for student, The Firebug console shows DOM Element, The output in browser will look like,This radar chart shows the a student('sandeep') marks in different subject,
June 25, 2013
by Sandeep Patel
· 39,398 Views
article thumbnail
CDI | @Default and @Inject Annotations
cdi (context and dependency injection) is a complete and lightweight injection technology designed for java ee environment. special container objects (ejb,entitymanager), primitive data type elements and java class/objects written by you can be easily managed and injected as well through cdi. every defined java class in each application that configured in cdi standard is a candidate to become an injectable cdi object. this default behavior is provided by @default annotation that was installed per each java class secretly. there is an car class which has a vehicle implementation in the above uml diagram. a random int value is produced in sayvelocity() method and there is an output to the console such as “the car is running at the speed of x” in work() method, where x is represents a number produced randomly. @default // optional public class car implements vehicle { public string work() { return "car is working in "+ sayvelocity()+" kmh."; } public int sayvelocity(){ return threadlocalrandom.current().nextint(20, 240) ; } } if the above car class is in an application activated in cdi environment, it becomes a candidate to be an object managed by cdi. so, what is implied by the activation of cdi? first of all, necessary dependencies need to be included in the classpath for the activation of cdi environment. if you are using an application server like glassfish, cdi can be used without any extra definition because of the existence of cdi libraries on the application server. but if your application is a java se application or is running in lightweight containers such as tomcat, jetty; a cdi library must be added to the project. the reference library of cdi technology is the jboss weld archetype. for this reason, if jboss weld dependencies are added to the project such as the following, first phase of the cdi activation is realized. org.jboss.weld.se weld-se 1.1.10.final to activate the cdi environment, a blank cdi configuration file named beans.xml must be in the application as a requirement of the standard. this file must be located on the /meta-inf/beans.xml path for java se applications and /web-inf/beans.xml path for java ee web applications. the existence necessity of this file may sound silly initially, but the existence of beans.xml in the directories specified above can be considered as a permission given to the container in order to activate cdi environment. activation of cdi environment is automatically started in java ee web applications when beans.xml file is encountered in the /web-inf directory. but it is not the same for a java se application, starting a cdi container is the developer’s job. this case can be seen clearly if you pay attention to the following gallery class: public class gallery { @inject // injection point private vehicle vehicle; public static void main(string[] args) { weld weld = new weld(); weldcontainer weldcontainer = weld.initialize(); gallery gallery = weldcontainer.instance().select(gallery.class).get(); string message= gallery.vehicle.work(); system.out.println("> "+message); } } weldcontainer type object reference in gallery class access to a cdi object which represents the initiated container environment and after this point, cdi objects are accessible and can be made injection procedures through weldcontainer object. after this point, it is used by adopting a cdi object that is a gallery class type through the container instance. in here, a programmatic access to the gallery object is provided. programmatic access is required for the startup of java se applications (as in spring), but you can easily access to all cdi objects in the environment also by annotation-based injection method through the obtained gallery cdi object, e.g. [ private @inject vehicle vehicle; ] an output as the following occurs when the gallery class is being run; the real content and sample code can be accessed in http://en.kodcu.com/2013/06/cdi-default-and-inject-annotations/ hope to see you again..
June 25, 2013
by Altuğ Altıntaş
· 33,796 Views
article thumbnail
Implementing Memcached a Servlet Filter for Spring MVC-Based RESTful Services
I have a number of Spring MVC based RESTful services that return JSON. In 90% of the cases, the state of objects these services return will not change within a 24 hour period. This makes them (the JSON objects) perfect candidates for simple caching enabled by memcached. The idea was to have every request to Spring controllers intercepted, cache key generated and checked against the cache. If the key and corresponding value (JSON string) is available (a cache hit), it is returned to the caller as-is without making a full round trip to the database. However, if the cache has no entry for the key and hence no corresponding value (a cache miss), the call is forwarded to the controller, which in turn calls the logic to fetch desired object from the database and not only return it to the caller but also update the cache with the returned content. Keys are generated using the URL of the service in case of GET requests and the URL concatenated with POSTed input (as JSON) in case of POST requests. The resultant strings are encoded with MD5 to come up with a 32 character cache key which is well within the 250 character key length limit of memcached. Performance impact of using MD5 is yet to be evaluated during our load testing cycle. I started off trying to get hold of JSON response in the postHandle method of a Spring HandlerInterceptor. However since we are using @ResponseBody annotation in our controller, the JSON would be written directly to the stream. The ModelAndView was of course null because of this reason. If we removed the annotation and returned ModelAndView from the controller, the intended JSON object got enclosed in a map wrapper. A quick question on stack overflow didn’t help as the only suggestion I got was to extract my original object from the map wrapper. I wanted to keep this option (as discussed here as well ) as my last resort. The solution I eventually came up with involved Replacing the HandlerInterceptor with Servlet Filters Using DelegatingFilterProxy to make my filters spring application context aware Using HttpServletRequestWrapper to get control of the POST request body in the filter on the way in Using HttpServletResponseWrapper to get control of the response content in the filter on the way out True, its probably a more complex solution than just overriding MappingJacksonJsonView and extracting my JSON object, but it is more generic as it does not assume that all my content will always be JSON. Lets first start with the filter definition in the web.xml cacheFilter org.springframework.web.filter.DelegatingFilterProxy ... cacheFilter /* A standard filter configuration except for the fact that the filter class is always going to be org.springframework.web.filter.DelegatingFilterProxy. Where do you specify your own class ? As a bean in your spring context xml. The name of the filter and the name of the bean must be the same for the delegation to happen. Using the DelegatingFilterProxy allowed me to use my Filters with Spring. I can inject my dependencies as I would normally. Next, lets look at my MemcacheFilter filter Memcache Filter Class public class MemcacheFilter implements Filter { private static Logger logger = Logger.getLogger(MemcacheFilter.class); private CacheConfig cacheConfig; /** * Memcached lookup is being performed in this method. Firstly, keys are * generated depending on the request method (GET/POST). Then a cache lookup * is performed. If a value is obtained, the value is written to the * response otherwise, the actual target (in this case, Spring's Dispatcher * Servlet) is called by calling doFilter on the filteChain. The dispatcher * servlet calls the controller to produce the desire response which is * intercepted when the doFilter method returns. The Response is added to * the cache if the reponse code was 200(OK). * * @param request * @param response * @param filterChain * @throws IOException * @throws ServletException */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { try { if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { // Wrapping the response in HTTPServletResponseWrapper MemcacheResponseWrapper responseWrap = new MemcacheResponseWrapper((HttpServletResponse) response); // Wrapping the request in HTTPServletResponseWrapper MemcacheRequestWrapper requestWrap = new MemcacheRequestWrapper((HttpServletRequest) request); // Get Memcached Client Instance MemcachedClient client = cacheConfig.getMemcachedClient(); Key keyGenerator = getKeyGenerator(requestWrap); if (keyGenerator != null) { String key = keyGenerator.getKey(requestWrap, cacheConfig); String value = (String) client.get(key); if (value == null) { // cache miss logger.info("Cache miss for key " + key); // call next filter/actual target for value filterChain.doFilter(requestWrap, responseWrap); if (responseWrap.getStatus() == HttpServletResponse.SC_OK) { // obtaining response content from // HttpServletResponseWrapper value = responseWrap.getOutputStream().toString(); // adding response to cache client.add(key, 0, value); logger.info("Adding response to cache: "+ (value.length() > 50 ? value.substring(0,50) + "..." : value)); } else { logger.warn("Did not add content to cache as response status is not 200"); } } else { // This case is a cache hit logger.info("Cache hit for key " + key); response.getWriter().println(value); } } else { logger.warn("Request skipped because no key generator could be found for the request's method"); // attempting call to actual target filterChain.doFilter(request, response); } } } catch (Exception ex) { logger.info("Cache functionality skipped due to exception", ex); // attempting call to actual target filterChain.doFilter(request, response); } } /** * Factory method that returns KeyGenerator based on the request method. * * @param httpRequest * @return */ private Key getKeyGenerator(HttpServletRequest httpRequest) { Key keyGenerator = null; if (httpRequest.getMethod().equalsIgnoreCase("GET")) { keyGenerator = new GetRequestKey(); } else if (httpRequest.getMethod().equalsIgnoreCase("POST")) { keyGenerator = new PostRequestKey(); } return keyGenerator; } public void init(FilterConfig arg0) throws ServletException { logger.debug("init"); } public CacheConfig getCacheConfig() { return cacheConfig; } public void setCacheConfig(CacheConfig cacheConfig) { this.cacheConfig = cacheConfig; } public void destroy() { logger.debug("destroy"); } } 1. I first wrap my request and response objects in the following statements. I have had to create the wrappers as well. Will get to those later. // Wrapping the response in HTTPServletResponseWrapper MemcacheResponseWrapper responseWrap = new MemcacheResponseWrapper((HttpServletResponse) response); // Wrapping the request in HTTPServletResponseWrapper MemcacheRequestWrapper requestWrap = new MemcacheRequestWrapper((HttpServletRequest) request); 2. Next, I have one of my injected classes, CacheConfig, provide me with a memcache client which I will use later to look up the cache. // Get Memcached Client Instance MemcachedClient client = cacheConfig.getMemcachedClient(); 3. I make a call to a function that tells me which key generator I should use, a GET one or a POST one depending on the request method. Key keyGenerator = getKeyGenerator(requestWrap); /** * Factory method that returns KeyGenerator based on the request method. * * @param httpRequest * @return */ private Key getKeyGenerator(HttpServletRequest httpRequest) { Key keyGenerator = null; if (httpRequest.getMethod().equalsIgnoreCase("GET")) { keyGenerator = new GetRequestKey(); } else if (httpRequest.getMethod().equalsIgnoreCase("POST")) { keyGenerator = new PostRequestKey(); } return keyGenerator; } 4. Check for a cache hit using the Key returned by the Key Generator. If its a miss, call next filter or target to compute actual value, get value from the response wrapper, and add it to the cache. if (keyGenerator != null) { String key = keyGenerator.getKey(requestWrap, cacheConfig); String value = (String) client.get(key); if (value == null) { // cache miss logger.info("Cache miss for key " + key); // call next filter/actual target for value filterChain.doFilter(requestWrap, responseWrap); if (responseWrap.getStatus() == HttpServletResponse.SC_OK) { // obtaining response content from // HttpServletResponseWrapper value = responseWrap.getOutputStream().toString(); // adding response to cache client.add(key, 0, value); logger.info("Adding response to cache: "+ (value.length() > 50 ? value.substring(0,50) + "..." : value)); } 5. If its a cache hit, just get return cached value else { // This case is a cache hit logger.info("Cache hit for key " + key); response.getWriter().println(value); } Lets take a look at each of the Wrappers. I am not going into a a lot of detail into how each of these work. Request Wrapper Class On the way in, the original POST content is extracted from the request and put in a String Buffer. To the filter, this content is returned via the toString() method of the WrappedInputStream class whereas the subsequently called controller calls the read method. public class MemcacheRequestWrapper extends HttpServletRequestWrapper { protected ServletInputStream stream; protected HttpServletRequest origRequest = null; protected BufferedReader reader = null; public MemcacheRequestWrapper(HttpServletRequest request) throws IOException { super(request); origRequest = request; } public ServletInputStream createInputStream() throws IOException { return (new WrappedInputStream(origRequest)); } @Override public ServletInputStream getInputStream() throws IOException { if (reader != null) { throw new IllegalStateException("getReader() has already been called for this request"); } if (stream == null) { stream = createInputStream(); } return stream; } @Override public BufferedReader getReader() throws IOException { if (reader != null) { return reader; } if (stream != null) { throw new IllegalStateException("getReader() has already been called for this request"); } stream = createInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); return reader; } private class WrappedInputStream extends ServletInputStream { private StringBuffer originalInput = new StringBuffer(); private HttpServletRequest originalRequest; private ByteArrayInputStream byteArrayInputStream; public WrappedInputStream(HttpServletRequest request) throws IOException { this.originalRequest = request; BufferedReader bufferedReader = null; try { InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { originalInput.append(charBuffer, 0, bytesRead); } } byteArrayInputStream = new ByteArrayInputStream(originalInput.toString().getBytes()); } catch (IOException ex) { throw ex; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { throw ex; } } } } @Override public String toString() { return this.originalInput.toString(); } @Override public int read() throws IOException { return byteArrayInputStream.read(); } } } Response Wrapper Class The response wrapper is similar to the request wrapper. Instead of the read method, there is a write method, called by the controller when its writing JSON content. This is stored in the wrapper and called in the filter. public class MemcacheResponseWrapper extends HttpServletResponseWrapper { protected ServletOutputStream stream; protected PrintWriter writer = null; protected HttpServletResponse origResponse = null; private int httpStatus = 200; public MemcacheResponseWrapper(HttpServletResponse response) { super(response); response.setContentType("application/json"); origResponse = response; } public ServletOutputStream createOutputStream() throws IOException { return (new WrappedOutputStream(origResponse)); } public ServletOutputStream getOutputStream() throws IOException { if (writer != null) { throw new IllegalStateException("getWriter() has already been called for this response"); } if (stream == null) { stream = createOutputStream(); } return stream; } public PrintWriter getWriter() throws IOException { if (writer != null) { return writer; } if (stream != null) { throw new IllegalStateException("getOutputStream() has already been called for this response"); } stream = createOutputStream(); writer = new PrintWriter(stream); return writer; } @Override public void sendError(int sc) throws IOException { httpStatus = sc; super.sendError(sc); } @Override public void sendError(int sc, String msg) throws IOException { httpStatus = sc; super.sendError(sc, msg); } @Override public void setStatus(int sc) { httpStatus = sc; super.setStatus(sc); } public int getStatus() { return httpStatus; } private class WrappedOutputStream extends ServletOutputStream { private StringBuffer originalOutput = new StringBuffer(); private HttpServletResponse originalResponse; public WrappedOutputStream(HttpServletResponse response) { this.originalResponse = response; } @Override public String toString() { return this.originalOutput.toString(); } @Override public void write(int arg0) throws IOException { originalOutput.append((char) arg0); originalResponse.getOutputStream().write(arg0); } } }
June 25, 2013
by Faheem Sohail
· 22,571 Views · 1 Like
article thumbnail
Resolving SOAPFaultException caused by com.ctc.wstx.exc. WstxUnexpectedCharException
If you’re using any of these tools for Web Services – Axis2, CXF etc. – that internally make use of Woodstox XML processor (wstx), and you're getting an exception like this during webservice calls, javax.xml.ws.soap.SOAPFaultException: Error reading XMLStreamReader. at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:...) ... Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character ... at com.ctc.wstx.sr.StreamScanner.throwUnexpectedChar(StreamScanner.java:...) at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:...) at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:...) at com.ctc.wstx.sr.BasicStreamReader.nextTag(BasicStreamReader.java:...) the problem is that the wstx tokenizer/parser encountered unexpected (but not necessarily invalid per se) character; character that is not legal in current context. Could happen, for example, if white space was missing between attribute value and name of next attribute, according to API docs (http://woodstox.codehaus.org/3.2.9/javadoc/com/ctc/wstx/exc/WstxUnexpectedCharException.html). This simply means that you’re receiving an ill-formed SOAP XML as response. You need to check the SOAP response construction logic/code at the other end you’re communicating to.
June 24, 2013
by Singaram Subramanian
· 21,029 Views
article thumbnail
Automatically Detect Browser Language With PHP
When you are working on a multinational website you may need the functionality to translate your website into different languages. There are many ways you can translate a website, in this article I will not go through the different ways you can translate a website. But one thing is that you will always need is to know what language you want display when a user hits your page. There are different options you can do with this, either have a default language and allow the user to switch to the language they want to use, or detect the language set in the browser and switch the language automatically. You can detect the language the browser is set to by looking at the server variable HTTP_ACCEPT_LANGUAGE. // Detect browser language $_SERVER['HTTP_ACCEPT_LANGUAGE']; This variable will display all the languages that you can set in your browser en-GB,en,en-US. But because you can select multiple languages for your browser they are returned as a comma separated string. From these languages you can explode the string and now you have a list of all languages that the user can read, looping through this list you can find supported languages and display these to the user. $supportedLangs = array('en-GB', 'fr', 'de'); $languages = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']); foreach($languages as $lang) { if(in_array($lang, $supportedLangs)) { // Set the page locale to the first supported language found $page->setLocale($lang); break; } }
June 22, 2013
by Paul Underwood
· 27,758 Views
article thumbnail
Mixins With Pure Java
implementation of mixins using aop (aspectj) or source-code modification (jamopp) in object-oriented programming languages, a mixin refers to a defined amount of functionality which can be added to a class. an important aspect of this is that it makes it possible to concentrate more on the properties of a particular behaviour than on the inheritance structures during development. in scala for example, a variant of mixins can be found under the name of “traits”. although java does not provide direct support for mixins, these can easily be added on with a few annotations, interfaces and some tool support. occasionally you read in a few online articles that mixins are incorporated into java version 8. unfortunately, this is not the case. a feature of the lambda project ( jsr-335 ) are the so-called “virtual extension methods” (vem). whilst these are similar to mixins, they do have a different background and are significantly more limited in functionality. the motivation for the introduction of vems is the problem of backward compatibility in the introduction of new methods in interfaces . as “real” mixins are not expected in the java language in the near future, this article intends to demonstrate how it is already possible to create mixin support in java projects now, using simple methods. to do this, we will discuss two approaches: using aop with aspectj and using source-code modification with jamopp . why not just inheritance? when asked at an event “ what would you change about java if you could reinvent it? ” james gosling , the inventor of java is said to have answered “ i would get rid of the classes “. after the laughter had died down, he explained what he meant by that: inheritance in java, which is expressed with the “extends” relationship, should – wherever possible – be replaced by interfaces [ why extends is evil ]. any experienced developer knows what he meant here: inheritance should be used sparingly. it is very easy to misuse it as a technical construct to reuse code, and not to model a technically motivated parent-child relationship with it. but even if one considers such a technically motivated code reuse as legitimate, one quickly reaches its limits, as java does not allow multiple inheritance. mixins are always useful if several classes have similar properties or define a similar behaviour, but these cannot be reasonably modelled simply via slim relationship hierarchies. in english, terms which end in “able” (e.g. “sortable”, “comparable” or “commentable”) are often an indicator for applications of mixins. also, when starting to write “utility” methods in order to avoid a code duplication in the implementation of interfaces, this can be an indication of a meaningful case of application. mixins with aop so-called inter-type declarations are an extremely simple possibility for implementing mixins, offered by the aspectj eclipse project. with these, it is possible – among other things – to add new instance variables and methods to any target class. this will be shown in the following, based on a small example in listing 1. for this, we will use the following terms: basis-interface describes the desired behaviour. classes which the mixin should not use can use this interface. mixin-interface intermediate interface used in the aspect and implemented by classes which the mixin is to use. mixin-provider aspect which provides the implementation for the mixin. mixin-user class which uses (implements) one or more mixin interfaces. // === listing 1 === /** base-interface */ public interface named { public string getname(); } /** mixin-interface */ public interface namedmixin extends named { } /** mixin-provider */ public aspect namedaspect { private string namedmixin.name; public final void namedmixin.setname(string name) { this.name = name; } public final string namedmixin.getname() { return name; } } /** mixin-user */ public class myclass implements namedmixin { // could have more methods or use different mixins } listing 1 shows a complete aop-based mixin example. if aspectj is set up correctly, the following source text should compile and run without errors: myclass myobj = new myclass(); myobj.setname("abc"); system.out.println(myobj.getname()); it is possible to work quite comfortably with aop variants, but there are also a few disadvantages which will be explored here. first of all, inter-type declarations cannot deal with generic types in the target class. this is not absolutely necessary in many cases, but can be very practical. for example, it is possible to define the “named” interface just as well with a generic type instead of “string”. it would then define the behaviour for any name types. the class used could then determine how the type of name should look. a further disadvantage is that the methods generated by aspectj follow their own naming conventions. this makes it difficult to search the classes using reflection, as you would have to reckon with method names such as “ajc$intermethoddispatch …” last but not least, without the support of the development environment, you cannot see the source code in the target class and are dependent on the interface declaration alone. this could, however, be seen as an advantage, since the using classes contain less code. appearance: java model parser and printer (jamopp) an alternative to the implementation of mixins with aspektj is offered by java model parser and printer (jamopp). simply put, jamopp can read java source code, present it as an object graph in the memory and transform (i.e. write) it back into text. with jamopp, it is therefore possible to programmatically process java code and thus automate refactoring or implement your own code analyses, for example. technologically, jamopp is based on the eclipse modeling framework (emf) and emftext . jamopp is jointly developed by the technical university of dresden and devboost gmbh and is freely available on github as an open-source project. mixins with jamopp in the following, we would like to take up the example from the aop mixins and expand this slightly. for this, we will first define a few annotations: @mixinintf indicates a mixin interface. @mixinprovider indicates a class which provides the implementation for a mixin. the implemented mixin interface is specified as the only parameter. @mixingenerated marks methods and instance variables which have been generated by the mixin. the only parameter is the class of the mixin provider. in the following, we will also be expanding the interfaces and classes from listing 1 with a generic type for the name. only the class using the mixin defines which concrete type the name should actually have. // === listing 2 === /** base-interface (extended with generic parameter) */ public interface named { public t getname(); } /** mixin-interface */ @mixinintf public interface namedmixin extends named { } /** mixin-provider */ @mixinprovider(namedmixin.class) public final class namedmixinprovider implements named { @mixingenerated(namedmixinprovider.class) private t name; @mixingenerated(namedmixinprovider.class) public void setname(t name) { this.name = name; } @override @mixingenerated(namedmixinprovider.class) public t getname() { return name; } } /** special name type (alternative to string) */ public final class myname { private final string name; public myname(string name) { super(); if (name == null) { throw new illegalargumentexception("name == null"); } if (name.trim().length() == 0) { throw new illegalargumentexception("name is empty"); } this.name = name; } @override public string tostring() { return name; } } in the class which the mixin is to use, the mixin interface is now implemented again as shown in listing 3. in order to “blend” the fields and methods defined by the mixin provider into the myclass class, a code generator is used. with the help of jamopp, this modifies the myclass class and adds the instance variables and methods provided by the mixin provider. // === listing 3 === /** mixin-user */ public class myclass implements namedmixin { // could have more methods or use different mixins } in doing this, the code generator does the following. it reads the source code of every class, similarly to the normal java compiler, and, in doing so, examines the amount of implemented interfaces. if a mixin interface is present, i.e. an interface with the annotation @mixinintf, the corresponding provider is found and the instance variables and methods are copied into the class which is implementing the mixin. in order to initiate the generation of mixin codes, there are currently two options: using an eclipse plug-in directly when saving or as a maven plug-in as part of the build. installation instructions and the source code of both plug-ins can be found on github in the small srcmixins4j project. there is also an on-screen video available there, which demonstrates the use of the eclipse plug-in. listing 4 shows the how the modified target class then looks. // === listing 4 === /** mixin-user */ public class myclass implements namedmixin { @mixingenerated(namedmixinprovider.class) private myname name; @mixingenerated(namedmixinprovider.class) public void setname(myname name) { this.name = name; } @override @mixingenerated(namedmixinprovider.class) public myname getname() { return name; } } if the mixin interface is removed from the “implements” section, all of the provider’s fields and methods annotated with “@mixingenerated” will be deleted automatically. generated code can be overridden at any time by removing the “@mixingenerated” annotation. click on the following image to open a flash video that demonstrates the eclipse plugin: conclusion as native support of mixins in the java language standard is not expected in the foreseeable future, it is currently possible to make do with just some aop or source-code generation. which of the two options you choose depends essentially on whether you prefer to keep the mixin code separate from your own application code or whether you want them directly in the respective classes. in any case, the speed of development is significantly increased and you will concentrate less on inheritance hierarchies and more on the definition of functional behaviour. neither approach is perfect. in particular, conflicts are not automatically resolved. methods with the same signature from different interfaces which are provided by different mixin providers will, for example, lead to an error in a class which uses both mixins. those seeking anything more would have to transfer to another language with native mixin support, such as scala. about these ads
June 20, 2013
by Michael Schnell
· 26,757 Views · 1 Like
article thumbnail
Getting Started with RabbitMQ in Java
RabbitMQ is a popular message broker typically used for building integration between applications or different components of the same application using messages. This post is a very basic introduction on how to get started using RabbitMQ and assumes you already have setup the rabbitmq server. RabbitMQ is written in Erlang and has drivers/clients available for most major languages. We are using Java for this post therefore we will first get hold of the java client. The maven dependency for the java client is given below. com.rabbitmq amqp-client 3.0.4 While message brokers such as RabbitMQ can be used to model a variety of schemes such as one to one message delivery or publisher/subscriber, our application will be simple enough and have two basic components, a single producer, that will produce a message and a single consumer that will consume that message. In our example, the producer will produce a large number of messages, each message carrying a sequence number while the consumer will consume the messages in a separate thread. The EndPoint Abstract class: Let’s first write a class that generalizes both producers and consumers as ‘endpoints’ of a queue. Whether you are a producer or a consumer, the code to connect to a queue remains the same therefore we can generalize it in this class. package co.syntx.examples.rabbitmq; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; /** * Represents a connection with a queue * @author syntx * */ public abstract class EndPoint{ protected Channel channel; protected Connection connection; protected String endPointName; public EndPoint(String endpointName) throws IOException{ this.endPointName = endpointName; //Create a connection factory ConnectionFactory factory = new ConnectionFactory(); //hostname of your rabbitmq server factory.setHost("localhost"); //getting a connection connection = factory.newConnection(); //creating a channel channel = connection.createChannel(); //declaring a queue for this channel. If queue does not exist, //it will be created on the server. channel.queueDeclare(endpointName, false, false, false, null); } /** * Close channel and connection. Not necessary as it happens implicitly any way. * @throws IOException */ public void close() throws IOException{ this.channel.close(); this.connection.close(); } } The Producer: The producer class is what is responsible for writing a message onto a queue. We are using Apache Commons Lang to convert a Serializable java object to a byte array. The maven dependency for commons lang is commons-lang commons-lang 2.6 package co.syntx.examples.rabbitmq; import java.io.IOException; import java.io.Serializable; import org.apache.commons.lang.SerializationUtils; /** * The producer endpoint that writes to the queue. * @author syntx * */ public class Producer extends EndPoint{ public Producer(String endPointName) throws IOException{ super(endPointName); } public void sendMessage(Serializable object) throws IOException { channel.basicPublish("",endPointName, null, SerializationUtils.serialize(object)); } } The Consumer: The consumer, which can be run as a thread, has callback functions for various events, most important of which is the availability of a new message. package co.syntx.examples.rabbitmq; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.SerializationUtils; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.ShutdownSignalException; /** * The endpoint that consumes messages off of the queue. Happens to be runnable. * @author syntx * */ public class QueueConsumer extends EndPoint implements Runnable, Consumer{ public QueueConsumer(String endPointName) throws IOException{ super(endPointName); } public void run() { try { //start consuming messages. Auto acknowledge messages. channel.basicConsume(endPointName, true,this); } catch (IOException e) { e.printStackTrace(); } } /** * Called when consumer is registered. */ public void handleConsumeOk(String consumerTag) { System.out.println("Consumer "+consumerTag +" registered"); } /** * Called when new message is available. */ public void handleDelivery(String consumerTag, Envelope env, BasicProperties props, byte[] body) throws IOException { Map map = (HashMap)SerializationUtils.deserialize(body); System.out.println("Message Number "+ map.get("message number") + " received."); } public void handleCancel(String consumerTag) {} public void handleCancelOk(String consumerTag) {} public void handleRecoverOk(String consumerTag) {} public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {} } Putting it together: In our driver class, we start a consumer thread and then proceed to generate a large number of messages that will be consumed by the consumer. package co.syntx.examples.rabbitmq; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; public class Main { public Main() throws Exception{ QueueConsumer consumer = new QueueConsumer("queue"); Thread consumerThread = new Thread(consumer); consumerThread.start(); Producer producer = new Producer("queue"); for (int i = 0; i < 100000; i++) { HashMap message = new HashMap(); message.put("message number", i); producer.sendMessage(message); System.out.println("Message Number "+ i +" sent."); } } /** * @param args * @throws SQLException * @throws IOException */ public static void main(String[] args) throws Exception{ new Main(); } }
June 20, 2013
by Faheem Sohail
· 93,974 Views · 2 Likes
article thumbnail
MOXy's @XmlVariableNode - Using a Map's Key as the Node Name
People often ask me how they can map a java.util.Map such that the keys become the node names. In this post I will demonstrate how this can be done using the new Variable Node mapping that we have added in EclipseLink MOXy. You can try this out today using a nightly build of EclipseLink 2.6.0: http://www.eclipse.org/eclipselink/downloads/nightly.php Input/Output Below are the XML and JSON representations we will use in this example. Each has node names that correspond to keys and contents that correspond to values of a Map. XML (input.xml) 1 2 JSON (Output) { "A" : 1, "B" : 2 } Java Model (Root) We want a non-default XML (and JSON) representation for Map so we will use an XmlAdapter (see: JAXB and java.util.Map). MOXy's @XmlPath extension will be used to prevent the contents of the adapted Map from being wrapped in a parent element (see: XPath Based Mapping). package blog.variablenode.map; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.eclipse.persistence.oxm.annotations.XmlPath; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Root { @XmlPath(".") @XmlJavaTypeAdapter(MapAdapter.class) private Map map = new HashMap(); } XmlAdapter (MapAdapter) An XmlAdapter is used to convert an object for the purposes of marshalling/unmarshalling (see: XmlAdapter - JAXB's Secret Weapon). In this example we convert the Map to an AdaptedMap that has a List of AdaptedEntry values. These AdaptedEntry values have a field (key) to represent the key. It is this field that we will use with @XmlVariableNode (line 13). We will mark the key field with @XmlTransient to prevent if from being marshalled/unmarshalled (line 20). package blog.variablenode.map; import java.util.*; import java.util.Map.Entry; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.eclipse.persistence.oxm.annotations.XmlVariableNode; public class MapAdapter extends XmlAdapter> { public static class AdaptedMap { @XmlVariableNode("key") List entries = new ArrayList(); } public static class AdaptedEntry { @XmlTransient public String key; @XmlValue public Integer value; } @Override public AdaptedMap marshal(Map map) throws Exception { AdaptedMap adaptedMap = new AdaptedMap(); for(Entry entry : map.entrySet()) { AdaptedEntry adaptedEntry = new AdaptedEntry(); adaptedEntry.key = entry.getKey(); adaptedEntry.value = entry.getValue(); adaptedMap.entries.add(adaptedEntry); } return adaptedMap; } @Override public Map unmarshal(AdaptedMap adaptedMap) throws Exception { List adaptedEntries = adaptedMap.entries; Map map = new HashMap(adaptedEntries.size()); for(AdaptedEntry adaptedEntry : adaptedEntries) { map.put(adaptedEntry.key, adaptedEntry.value); } return map; } } Demo Below is some demo code that can be run to prove that everything works. The Root object will be instantiated from XML input and marshalled to create the JSON output. package blog.variablenode.map; import java.io.File; import javax.xml.bind.*; import org.eclipse.persistence.jaxb.MarshallerProperties; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/blog/variablenode/map/input.xml"); Root root = (Root) unmarshaller.unmarshal(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json"); marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false); marshaller.marshal(root, System.out); } } Further Reading If you enjoyed this post then you may also be interested in: MOXy's @XmlVariableNode - JSON Schema Example Specifying EclipseLink MOXy as your JAXB Provider JAXB and java.util.Map JSON Binding with EclipseLink MOXy - Twitter Example
June 20, 2013
by Blaise Doughan
· 13,067 Views
article thumbnail
Why does my Java process consume more memory than Xmx?
This post comes from Vladimir Šor at the Plumbr blog. Some of you have been there. You have added -Xmx option to your startup scripts and sat back relaxed knowing that there is no way your Java process is going to eat up more memory than your fine-tuned option had permitted. And then you were up for a nasty surprise. Either by yourself by checking a process table in your development / test box or if things got really bad then by operations who calls you in the middle of the night telling that the 4G memory you had asked for the production is exhausted. And that the application just died. So what the heck is happening under the hood? Why is the process consuming more memory than you allocated? Is it a bug or something completely normal? Bear with me and I will guide you through what is happening. First of all, part of it can definitely be a malicious native code leaking memory. But on 99% of the cases it is completely normal behaviour of the JVM. What you have specified via the -Xmx switches is limiting the memory consumed by your application heap. Besides heap there are other regions in memory which your application is using under the hood – namely permgen and stack sizes. So in order to limit those you should also specify the -XX:MaxPermSize and -Xss options respectively. In a short, you can predict your application memory usage with the following formula Max memory = [-Xmx] + [-XX:MaxPermSize] + number_of_threads * [-Xss] But besides the memory consumed by your application, the JVM itself also needs some elbow room. The need for it derives from several different reasons: Garbage collection. As you might recall, Java is a garbage collected language. In order for the garbage collector to know which objects are eligible for collection, it needs to keep track of the object graphs. So this is one part of the memory lost for this internal bookkeeping. Especially G1 is known for its excessive appetite for additional memory, so be aware of this. JIT optimization. Java Virtual Machine optimizes the code during the runtime. Again, to know which parts to optimize it needs to keep track of the execution of certain code parts. So again, you are going to lose memory. Off-heap allocations. If you happen to use off-heap memory, for example while using direct or mapped ByteBuffers yourself or via some clever 3rd party API then voila – you are extending your heap to something you actually cannot control via JVM configuration. JNI code. When you are using native code for example in the format of Type 2 database drivers then again, you are loading code in the native memory. Metaspace. If you are an early adopter of Java 8, you are using metaspace instead of the good old permgen to store class declarations. This is unlimited and in a native part of the JVM. You can end up using memory for other reasons than listed above as well, but I hope I managed to convince you that there is a significant amount of memory eaten up by the JVM internals. But is there a way to predict how much memory is actually going to be needed? Or at least understand where it disappears in order to optimize? As we have found out via painful experience – it is not possible to predict it with a reasonable precision. The JVM overhead can range from anything between just a few percentages to several hundred %. Your best friend is again the good old trial and error. So you need to run your application with loads similar to production environment and measure. Measuring the additional overhead is trivial – just monitor the process with the OS built-in tools (top on Linux, Activity Monitor on OS X, Task Manager on Windows) to find out the real memory consumption. Subtract the heap and permgen sizes from the real consumption and you see the overhead posed. Now if you need to reduce to overhead you would like to understand where it actually disappears. We have found vmmap on Mac OS X and pmap on Linux to be a truly helpful tools in this case. We have not used the vmmap port to Windows by ourselves, but it seems there is a tool for Windows fanboys as well. The following example illustrates this situation. I have launched my Jetty with the following startup parameters: -Xmx168m -Xms168m -XX:PermSize=32m -XX:MaxPermSize=32m -Xss1m Knowing that I have 30 threads launched in my application I might expect that my memory usage does not exceed 230M no matter what. But now when I look at the Activity Monitor on my Mac OS X, I see something different The real memory usage has exceeded 320M. Now digging under the hood how the process with the help of the vmmap output we start to understand where the memory is disappearing. Lets go through some samples: The following says we have lost close to 2MB is lost to memory mapped rt.jar library. mapped file 00000001178b9000-0000000117a88000 [ 1852K] r--/r-x SM=ALI /Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home/jre/lib/rt.jar - Next section explains that we are using ~6MB for a particular Dynamic Library loaded __TEXT 0000000104573000-0000000104c00000 [ 6708K] r-x/rwx SM=COW /Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home/jre/lib/server/libjvm.dylib - See more at: http://plumbr.eu/blog/why-does-my-java-process-consume-more-memory-than-xmx?utm_source=rss&utm_medium=rss&utm_campaign=rss20130618#sthash.G8fx60eX.dpuf And here we have threads no 25-30 each allocating 1MB for their stacks and stack guards Stack 000000011a5f1000-000000011a6f0000 [ 1020K] rw-/rwx SM=ZER thread 25 Stack 000000011aa8c000-000000011ab8b000 [ 1020K] rw-/rwx SM=ZER thread 27 Stack 000000011ab8f000-000000011ac8e000 [ 1020K] rw-/rwx SM=ZER thread 28 Stack 000000011ac92000-000000011ad91000 [ 1020K] rw-/rwx SM=ZER thread 29 Stack 000000011af0f000-000000011b00e000 [ 1020K] rw-/rwx SM=ZER thread 30 - See more at: http://plumbr.eu/blog/why-does-my-java-process-consume-more-memory-than-xmx?utm_source=rss&utm_medium=rss&utm_campaign=rss20130618#sthash.G8fx60eX.dpuf STACK GUARD 000000011a5ed000-000000011a5ee000 [ 4K] ---/rwx SM=NUL stack guard for thread 25 STACK GUARD 000000011aa88000-000000011aa89000 [ 4K] ---/rwx SM=NUL stack guard for thread 27 STACK GUARD 000000011ab8b000-000000011ab8c000 [ 4K] ---/rwx SM=NUL stack guard for thread 28 STACK GUARD 000000011ac8e000-000000011ac8f000 [ 4K] ---/rwx SM=NUL stack guard for thread 29 STACK GUARD 000000011af0b000-000000011af0c000 [ 4K] ---/rwx SM=NUL stack guard for thread 30 - See more at: http://plumbr.eu/blog/why-does-my-java-process-consume-more-memory-than-xmx?utm_source=rss&utm_medium=rss&utm_campaign=rss20130618#sthash.G8fx60eX.dpuf I hope I managed to shed some light upon the tricky task of predicting and measuring the actual memory consumption. If you enjoyed the content – subscribe to our RSS feed or start following us in Twitter to be notified on future interesting posts.
June 19, 2013
by Nikita Salnikov-Tarnovski
· 21,573 Views
article thumbnail
How to Optimize MySQL UNION for High Speed
There are two ways to speedup UNIONs in a MySQL database. First use UNION ALL if at all possible, and second try to push down your conditions. 1. UNION ALL is much faster than UNION How does a UNION work? Imagine you have two tables for shirts. The short_sleeve table looks like this: blue green gray black And long_sleeve another that looks like this: red green yellow blue Related: Why Generalists are Better at Scaling the Web If you UNION those two tables, first MySQL will sort the combined set into a temp table like this: black blue blue gray green green red yellow Once it’s done this sort, it can easily remove the duplicate blue & duplicate green for this resulting set: black blue gray green red yellow See also: Mythical MySQL DBA – the talent drought. Why does it do this? UNION is defined that way in SQL. Duplicates must be removed and this is an efficient way for the MySQL engine to remove them. Combine results, sort, remove duplicates and return the set. Queries with UNION can be accelerated in two ways. Switch to UNION ALL or try to push ORDER BY, LIMIT and WHERE conditions inside each subquery. You’ll be glad you did! What if we did UNION ALL? The result would look like this: blue green gray black red green yellow blue Read this: MySQL DBA Interview & Hiring Guide. It doesn’t have to sort, and doesn’t have to remove duplicates. If you imagine combining two 10 million row tables, and don’t have to sort, this speedup can be HUGE. 2. Use Push-down Conditions to speedup UNION in MySQL Imagine with our example above the shirts have a design date, the year they were released. Yes we’re keeping this example very simple to illustrate the concept. Here is the short_sleeve table: blue 2013 green 2013 green 2012 gray 2011 black 2009 black 2011 And long_sleeve table looks like this: red 2012 red 2013 green 2011 yellow 2010 blue 2011 For 2013 designs could combine them like this: (SELECT type, release FROM short_sleeve) UNION (SELECT type, release FROM long_sleeve); WHERE release >=2013; See also: 5 More Things Deadly to Scalability and the original 5 Things Toxic to Scalability.. Here the WHERE clause works on this 11 record temp table: black 2009 black 2011 blue 2011 blue 2013 gray 2011 green 2013 green 2012 green 2011 red 2012 red 2013 yellow 2010 But it would be much faster to move the WHERE inside each subquery like this: (SELECT type, release FROM short_sleeve WHERE release >=2013) UNION (SELECT type, release FROM long_sleeve WHERE release >=2013); That would be operating on a combined 3 record table. Faster to sort & remove duplicates. Smaller result sets cache better too, providing a pay forward dividend. That’s what performance optimization is all about! Read this: RDS or MySQL – 10 Use Cases. Remember multi-million row sets in each part of this query will quickly illustrate the optimization. We’re using very small results to make visualizing easier. You can also use this optimization for ORDER BY and for LIMIT conditions. By reducing the number of records returned by EACH PART of the UNION, you reduce the work that happens at the stage where they are all combined. If you’re seeing some UNION queries in your slow query log, I suggest you try this optimization out and see if you can tweak it.
June 17, 2013
by Sean Hull
· 24,078 Views
article thumbnail
OCAJP 7 Object Lifecycle in Java
What is an Object? An object is a collection of data and actions. An object is an instance of a class. Objects have states and behaviors. In the real-world, we can find so many objects around us, for example Cars, Birds, Humans etc. All these objects have a state and behavior. If we consider a Car then it have some data speed, lights on, direction, etc. and have some actions turn right, accelerate, turn lights on, etc. If you compare the java object with a real world object, both of them have similar characteristics. Java objects also have a state and behavior. A Java object's state is stored in fields and behavior is shown via methods. Technically speaking Car, Bird and Human are considered as Class in Java. Brian Christopher is an object of human and Vehicle XKMV-669 is the object of car. Creating Object Using new keyword is the most common way to create an object in java. Syntax:- ClassName Obj.Name = new ClassName(); // Human brianChristopher= new Human(); // Car vehicleXKMV_669 = new Car(); The first statement creates a new Human object and second statement creates Car object. This single statement performs three actions, Declaration, Instantiation, and Initialization. Here, Human brianChristopher is a variable declaration which simply declares to the compiler that the name brianChristopher will be used to refer to an object whose type is Human, the new operator instantiates the Human class (thereby creating a new Human object), and Human initializes the object. Object Lifecycle In Java, it has seven states in Object lifecycle. They are, Created In use Invisible Unreachable Collected Finalized De-allocated Created The following are the some actions performed when an object is created,New memory is allocated for an object. Once the object has been created, assuming that it is assigned to some variable and then it directly moves to the In Use state. In use Objects that are held by at least one strong reference are considered to be “In Use”. Invisible An object is in the “Invisible” state when there are no longer any strong references that are accessible to the program, even though there might still be references. Unreachable An object enters an “unreachable” state when no more strong references to it exist. When an object is unreachable then it is a state for collection. It is important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. Garbage collection roots are a special class of variable that includes,Temporary variables on the stack Collected An object is in the “collected” state when the garbage collector has recognized an object as unreachable and readies it for final processing as a precursor to de-allocation. If the object has a finalize method, then it is marked for finalization. Finalized An object is in the “finalized” state if it is still unreachable after it’s finalize method, if any, has been run. A finalized object is awaiting de-allocation. If you are considering using a finalizer to ensure that important resources are freed in a timely manner, you might want to reconsider. To lengthening object lifetimes, finalize methods can increase object size. De-allocated The de-allocated state is the final step in garbage collection. If an object is still unreachable after all the above work has done, then this is the state for de-allocation. For more detailed discussion about Object Lifecycle with real-world examples download OCAJP 7 Training Lab from EPractize Labs.
June 16, 2013
by Anand Epl
· 25,191 Views · 3 Likes
article thumbnail
Mockito - Extra Interfaces with Annotations and Static Methods
In the code I have quite recently came across a really bad piece of code that based on class casting in terms of performing some actions on objects. Of course the code needed to be refactored but sometimes you can't do it / or don't want to do it (and it should be understandable) if first you don't have unit tests of that functionality. In the following post I will show how to test such code, how to refactor it and in fact what I think about such code ;) Let's take a look at the project structure: As presented in the post regarding Mocktio RETURNS_DEEP_STUBS Answer for JAXB yet again we have the JAXB generated classes by the JAXB compiler in thecom.blogspot.toomuchcoding.model package. Let's ommit the discussion over the pom.xml file since it's exactly the same as in the previous post. In the com.blogspot.toomuchcoding.adapter package we have adapters over the JAXB PlayerDetails class that provides access to the Player interface. There is the CommonPlayerAdapter.java package com.blogspot.toomuchcoding.adapter; import com.blogspot.toomuchcoding.model.Player; import com.blogspot.toomuchcoding.model.PlayerDetails; /** * User: mgrzejszczak * Date: 09.06.13 * Time: 15:42 */ public class CommonPlayerAdapter implements Player { private final PlayerDetails playerDetails; public CommonPlayerAdapter(PlayerDetails playerDetails){ this.playerDetails = playerDetails; } @Override public void run() { System.out.printf("Run %s. Run!%n", playerDetails.getName()); } public PlayerDetails getPlayerDetails() { return playerDetails; } } DefencePlayerAdapter.java package com.blogspot.toomuchcoding.adapter; import com.blogspot.toomuchcoding.model.DJ; import com.blogspot.toomuchcoding.model.DefensivePlayer; import com.blogspot.toomuchcoding.model.JavaDeveloper; import com.blogspot.toomuchcoding.model.PlayerDetails; /** * User: mgrzejszczak * Date: 09.06.13 * Time: 15:42 */ public class DefencePlayerAdapter extends CommonPlayerAdapter implements DefensivePlayer, DJ, JavaDeveloper { public DefencePlayerAdapter(PlayerDetails playerDetails){ super(playerDetails); } @Override public void defend(){ System.out.printf("Defence! %s. Defence!%n", getPlayerDetails().getName()); } @Override public void playSomeMusic() { System.out.println("Oops I did it again...!"); } @Override public void doSomeSeriousCoding() { System.out.println("System.out.println(\"Hello world\");"); } } OffensivePlayerAdapter.java package com.blogspot.toomuchcoding.adapter; import com.blogspot.toomuchcoding.model.OffensivePlayer; import com.blogspot.toomuchcoding.model.PlayerDetails; /** * User: mgrzejszczak * Date: 09.06.13 * Time: 15:42 */ public class OffensivePlayerAdapter extends CommonPlayerAdapter implements OffensivePlayer { public OffensivePlayerAdapter(PlayerDetails playerDetails){ super(playerDetails); } @Override public void shoot(){ System.out.printf("%s Shooooot!.%n", getPlayerDetails().getName()); } } Ok, now let's go to the more interesting part. Let us assume that we have a very simple factory of players: PlayerFactoryImpl.java package com.blogspot.toomuchcoding.factory; import com.blogspot.toomuchcoding.adapter.CommonPlayerAdapter; import com.blogspot.toomuchcoding.adapter.DefencePlayerAdapter; import com.blogspot.toomuchcoding.adapter.OffensivePlayerAdapter; import com.blogspot.toomuchcoding.model.Player; import com.blogspot.toomuchcoding.model.PlayerDetails; import com.blogspot.toomuchcoding.model.PositionType; /** * User: mgrzejszczak * Date: 09.06.13 * Time: 15:53 */ public class PlayerFactoryImpl implements PlayerFactory { @Override public Player createPlayer(PositionType positionType) { PlayerDetails player = createCommonPlayer(positionType); switch (positionType){ case ATT: return new OffensivePlayerAdapter(player); case MID: return new OffensivePlayerAdapter(player); case DEF: return new DefencePlayerAdapter(player); case GK: return new DefencePlayerAdapter(player); default: return new CommonPlayerAdapter(player); } } private PlayerDetails createCommonPlayer(PositionType positionType){ PlayerDetails playerDetails = new PlayerDetails(); playerDetails.setPosition(positionType); return playerDetails; } } Ok so we have the factory that builds Players. Let's take a look at the Service that uses the factory: PlayerServiceImpl.java package com.blogspot.toomuchcoding.service; import com.blogspot.toomuchcoding.factory.PlayerFactory; import com.blogspot.toomuchcoding.model.*; /** * User: mgrzejszczak * Date: 08.06.13 * Time: 19:02 */ public class PlayerServiceImpl implements PlayerService { private PlayerFactory playerFactory; @Override public Player playAGameWithAPlayerOfPosition(PositionType positionType) { Player player = playerFactory.createPlayer(positionType); player.run(); performAdditionalActions(player); return player; } private void performAdditionalActions(Player player) { if(player instanceof OffensivePlayer){ OffensivePlayer offensivePlayer = (OffensivePlayer) player; performAdditionalActionsForTheOffensivePlayer(offensivePlayer); }else if(player instanceof DefensivePlayer){ DefensivePlayer defensivePlayer = (DefensivePlayer) player; performAdditionalActionsForTheDefensivePlayer(defensivePlayer); } } private void performAdditionalActionsForTheOffensivePlayer(OffensivePlayer offensivePlayer){ offensivePlayer.shoot(); } private void performAdditionalActionsForTheDefensivePlayer(DefensivePlayer defensivePlayer){ defensivePlayer.defend(); try{ DJ dj = (DJ)defensivePlayer; dj.playSomeMusic(); JavaDeveloper javaDeveloper = (JavaDeveloper)defensivePlayer; javaDeveloper.doSomeSeriousCoding(); }catch(ClassCastException exception){ System.err.println("Sorry, I can't do more than just play football..."); } } public PlayerFactory getPlayerFactory() { return playerFactory; } public void setPlayerFactory(PlayerFactory playerFactory) { this.playerFactory = playerFactory; } } Let's admit it... this code is bad. Internally when you look at it (regardless of the fact whether it used instance of operator or not) you feel that it is evil :) As you can see in the code we have some class casts going on... How on earth can we test it? In the majority of testing frameworks you can't do such class casts on mocks since they are built with the CGLIB library and there can be some ClassCastExceptions thrown. You could still not return mocks and real implementations (assuming that those will not perform any ugly stuff in the construction process) and it could actually work but still - this is bad code :P Mockito comes to the rescue (although you shouldn't overuse this feature - in fact if you need to use it please consider refactoring it) with its extraInterfaces feature: extraInterfaces MockSettings extraInterfaces(java.lang.Class... interfaces) Specifies extra interfaces the mock should implement. Might be useful for legacy code or some corner cases. For background, see issue 51 hereThis mysterious feature should be used very occasionally. The object under test should know exactly its collaborators & dependencies. If you happen to use it often than please make sure you are really producing simple, clean & readable code. Examples: Foo foo = mock(Foo.class, withSettings().extraInterfaces(Bar.class, Baz.class)); //now, the mock implements extra interfaces, so following casting is possible: Bar bar = (Bar) foo; Baz baz = (Baz) foo; Parameters:interfaces - extra interfaces the should implement. Returns:settings instance so that you can fluently specify other settings Now let's take a look at the test: PlayerServiceImplTest.java package com.blogspot.toomuchcoding.service; import com.blogspot.toomuchcoding.factory.PlayerFactory; import com.blogspot.toomuchcoding.model.*; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.*; /** * User: mgrzejszczak * Date: 08.06.13 * Time: 19:26 */ @RunWith(MockitoJUnitRunner.class) public class PlayerServiceImplTest { @Mock PlayerFactory playerFactory; @InjectMocks PlayerServiceImpl objectUnderTest; @Mock(extraInterfaces = {DJ.class, JavaDeveloper.class}) DefensivePlayer defensivePlayerWithDjAndJavaDevSkills; @Mock DefensivePlayer defensivePlayer; @Mock OffensivePlayer offensivePlayer; @Mock Player commonPlayer; @Test public void shouldReturnOffensivePlayerThatRan() throws Exception { //given given(playerFactory.createPlayer(PositionType.ATT)).willReturn(offensivePlayer); //when Player createdPlayer = objectUnderTest.playAGameWithAPlayerOfPosition(PositionType.ATT); //then assertThat(createdPlayer == offensivePlayer, is(true)); verify(offensivePlayer).run(); } @Test public void shouldReturnDefensivePlayerButHeWontBeADjNorAJavaDev() throws Exception { //given given(playerFactory.createPlayer(PositionType.GK)).willReturn(defensivePlayer); //when Player createdPlayer = objectUnderTest.playAGameWithAPlayerOfPosition(PositionType.GK); //then assertThat(createdPlayer == defensivePlayer, is(true)); verify(defensivePlayer).run(); verify(defensivePlayer).defend(); verifyNoMoreInteractions(defensivePlayer); } @Test public void shouldReturnDefensivePlayerBeingADjAndAJavaDev() throws Exception { //given given(playerFactory.createPlayer(PositionType.GK)).willReturn(defensivePlayerWithDjAndJavaDevSkills); doAnswer(new Answer
June 12, 2013
by Marcin Grzejszczak
· 21,778 Views · 2 Likes
article thumbnail
NetBeans IDE 7.3.1 Now Available with Java EE 7 Support
NetBeans IDE 7.3.1 is an update to NetBeans IDE 7.3 and includes the following highlights: Support for Java EE 7 development Deployment to GlassFish 4 Support for major Java EE 7 specifications: JSF 2.2, JPA 2.1, JAX-RS 2.0, WebSocket 1.0 and more Support for WebLogic 12.1.2 and JBoss 7.x Integration of recent patches There are two ways to get the recent changes: To use the new Java EE 7 support, it is recommended to download and install NetBeans IDE 7.3.1. To get only the integration of recent patches: Launch your current installation of NetBeans IDE 7.3. An update notification will appear in the IDE. Click the notification box to install the updates. OR to perform the update manually, in the IDE select Help-->Check for Updates. NetBeans IDE 7.3.1 is available in English, Brazilian Portuguese, Japanese, Russian, and Simplified Chinese.
June 12, 2013
by Tinu Awopetu
· 9,420 Views
  • Previous
  • ...
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×