Featured FREE Whitepapers

What's New Here?

jcg-logo

Best Of The Week – 2011 – W30

Hello guys, Time for the “Best Of The Week” links for the week that just passed. Here are some links that drew JavaCodeGeeks attention: * Test-Driven Development Is Not Slower: An article praising the advantages of Test Driven Development (TDD) in terms of development speed, dispersing the myth that developers do not have enough time for unit testing. * SQL vs NoSQL in the Cloud: Which Database Should You Choose?: A nice, short article describing the differences of SQL and NoSQL solutions and discussing the advantages of each approach. In the end, a hybrid solution is examined (SQL database implementation that uses NoSQL infrastructure). * Visual Studio v. Eclipse: a Comparison of Automation Tooling: An introduction of the methodology for creating Eclipse and Visual Studio-based toolkits, and introduce Visual Studio Pattern Automation Toolkit, a toolkit for toolkit developers. . * Reverse Engineering Applications: A presentation explaining why someone would use reverse engineering, outlining some of the tools for managed .NET and Java code, along with demoing techniques. * OutOfMemoryError warning system with Spring: This article examines the common OutOfMemoryError JVM error and provides a Spring based application that triggers it. JMX is used in order to monitor the application and create metrics. * Performance-driven SQL databases and virtualization: A short article on SQL deployment on virtualized and non-virtualized environments. Performance versus expenses are examined in each case. * EJB 3.1 Cookbook by Richard Reese review: A review on the new book “EJB 3.1 Cookbook” written by our JCG partner Tomek Nurkiewicz. * Hidden Java 7 Features – System and Process CPU Load Monitoring: This article discusses a new MBean in Java 7 that allows Java developers to access overall System and current process CPU load monitoring. Also, check out “Java 7: try-with-resources explained” and “A glimpse at Java 7 MethodHandle and its usage”. That’s all for this week. Stay tuned for more, here at JavaCodeGeeks. Related Articles:Best Of The Week – 2011 – W29 Best Of The Week – 2011 – W28 Best Of The Week – 2011 – W27 Best Of The Week – 2011 – W26 Best Of The Week – 2011 – W25 Best Of The Week – 2011 – W23 Best Of The Week – 2011 – W22 Best Of The Week – 2011 – W21 Best Of The Week – 2011 – W20 Best Of The Week – 2011 – W19...
java-logo

Java and Memory Leaks

Overview The term “memory leak” is used in Java in a manner which is different to how it is used in other languages. What does a “memory leak” mean in general terminology and how is it used in Java? Wikipedia definition A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system. The JVM reserves the heap as virtual memory on startup and doesn’t gives that memory back until it exits. This virtual memory turns into main memory as it is used. This is why the virtual size and the resident size for a JVM can be very different and the resident memory can grow without the virtual memory changing. In object-oriented programming, a memory leak happens when an object is stored in memory but cannot be accessed by the running code. The GC can always find every object on the heap, even those which are not reachable to the application. As such there is no object which is not reachable to running code. however, many people refer to any unwanted increase in memory usage as a memory leak, though this is not strictly accurate from a technical perspective. In Java, the amount of memory required cannot be determined without a full GC. It is normal to see the “used” memory of a Java application sawtooth. Returning to the same amount of memory used after each GC indicates the memory required has not increased. A memory leak can diminish the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down unacceptably due to thrashing. This is how the term is used in Java. There is a reduction in available memory, conclusion: it is a memory leak. But is it really a memory leak? Examples of “memory leaks” in Java Recently, two questions were asked on StackOverflow which illustrate a variety of views over what a “memory leak” means in Java. Is Go subject to the same subtle memory-leaks that Java is? Creating a memory leak in Java In the first article there was a view expressed that a “memory leak” is when an application holds references to objects which are no longer needed. Another view was that the JVM itself doesn’t have memory leaks. In the second article there were many examples of how the JVM could be used to hide away memory usage or operations which would consume memory. Examples included File.deleteOnExit(), creating large static fields, discarded sockets, file handles, threads, JDBC connection which you don’t need. The File.deleteOnExit on exit must use some memory to be able to perform its task. This is not a leak in my option as it is not retaining memory which is not needed. Having static fields and threads which you don’t need will waste memory and this is bug which the JVM cannot correct for. However, creating sockets, file handles, and JDBC connections the JVM does handle. When the finalize() method is called, these resources are cleaned up. Conclusion In Java it is meaningful to refer to objects which are retained and are not longer needed as a “memory leak”. There is nothing in the Java language which is prone to this problem and the JRE libraries do protect themselves from bugs in application code. Your application can still have a memory leak, and you need to make sensible choices about when you still need a resource, in particular a thread and if you hold onto it too long it can mean you have a “memory leak”. Reference: Java and Memory Leaks from our JCG partner Peter Lawrey at the Vanilla Java blog. Related Articles :Low GC in Java: Use primitives instead of wrappers Erlang vs Java memory architecture How does JVM handle locks JVM options: -client vs -server...
android-logo

Android Game Development – Sprite Animation

If you followed the series so far we are pretty knowledgable in handling touches, displaying images and moving them around. But a moving image it’s a pretty dull sight as it looks really fake and amateurish. To give the characters some life we will need to do more than that. That is what animation is all about. A rock is an inanimate object and even if it is thrown, it doesn’t change its shape. A human on the other hand, is very animated. Try throwing one and you’ll see twitching limbs and even screams in the air. Let’s just resort to examining walking which is pretty complex in its own. Imagine a human crossing your way (just in 2D). You’ll notice different displays of the body. Left foot in front, right hand in front while the oposite limbs are behind. This slowly changes so the left foot remains behind while the right progresses along with the body. But at one point the cycle repeats. If you don’t close your eyes you see the person progressing smoothly. If you close your eyes and keep them closed for a bit and open them again the person already went on and is in a different position. Try blinking quite rapidly and you will see something like the old black and white comedies. That is low frame rate. More on FPS here. Actually we do want a low frame rate walking for this tutorial, just like this.The walking presented above is a bit dodgy but it’s a ripped off version of the sprites from Monkey Island. She’s Elaine Marley. This is called a Sprite. It is a simple 2 dimensional image or animation. To be able to re-create the above animation, we need every frame from the walking cycle.It is a 150 pixels wide image and each frame is 30 pixels wide. To illustrate it better check the following image.To get the above animation in android (or iPhone or in any other program for that matter), we need to load up each frame as a separate image and display them at regular intervals one after each other. OR we can load up the big image containing all the frames and use the methods provided by android do slice and dice them on the fly and to display only the relevant frame. To do that is trivial. We know that we have 5 frames and each frame is 30 pixels wide. We define a rectangle (that will be our selection) which has the width of one frame and the height of the image. The following image shows how I cut out the first two frames. The rest you should fill in.Knowing all this let’s go create the project. We will use the knowledge from some previous chapters, most notably about the game loop and the one about the image display (here we set up the thread that triggers the drawing of the graphics item every frame). We will need an object to animate. We use Elaine from Monkey Island so I will the class ElaineAnimated.java. public class ElaineAnimated {private static final String TAG = ElaineAnimated.class.getSimpleName();private Bitmap bitmap; // the animation sequence private Rect sourceRect; // the rectangle to be drawn from the animation bitmap private int frameNr; // number of frames in animation private int currentFrame; // the current frame private long frameTicker; // the time of the last frame update private int framePeriod; // milliseconds between each frame (1000/fps)private int spriteWidth; // the width of the sprite to calculate the cut out rectangle private int spriteHeight; // the height of the spriteprivate int x; // the X coordinate of the object (top left of the image) private int y; // the Y coordinate of the object (top left of the image)}The private attributes are commented but worth mentioning a few.bitmap is the png file containing all the frames. The second image in this article. sourceRect is the selection rectangle. It is the blue window in the image above. The rectangle moves every frame onto the next. frameTicker this is the java timestamp of the last frame change in the walking sequence. Note that this is not the game FPS but the walking FPS. If we want Elaine to perform a complete walk cycle in a second we set the frame rate for walking to 5 because we have 5 frames. To get a really smooth animation we need 30 frames but it’s not the point now. framePeriod is time in milliseconds that represents the period of time a frame is being displayed. If the cycle completes in 1 second that means for 5 frames the period will be 0.2 seconds. That is, each frame will be displayed for 0.2 seconds.The constructor is as follows: public ElaineAnimated(Bitmap bitmap, int x, int y, int width, int height, int fps, int frameCount) { this.bitmap = bitmap; this.x = x; this.y = y; currentFrame = 0; frameNr = frameCount; spriteWidth = bitmap.getWidth() / frameCount; spriteHeight = bitmap.getHeight(); sourceRect = new Rect(0, 0, spriteWidth, spriteHeight); framePeriod = 1000 / fps; frameTicker = 0l; }I’m assuming that the frames are the same width so I calculate the width of the rectangle by dividing the width of the image with the number of frames. I also pass in the fps which is again, the frames per second of the walk cycle not the game FPS. Elaine will have an update method of her own as she is an animated object and she needs to look good and she is in charge of dragging her feet. Because the period of the game update cycle and Elaine’s one might be (in this case is) different we pass the actual game time as a variable so we know when we need to display the next frame. For example the game runs very fast and the update is called every 20 milliseconds and we need to update the frame every 200ms, then the progression of the frame will happen at every 10th game update. Here’s the code: public void update(long gameTime) { if (gameTime > frameTicker + framePeriod) { frameTicker = gameTime; // increment the frame currentFrame++; if (currentFrame >= frameNr) { currentFrame = 0; } } // define the rectangle to cut out sprite this.sourceRect.left = currentFrame * spriteWidth; this.sourceRect.right = this.sourceRect.left + spriteWidth; }The update is called from the main game panel (check previous entries how that works). This is the update method of the MainGamePanel class. public void update() { elaine.update(System.currentTimeMillis()); }The update method is simple (Elaine’s). It increments the frame if the passed in time (which is the system time when the update method was called) is greater than the last time (frameTicker) the frame was updated plus the period of the next update. If the next frame is beyond the last, we reset the cycle. After all that area from which the image will be cut out is defined as the sourceRect. That’s it. Now let’s go on to display it. public void draw(Canvas canvas) { // where to draw the sprite Rect destRect = new Rect(getX(), getY(), getX() + spriteWidth, getY() + spriteHeight); canvas.drawBitmap(bitmap, sourceRect, destRect, null); }That is all. We set the destination rectangle as to where to draw the cut out image. It is at Elaine’s position (X and Y set in the constructor). canvas.drawBitmap(bitmap, sourceRect, destRect, null);tells android to cut out the image defined by sourceRect from the image contained in bitmap and draw it into the rectangle on the canvas defined by destRect. The draw is called from the game panel’s render method triggered by the game loop (check previous entries). The MainGamePanel.java differs slightly from the one from previous chapters. I got rid of all the droidz and added just Elaine. private ElaineAnimated elaine;public MainGamePanel(Context context) { //* ... removed ... */// create Elaine and load bitmap elaine = new ElaineAnimated( BitmapFactory.decodeResource(getResources(), R.drawable.walk_elaine) , 10, 50 // initial position , 30, 47 // width and height of sprite , 5, 5); // FPS and number of frames in the animation// create the game loop thread thread = new MainThread(getHolder(), this);//* ... removed ... */ }Elaine is instantiated in the panel’s constructor and is given an initial positon of (X=10, Y=50). I pass in the width and the height of the sprite too but that is ignored anyway, but you can modify the code. The FPS is very important and the number of frames too. FPS says how many frames are to be shown in one second. The last parameter is the number of frames in the cycle. The thread and activity classes haven’t changed at all. You can find them in the download as they are quite long to be pasted. The image is named walk_elaine.png and it was copied to /res/drawable-mdpi/ so android can pick it up automatically. If you run the application you should be seeing Elaine performing walking cycles in one place. We should have used jumping as that can be performed in one place but you get the idea.Elaine WalkingEnhancement To make some neat additions modify Elaine’s draw method so it displays the original image containing the sprites from which the frames are extracted. public void draw(Canvas canvas) { // where to draw the sprite Rect destRect = new Rect(getX(), getY(), getX() + spriteWidth, getY() + spriteHeight); canvas.drawBitmap(bitmap, sourceRect, destRect, null); canvas.drawBitmap(bitmap, 20, 150, null); Paint paint = new Paint(); paint.setARGB(50, 0, 255, 0); canvas.drawRect(20 + (currentFrame * destRect.width()), 150, 20 + (currentFrame * destRect.width()) + destRect.width(), 150 + destRect.height(), paint); }This just displays the image at (20, 150) and creates a new paint object so we can paint over the current frame on the original image. The method setARGB creates a semi-transparent green paint. The first value is 50 which means it’s 75% transparent. 0 is completely transparent while 255 is fully opaque. After everything was drawn we paint a rectangle of the size of a frame onto the original image so you see which frame is being displayed in the motion.Walking with Current Frame PaintedThat’s it. Run it and you have your first sprite animation. Download the source code here (animation_walk.tar.gz) Reference: Sprite Animation with Android from our JCG partner Tamas Jano from “Against The Grain” blog. Do not forget to check out our new Android Game ArkDroid (screenshots below). You feedback will be more than helpful!Related Articles:Android Game Development Tutorials Introduction Android Game Development – The Game Idea Android Game Development – Create The Project Android Game Development – A Basic Game Architecture Android Game Development – A Basic Game Loop Android Game Development – Displaying Images with Android Android Game Development – Moving Images on Screen Android Game Development – The Game Loop Android Game Development – Measuring FPS Android Game Development – Particle Explosion Android Game Development – Design In-game Entities – The Strategy Pattern Android Game Development – Using Bitmap Fonts Android Game Development – Switching from Canvas to OpenGL ES Android Game Development – Displaying Graphical Elements (Primitives) with OpenGL ES Android Game Development – OpenGL Texture Mapping Android Game Development – Design In-game Entities – The State Pattern Android Games Article Series...
software-development-2-logo

Roles in the IT World

The following comic is a matrix, each entry is how one kind of employee views another.Description :Product managers view themselves as orchestra conductors. Site reliability Engineers view the product managers as a person asking for a space shuttle launch. Software engineers view the product manager as a person sitting in front of a computer, checking and responding to email. Managers view the product manager as a person giving a presentation with lots of graphs. User interface designers view the product manager as a person with a net, chasing bugs.Product managers view the site reliability engineer as a person in the road holding a stop sign. Behind him is the finish line, with ‘launch’ written across it. Site reliability engineers view themselves as the captain of a ship. Software engineers view the site reliability engineer as a person surrounded by empty beer bottles. Managers view the site reliability engineer as a person with a bucket, running under a pipe with multiple leaks, trying to catch all of the drops of water. User interface designers view the site reliability engineer as a person with a hammer and tool belt, walking between large racks of computers.Product managers view the software engineer as a wizard with a pointed cap and wand. Site reliability engineers view the software engineer as an infant in a diaper, smashing blocks with a hammer and making infantile noises. Software engineers view themselves as a rock star with a haircut from the 80s and a pink guitar. Managers view the software engineer as a battery. User interface designers view the software engineer as a person building a house, with a sign out front saying ‘The Saint Mock’ showing how the house should look like once built.Product managers view the manager as a person directing children in a line. The children have green hair and purple clothing, like Lemmings or Oompa Loopas from ‘Charlie and the chocolate factory’. Site reliability engineers view the manager as a clown in a checkered suit. Software engineers view the manager as a god with a floating hand coming from the sky, and emitting a godly light. Managers themselves as a rock stars, with a long white beard and white hair, standing on clouds. User interface designers view the manager as Darth Vader.Product managers view the user interface designer as a person standing still, as cobwebs collect on him. Site reliability engineers view the user interface designer as an infant, making hand prints on a canvas with finger paints. Software engineers view the user interface designer as a person with a moustache painting a scene, with melting clocks like Salvador Dali’s work. Managers view the user interface designer as a person describing a box labeled ‘product’, surrounded by floating colored flowers and with eyes trying to hypnotize you. User interface designers view themselves as a man with pointy hair and sunglasses in a red convertible car.Reference: Roles in the IT World from our JCG partner Spyros Doulgeridis at the Spyros’ Log. Comic source: Roles in the IT World Related Articles:Funny Source Code Comments Things Every Programmer Should Know 10 Tips for Proper Application Logging Laws of Software Design Java Best Practices Series 9 Tips on Surviving the Wild West Development Process...
java-logo

How to get C like performance in Java

Overview Java has many areas which can be slow. However for every problem there is a solution. Many solutions/hacks require working around Java’s protections but if you need low level performance it is still possible. Java makes high level programming simpler and easier at the cost of making low level programming much harder. Fortunately most applications follow the rule of thumb that you spend 90% of your time in 10% of the code. This implies you are better off 90% of the time, worse off 10% of the time. ;) It makes me wonder why you would write more than 10% of your code in C/C++ for most projects. There will be some projects where C/C++ is the only sensible solution, but I suspect most C/C++ projects would more productive with the use of higher level languages like Java. One way to get C-like performance is to use C via JNI for key sections of code. If you want to avoid using C or JNI there are still ways you can get the performance you want. Note: Most of these suggestions only work for standalone applications rather than applets. Note 2: Use at your own risk. You are likely to need to test edge cases which you wouldn’t normally need to worry about when using low level Java. Fast array access One area Java can be slower is array access. This is because it implicitly does bounds checking. The JVM is smart enough to optimise checks for loops by checking the first and last element, however this doesn’t always apply. One work around is to use the Unsafe class (which is only available on some JVMs, OpenJDK JVMs do) This class has getXxxx() and setXxxx() for each primitive type and gives you direct access to an object, array or direct memory where you have to do the bounds checking. In native code, these are compiled to single machine code instruction. There is also a getObject(), setObject() methods however I suspect that they don’t provide as much of a performance improvement (by the time you access the Object as well) You can check the native code generated for a method by downloading the debug version of the OpenJDK and getting it to print the compiled native code. Arbitrary memory access You can use the Unsafe class again for arbitrary access, however a “friendlier” way is to use a DirectByteBuffer and change its address and limit as desired (via reflection or via JNI) This will give you a Buffer which points to a random area of memory such as device buffer. Using less memory This is not as much of an issue as it used to be. A 16 GB server costs $1000 and a 1 TB server costs about $70K. However, cache memory is still a premium and for some applications and its worth cutting memory consumption. A simple thing to do is to use Trove which support primitives in collections efficiently. If you have a large table of data, you can store data by column instead of by row (if you have lots of rows of data, and a few columns). This can improve caching behaviour if you are scanning data by field but don’t need all fields. You can also use Direct memory to store data how you wish. This is what the BigMemory library uses. Stream based IO is slow and NIO is a pain to use How can use you have the best of both worlds? Use blocking IO in NIO (which is the default for a Channel) Don’t use Selectors unless you need them. In many cases, they just add complexity. Most systems can handle 1K-10K threads efficiently. If you need more connections than that, buy another server, a cheap one cost about $500. Fast Efficient Strings Java 6 update 21 has an option -XX:+UseCompressedStrings which can use byte[] instead of char[] for the strings which don’t need 16-bit characters. For many applications this saves memory but is slower. (5%-10%) Instead you can use your own Text type which wraps a byte[], or get you text data from ByteBuffer, CharBuffer or use Unsafe. Faster Startup times Java tends to have slow startup times when you load in lots of bloated libraries. If this is really a problem for you load less libraries. Keeping them to a minimum is good practice anyway. Do this and your startup times will be a few seconds (not as fast as C, but likely to be fast enough) Less GC pauses Most Java libraries create objects freely and generally this is not a problem. However this doesn’t mean you can’t pre-allocate your objects, use Direct ByteBuffers and Object recycling techniques to minimise your object creation. By increasing the Eden size you can have an application which rarely GCs. You may even reduce it to one GC per day (say as a scheduled over night job) Reference: How to get C like performance in Java from our JCG partner Peter Lawrey at the Vanilla Java. Related Articles:Low GC in Java: Use primitives instead of wrappers Things Every Programmer Should Know 10 Tips for Proper Application Logging Laws of Software Design Java Best Practices Series 9 Tips on Surviving the Wild West Development Process...
software-development-2-logo

Funny Source Code Comments

I recently stumbled upon an awesome Stack Overflow thread, entitled “What is the best comment in source code you have ever encountered?”. As you might have guessed, it is a collection of funny source code comments, provided by developers all over the world. Take a look at it, it could definitely make your day. I am reposting here my personal favorites from that long long collection: // sometimes I believe compiler ignores all my comments Exception up = new Exception(“Something is really wrong.”); throw up; //ha ha //When I wrote this, only God and I understood what I was doing //Now, God only knows // I dedicate all this code, all my work, to my wife, Darlene, who will // have to support me and our three children and the dog once it gets // released into the public. // drunk, fix later // Magic. Do not touch. return 1; # returns 1 double penetration; // ouch /////////////////////////////////////// this is a well commented line // I am not sure if we need this, but too scared to delete. // I am not responsible of this code. // They made me write it, against my will. //Dear future me. Please forgive me. //I can’t even begin to express how sorry I am. options.BatchSize = 300; //Madness? THIS IS SPARTA! // I have to find a better job // hack for ie browser (assuming that ie is a browser) } catch (PartInitException pie) { // Mmm… pie } // John! If you’ll svn remove this once more, // I’ll shut you, for God’s sake! // That piece of code is not “something strange”! // That is THE AUTH VALIDATION. try { } catch (SQLException ex) { // Basically, without saying too much, you’re screwed. Royally and totally. } catch(Exception ex) { //If you thought you were screwed before, boy have I news for you!!! } // Catching exceptions is for communists // If you’re reading this, that means you have been put in charge of my previous project. // I am so, so sorry for you. God speed. // if i ever see this again i’m going to start bringing guns to work // The magnitude of this hack compares favorably with that of the national debt. //ALL YOUR BASE ARE BELONG TO US // If this code works, it was written by Paul. If not, I don’t know who wrote it //You are not expected to understand this /** * If you don’t understand this code, you should be flipping burgers instead. */ ‘NO COMMENT //Abandon all hope yea who enter beyond this point //Mr. Compiler, please do not read this. catch (Ex as Exception) { // oh crap, we should do something. } // TODO make this work // If you delete the credits, I will fucking kill you. // This is crap code but it’s 3 a.m. and I need to get this working. // For the sins I am about to commit, may James Gosling forgive me // Houston, we have a problem // If I from the future read this I’ll back in time and kill myself. Pure awesomeness… Don’t forget to share your own favorites in the comments! Related Articles :The top 9+7 things every programmer or architect should know Top 25 Most Dangerous Software Errors – 2011 Things Every Programmer Should Know Hate Java? You’re fighting the wrong battle. 10 Tips for Proper Application Logging...
android-logo

Android Game Development – Measuring FPS

In the previous entry we have created a game loop that runs at a constant speed and constant (more or less) FPS. How can we measure it? Check the new MainThread.java class.           package net.obviam.droidz;import java.text.DecimalFormat;import android.graphics.Canvas; import android.util.Log; import android.view.SurfaceHolder;/** * @author impaler * * The Main thread which contains the game loop. The thread must have access to * the surface view and holder to trigger events every game tick. */ public class MainThread extends Thread {private static final String TAG = MainThread.class.getSimpleName();// desired fps private final static int MAX_FPS = 50; // maximum number of frames to be skipped private final static int MAX_FRAME_SKIPS = 5; // the frame period private final static int FRAME_PERIOD = 1000 / MAX_FPS;// Stuff for stats */ private DecimalFormat df = new DecimalFormat("0.##"); // 2 dp // we'll be reading the stats every second private final static int STAT_INTERVAL = 1000; //ms // the average will be calculated by storing // the last n FPSs private final static int FPS_HISTORY_NR = 10; // last time the status was stored private long lastStatusStore = 0; // the status time counter private long statusIntervalTimer = 0l; // number of frames skipped since the game started private long totalFramesSkipped = 0l; // number of frames skipped in a store cycle (1 sec) private long framesSkippedPerStatCycle = 0l;// number of rendered frames in an interval private int frameCountPerStatCycle = 0; private long totalFrameCount = 0l; // the last FPS values private double fpsStore[]; // the number of times the stat has been read private long statsCount = 0; // the average FPS since the game started private double averageFps = 0.0;// Surface holder that can access the physical surface private SurfaceHolder surfaceHolder; // The actual view that handles inputs // and draws to the surface private MainGamePanel gamePanel;// flag to hold game state private boolean running; public void setRunning(boolean running) { this.running = running; }public MainThread(SurfaceHolder surfaceHolder, MainGamePanel gamePanel) { super(); this.surfaceHolder = surfaceHolder; this.gamePanel = gamePanel; }@Override public void run() { Canvas canvas; Log.d(TAG, "Starting game loop"); // initialise timing elements for stat gathering initTimingElements();long beginTime; // the time when the cycle begun long timeDiff; // the time it took for the cycle to execute int sleepTime; // ms to sleep (<0 if we're behind) int framesSkipped; // number of frames being skippedsleepTime = 0;while (running) { canvas = null; // try locking the canvas for exclusive pixel editing // in the surface try { canvas = this.surfaceHolder.lockCanvas(); synchronized (surfaceHolder) { beginTime = System.currentTimeMillis(); framesSkipped = 0; // resetting the frames skipped // update game state this.gamePanel.update(); // render state to the screen // draws the canvas on the panel this.gamePanel.render(canvas); // calculate how long did the cycle take timeDiff = System.currentTimeMillis() - beginTime; // calculate sleep time sleepTime = (int)(FRAME_PERIOD - timeDiff);if (sleepTime > 0) { // if sleepTime > 0 we're OK try { // send the thread to sleep for a short period // very useful for battery saving Thread.sleep(sleepTime); } catch (InterruptedException e) {} }while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) { // we need to catch up this.gamePanel.update(); // update without rendering sleepTime += FRAME_PERIOD; // add frame period to check if in next frame framesSkipped++; }if (framesSkipped > 0) { Log.d(TAG, "Skipped:" + framesSkipped); } // for statistics framesSkippedPerStatCycle += framesSkipped; // calling the routine to store the gathered statistics storeStats(); } } finally { // in case of an exception the surface is not left in // an inconsistent state if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas); } } // end finally } }/** * The statistics - it is called every cycle, it checks if time since last * store is greater than the statistics gathering period (1 sec) and if so * it calculates the FPS for the last period and stores it. * * It tracks the number of frames per period. The number of frames since * the start of the period are summed up and the calculation takes part * only if the next period and the frame count is reset to 0. */ private void storeStats() { frameCountPerStatCycle++; totalFrameCount++;// check the actual time statusIntervalTimer += (System.currentTimeMillis() - statusIntervalTimer);if (statusIntervalTimer >= lastStatusStore + STAT_INTERVAL) { // calculate the actual frames pers status check interval double actualFps = (double)(frameCountPerStatCycle / (STAT_INTERVAL / 1000));//stores the latest fps in the array fpsStore[(int) statsCount % FPS_HISTORY_NR] = actualFps;// increase the number of times statistics was calculated statsCount++;double totalFps = 0.0; // sum up the stored fps values for (int i = 0; i < FPS_HISTORY_NR; i++) { totalFps += fpsStore[i]; }// obtain the average if (statsCount < FPS_HISTORY_NR) { // in case of the first 10 triggers averageFps = totalFps / statsCount; } else { averageFps = totalFps / FPS_HISTORY_NR; } // saving the number of total frames skipped totalFramesSkipped += framesSkippedPerStatCycle; // resetting the counters after a status record (1 sec) framesSkippedPerStatCycle = 0; statusIntervalTimer = 0; frameCountPerStatCycle = 0;statusIntervalTimer = System.currentTimeMillis(); lastStatusStore = statusIntervalTimer; // Log.d(TAG, "Average FPS:" + df.format(averageFps)); gamePanel.setAvgFps("FPS: " + df.format(averageFps)); } }private void initTimingElements() { // initialise timing elements fpsStore = new double[FPS_HISTORY_NR]; for (int i = 0; i < FPS_HISTORY_NR; i++) { fpsStore[i] = 0.0; } Log.d(TAG + ".initTimingElements()", "Timing elements for stats initialised"); }} I introduced a simple measuring function. I count the number of frames every second and store them in the fpsStore[] array. The storeStats() is called every tick and if the 1 second interval (STAT_INTERVAL = 1000;) is not reached then it simply adds the number of frames to the existing count. If the one second is hit then it takes the number of rendered frames and adds them to the array of FPSs. After this I just reset the counters for the current statistics cycle and add the results to a global counter. The average is calculated on the values stored in the last 10 seconds. Line 171 logs the FPS every second while line 172 sets the avgFps value of the gamePanel instance to be displayed on the screen. The MainGamePanel.java class’s render method contains the the displayFps call which just draws the text onto the top right corner of the display every time the state is rendered. It also has a private member that is set from the thread. // the fps to be displayed private String avgFps; public void setAvgFps(String avgFps) { this.avgFps = avgFps; }public void render(Canvas canvas) { canvas.drawColor(Color.BLACK); droid.draw(canvas); // display fps displayFps(canvas, avgFps); }private void displayFps(Canvas canvas, String fps) { if (canvas != null && fps != null) { Paint paint = new Paint(); paint.setARGB(255, 255, 255, 255); canvas.drawText(fps, this.getWidth() - 50, 20, paint); } } Try running it. You should have the FPS displayed in the top right corner.FPS displayedReference: Measuring FPS from our JCG partner Tamas Jano from “Against The Grain” blog. Do not forget to check out our new Android Game ArkDroid (screenshots below). You feedback will be more than helpful!Related Articles:Android Game Development Tutorials Introduction Android Game Development – The Game Idea Android Game Development – Create The Project Android Game Development – A Basic Game Architecture Android Game Development – A Basic Game Loop Android Game Development – Displaying Images with Android Android Game Development – Moving Images on Screen Android Game Development – The Game Loop Android Game Development – Sprite Animation Android Game Development – Particle Explosion Android Game Development – Design In-game Entities – The Strategy Pattern Android Game Development – Using Bitmap Fonts Android Game Development – Switching from Canvas to OpenGL ES Android Game Development – Displaying Graphical Elements (Primitives) with OpenGL ES Android Game Development – OpenGL Texture Mapping Android Game Development – Design In-game Entities – The State Pattern Android Games Article Series...
java-logo

JVM options: -client vs -server

Have you ever wonder what is this -client or -server switch when you run your java app? e.g.: javaw.exe -client com.blogspot.sdoulger.LoopTestthat are also displayed in the Help of the java.exe e.g. where options include: -client to select the “client” VM -server to select the “server” VMWhat’s the difference between the -client and -server systems? These two systems are different binaries. They are essentially two different compilers (JITs) interfacing to the same runtime system. The client system is optimal for applications which need fast startup times or small footprints, the server system is optimal for applications where the overall performance is most important. In general the client system is better suited for interactive applications such as GUIs. Some of the other differences include the compilation policy,heap defaults, and inlining policy.According to “The Java HotSpot Performance Engine Architecture“: The JDK includes two flavors of the VM — a client-side offering, and a VM tuned for server applications. These two solutions share the Java HotSpot runtime environment code base, but use different compilers that are suited to the distinctly unique performance characteristics of clients and servers. These differences include the compilation inlining policy and heap defaults. The JDK contains both of the these systems in the distribution, so developers can choose which system they want by specifying -client or -server. Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. It is intended for executing long-running server applications, which need the fastest possible operating speed more than a fast start-up time or smaller runtime memory footprint. The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM offers improved run time performance for applications and applets. The Java HotSpot Client VM has been specially tuned to reduce application start-up time and memory footprint, making it particularly well suited for client environments. In general, the client system is better for GUIs. The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. This means the Client VM can start up faster and requires a smaller memory footprint. Note: It seems that the main cause of the difference in performance is the amount of optimizations. The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques. Both solutions deliver extremely reliable, secure, and maintainable environments to meet the demands of today’s enterprise customers. Default options:For Hotspot is client For JRockit is serverJRockit’s client and server VM options JRockit also has this two options with the default being server option (Hotspot is client). JRockit client option is -client and server is -jrockit. Hands-on example on the performance difference An example taken from Onkar Joshi’s blog that proves the performance difference. We run the following code with both switches: package com.blogspot.sdoulger;public class LoopTest { public LoopTest() { super(); }public static void main(String[] args) { long start = System.currentTimeMillis(); spendTime(); long end = System.currentTimeMillis(); System.out.println("Time spent: "+ (end-start)); LoopTest loopTest = new LoopTest(); }private static void spendTime() { for (int i =500000000;i>0;i--) { } } }Note: The code is been compiled only once! The classes are the same in both runs! With -client: java.exe -client -classpath C:\JDeveloper\mywork\Test_java_client-server_switches\Project1\classes com.blogspot.sdoulger.LoopTest Time spent: 766 With -server: java.exe -server -classpath C:\JDeveloper\mywork\Test_java_client-server_switches\Project1\classes com.blogspot.sdoulger.LoopTest Time spent: 0 It seems that the more aggressive optimazation of the server system, remove the loop as it understands that it does not perform any action! Dig more/sources:What’s the difference between the -client and -server systems? http://java.sun.com/products/hotspot/whitepaper.html#1 http://www.velocityreviews.com/forums/t130082-difference-between-client-server-classic-and-hotspot-jvms.html http://www.onkarjoshi.com/blog/174/hotspot-jvm-client-server-vm-optimization/ http://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-clientReference: Difference between -client and -server JVM command line options from our JCG partner Spyros Doulgeridis at the Spyro’s Log blog. Related Articles :Low GC in Java: Use primitives instead of wrappers Java Generics Quick Tutorial How does JVM handle locks How to Avoid ConcurrentModificationException when using an Iterator...
jcg-logo

Best Of The Week – 2011 – W29

Hello guys, Time for the “Best Of The Week” links for the week that just passed. Here are some links that drew JavaCodeGeeks attention: * Facebook trapped in MySQL ‘fate worse than death’: In this article the author argues that MySQL is posing a liability into Facebook’s growth and performance.This predicament is common among web startups that start small and grow to epic proportions. But NoSQL seems to also not be a viable solution. Enter NewSQL. * 7 new cool features in Java 7: This article describes some of the new cool features that are provided in the forthcoming Java 7 release. Among them, Strings in switch Statements, Type Inference for Generic Instance Creation, Multiple Exception Handling Syntax and try-with-resources Statement. * 101 Tips to MySQL Tuning and Optimization: For those of you working with MySQL, this is a good list of tips for tuning and optimizing your MySQL servers. The tips cover hardware and OS tuning, server configuration, schema optimization, queries optimization and backup procedure. * JBoss AS7 Released: In case you haven’t already heard, JBoss AS 7 was released the previous week, being both EE6 Web Profile certified and OSGi 4.2 compliant. The biggest change is that the AS 7 stack has been modularised for the release, which enables selective startup of modules; those that aren’t used are not loaded into the runtime, which allows it to be one of the fastest starting containers today. * Open source physics engines: This article introduces the use and basics of a physics engine, a simulator used to create a virtual environment that incorporates laws from the physical world. It also explores two options from the open source community, Box2D and Bullet. A good introduction for game programmers. Also check out our Android Game Development Tutorials. * VisualVM for Java Development: jVisualVM comes bundled with the JDK and provides a very efficient way of monitoring your Java applications. It allows you to view configuration information, dynamically monitor the application (GC activity, heap activity etc.), monitor CPU usage per thread, monitor memory usage, profile your application and analyze the output of a heap dump. What else can you ask? * How much should you pay developers?: Joel Spolsky has talked a lot in the past about hiring and compensating developers. In this post he describes the basic principles regarding developer compensation in the Stack Exchange team and provides a guide with the detailed process. * Hibernate Object Mapping for NoSQL Datastores: Hibernate recently introduced support for NoSQL databases via a new framework named OGM (Object Grid Mapping). They started with Infinispan (another JBoss product) but they plan on supporting a bunch of other NoSQL solutions. * Apache Thrift vs. Protocol Buffers: A comprehensive comparison between Apache’s Thrift and Google’s Protobuf for platform agnostic serialization. Features, performance, code quality, open-ness and documentation are all taken under account. Also check out our article Java Best Practices – High performance Serialization. * Google+ is Built Using Tools You Can Use Too: Closure, Java Servlets, JavaScript, BigTable, Colossus, Quick Turnaround: This article discusses the stack used for building Google+. It consists of Closure (a suite of JavaScript tools), plain old Java servlets, Google’s own BigTable and Colossus (Google’s next generation file system) among others. * Developing RESTful applications on JBoss AS 7: After getting introduced to JBoss AS 7, it is time to take it for a test drive. This is a straightforward guide on how to deploy REST applications on the brand new JBoss 7. First, the new JBoss modules approach is examined, then the Maven and Eclipse integration is explained and finally a sample RESTful web service is deployed on the server. * Google Code Gets Git: With Git getting a lot of traction during the past years, Google Code introduced support for Git repositories, along with the existing Subversion and Mercurial ones. It is also possible for existing projects to switch over to Git repositories. Cool! That’s all for this week. Stay tuned for more, here at JavaCodeGeeks. Related Articles:Best Of The Week – 2011 – W28 Best Of The Week – 2011 – W27 Best Of The Week – 2011 – W26 Best Of The Week – 2011 – W25 Best Of The Week – 2011 – W23 Best Of The Week – 2011 – W22 Best Of The Week – 2011 – W21 Best Of The Week – 2011 – W20 Best Of The Week – 2011 – W19 Best Of The Week – 2011 – W18...
spring-logo

jqGrid, REST, AJAX and Spring MVC Integration

More than two years back I wrote an article on how two implement elegant CRUD in Struts2. Actually I had to devote two articles on that subject because the topic was so broad. Today I have taken much more lightweight and modern approach with a set of popular and well established frameworks and libraries. Namely, we will use Spring MVC on the back-end to provide REST interface to our resources, fabulous jqGrid plugin for jQuery to render tabular grids (and much more!) and we will wire up everything with a pinch of JavaScript and AJAX. Back-end is actually the least interesting part of this showcase, it could have been implemented using any server-side technology capable of handling RESTful requests, probably JAX-RS should now be considered standard in this field. I have chosen Spring MVC without any good reason, but it’s also not a bad choice for this task. We will expose CRUD operations over REST interface; the list of best selling books in history will be our domain model (can you guess who is on the podium?) @Controller @RequestMapping(value = "/book") public class BookController {private final Map<Integer, Book> books = new ConcurrentSkipListMap<Integer, Book>();@RequestMapping(value = "/{id}", method = GET) public @ResponseBody Book read(@PathVariable("id") int id) { return books.get(id); }@RequestMapping(method = GET) public @ResponseBody Page<Book> listBooks( @RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "20") int max) { final ArrayList<Book> booksList = new ArrayList<Book>(books.values()); final int startIdx = (page - 1) * max; final int endIdx = Math.min(startIdx + max, books.size()); return new Page<Book>(booksList.subList(startIdx, endIdx), page, max, books.size()); }}Few things need explanation. First of all for the purposes of this simple showcase I haven’t used any database, all the books are stored in an in-memory map inside a controller. Forgive me. Second issue is more subtle. Since there seems to be no agreement on how to handle paging with RESTful web services, I used simple query parameters. You may find it ugly, but I find abusing Accept-Ranges and Range headers together with 206 HTTP response code even uglier. Last notable detail is the Page wrapper class: @XmlRootElement public class Page<T> {private List<T> rows;private int page; private int max; private int total;//...}I could have return raw list (or, more precisely, requested part of the list), but I also need a way to provide convenient metadata like total number of records to the view layer, not to mention some difficulties while marshalling/unmarshalling raw lists. We are now ready to start our application and do a little test drive with curl: <!-- $ curl -v "http://localhost:8080/books/rest/book?page=1&max=2" --><?xml version="1.0" encoding="UTF-8" standalone="yes"?> <page> <total>43</total> <page>1</page> <max>3</max> <rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book"> <author>Charles Dickens</author> <available>true</available> <cover>PAPERBACK</cover> <id>1</id> <publishedYear>1859</publishedYear> <title>A Tale of Two Cities</title> </rows> <rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book"> <author>J. R. R. Tolkien</author> <available>true</available> <cover>HARDCOVER</cover> <id>2</id> <publishedYear>1954</publishedYear> <title>The Lord of the Rings</title> </rows> <rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book"> <author>J. R. R. Tolkien</author> <available>true</available> <cover>PAPERBACK</cover> <id>3</id> <publishedYear>1937</publishedYear> <title>The Hobbit</title> </rows> </page>Response type defaults to XML if none is specified but if we add Jackson library to the CLASSPATH, Spring will pick it up and enable us to use JSON as well: // $ curl -v -H "Accept: application/json" "http://localhost:8080/books/rest/book?page=1&max=3"{ "total":43, "max":3, "page":1, "rows":[ { "id":1, "available":true, "author":"Charles Dickens", "title":"A Tale of Two Cities", "publishedYear":1859, "cover":"PAPERBACK", "comments":null }, { "id":2, "available":true, "author":"J. R. R. Tolkien", "title":"The Lord of the Rings", "publishedYear":1954, "cover":"HARDCOVER", "comments":null }, { "id":3, "available":true, "author":"J. R. R. Tolkien", "title":"The Hobbit", "publishedYear":1937, "cover":"PAPERBACK", "comments":null } ] }Nice, now we can work on the front-end, hopefully not making our hands too dirty. With regards to HTML markup, this is all we need, seriously: <table id="grid"></table> <div id="pager"></div>Keep in mind that we will implement all CRUD operations, but still, this is all we need. No more HTML. Rest of the magic happens thanks to marvellous jqGrid library. Here is a basic setup: $("#grid") .jqGrid({ url:'rest/book', colModel:[ {name:'id', label: 'ID', formatter:'integer', width: 40}, {name:'title', label: 'Title', width: 300}, {name:'author', label: 'Author', width: 200}, {name:'publishedYear', label: 'Published year', width: 80, align: 'center'}, {name:'available', label: 'Available', formatter: 'checkbox', width: 46, align: 'center'} ], caption: "Books", pager : '#pager', height: 'auto' }) .navGrid('#pager', {edit:false,add:false,del:false, search: false});Technically, this is all we need. URL to fetch the data, pointing to our controller (jqGrid will perform all the AJAX magic for us) and the data model (you may recognize book fields and their descriptions). However, since jqGrid is highly customizable, I applied few tweaks to make the grid look a bit better. Also I didn’t like suggested names of metadata, for instance total field returned from the server is suppose to be the total number of pages, not records – highly counter-intuitive. Here are my tweaked options: $.extend($.jgrid.defaults, { datatype: 'json', jsonReader : { repeatitems:false, total: function(result) { //Total number of pages return Math.ceil(result.total / result.max); }, records: function(result) { //Total number of records return result.total; } }, prmNames: {rows: 'max', search: null}, height: 'auto', viewrecords: true, rowList: [10, 20, 50, 100], altRows: true, loadError: function(xhr, status, error) { alert(error); } });Eager to see the results? Here is a browser screenshot:Good looking, with customizable paging, lightweight refreshing… And our hands are still relatively clean! But I promised CRUD… If you were careful, you have probably noticed few navGrid attributes, dying to be turned on: var URL = 'rest/book'; var options = { url: URL, editurl: URL, colModel:[ { name:'id', label: 'ID', formatter:'integer', width: 40, editable: true, editoptions: {disabled: true, size:5} }, { name:'title', label: 'Title', width: 300, editable: true, editrules: {required: true} }, { name:'author', label: 'Author', width: 200, editable: true, editrules: {required: true} }, { name:'cover', label: 'Cover', hidden: true, editable: true, edittype: 'select', editrules: {edithidden:true}, editoptions: { value: {'PAPERBACK': 'paperback', 'HARDCOVER': 'hardcover', 'DUST_JACKET': 'dust jacket'} } }, { name:'publishedYear', label: 'Published year', width: 80, align: 'center', editable: true, editrules: {required: true, integer: true}, editoptions: {size:5, maxlength: 4} }, { name:'available', label: 'Available', formatter: 'checkbox', width: 46, align: 'center', editable: true, edittype: 'checkbox', editoptions: {value:"true:false"} }, { name:'comments', label: 'Comments', hidden: true, editable: true, edittype: 'textarea', editrules: {edithidden:true} } ], caption: "Books", pager : '#pager', height: 'auto' }; $("#grid") .jqGrid(options) .navGrid('#pager', {edit:true,add:true,del:true, search: false});The configuration is getting dangerously verbose, but there’s nothing complicated out there – for each field we have added few additional attributes controlling how this field should be treated in edit mode. This includes what type of HTML input should represent it, validation rules, visibility, etc. But honestly, I believe it was worth it:This nicely looking edit window has been fully generated by jqGrid based on our edit options mentioned above, including validation logic. We can make some of the fields visible in the grid hidden/inactive in edit dialog (like id) and vice-versa (cover and comments are not present in the grid, however you can modify them). Also notice few new icons visible in bottom-left corner of the grid. Adding and deleting is possible as well – and we haven’t written a single line of HTML/JSP/JavaScript (excluding jqGrid configuration object).Of course we all know that The User Interface Is The Application, and our interface is pretty good, however sometimes we really want a beautiful and working application. And currently the latter requirement is our Achilles’ heel. Not because the back-end isn’t ready, this is rather trivial: @Controller @RequestMapping(value = "/book") public class BookController {private final Map<Integer, Book> books = new ConcurrentSkipListMap<Integer, Book>();@RequestMapping(value = "/{id}", method = GET) public @ResponseBody Book read(@PathVariable("id") int id) { //... }@RequestMapping(method = GET) public @ResponseBody Page<Book> listBooks( @RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "20") int max) { //... }@RequestMapping(value = "/{id}", method = PUT) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateBook(@PathVariable("id") int id, @RequestBody Book book) { //... }@RequestMapping(method = POST) public ResponseEntity<String> createBook(HttpServletRequest request, @RequestBody Book book) { //... }@RequestMapping(value = "/{id}", method = DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteBook(@PathVariable("id") int id) { //... }}Server-side is ready, but when it comes to data manipulation on the client-side, jqGrid reveals its dirty secret – all the traffic to the server is sent using POST like this: Content-Type: application/x-www-form-urlencoded in the following format: id=&title=And+Then+There+Were+None&author=Agatha+Christie&cover=PAPERBACK&publishedYear=1939&available=true&comments=&oper=addThe last attribute (oper=add) is crucial. Not really idiomatic REST, don’t you think? If we could only use POST/PUT/DELETE appropriately and serialize data using JSON or XML… Modifying my server so that it is compliant with some JavaScript library (no matter how cool it is), seems like a last resort. Thankfully, everything can be customized with a moderate amount of work. $.extend($.jgrid.edit, { ajaxEditOptions: { contentType: "application/json" }, mtype: 'PUT', serializeEditData: function(data) { delete data.oper; return JSON.stringify(data); } }); $.extend($.jgrid.del, { mtype: 'DELETE', serializeDelData: function() { return ""; } });var URL = 'rest/book'; var options = { url: URL, //... }var editOptions = { onclickSubmit: function(params, postdata) { params.url = URL + '/' + postdata.id; } }; var addOptions = {mtype: "POST"}; var delOptions = { onclickSubmit: function(params, postdata) { params.url = URL + '/' + postdata; } };$("#grid") .jqGrid(options) .navGrid('#pager', {}, //options editOptions, addOptions, delOptions, {} // search options );We have customized HTTP method per operation, serialization is handled using JSON and finally URLs for edit and delete operations are now suffixed with /record_id. Now it not only looks, it works! Look at the browser interaction with the server (note different HTTP methods and URLs):Here is an example of creating a new resource on browser side:To follow REST principles as closely as possible I return 201 Created response code together with Location header pointing to newly created resource. As you can see data is now being sent to the server in JSON format. To summarize, such an approach has plenty of advantages:GUI is very responsive, page appears instantly (it can be a static resource served from CDN), while data is loaded asynchronously via AJAX in lightweight JSON format We get CRUD operations for free REST interface for other systems is also for freeCompare this with any web framework out there. And did I mention about this little cherry on our JavaScript frosting: jqGrid is fully compliant with jQuery UI themes and also supports internationalization. Here is the same application with changed theme and language:Full source code is available on Tomek’s GitHub account. The application is self contained, just build it and deploy it to some servlet container. Reference: Poor man’s CRUD: jqGrid, REST, AJAX, and Spring MVC in one house from our JCG partner Tomek Nurkiewicz at the NoBlogDefFound blog. Related Articles :Spring 3 RESTful Web Services RESTful Web Services with RESTeasy JAX-RS on Tomcat 7 – Eclipse and Maven project Spring MVC3 Hibernate CRUD Sample Application Spring MVC Development – Quick Tutorial JAX–WS with Spring and Maven Tutorial...
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books