среда, 19 июня 2013 г.

Dynamic elements replacement in GWT

    Let's say you want to replace all email addresses from string to some clickable element or maybe add custom handler. I'll show you a way how to do it. 
     For the purpose of this example, we will assume that server side response to the client some information that contains different email addresses. Something like this:
&nbsp;&nbsp;<b>Main requirements:</b><br/>Expertise in Java, Spring Framework, Hibernate, JMS, Enterprise Integration Platforms.<br/>Experience with GWT, JavaScript, JQuery.<br/>Strong object oriented programming concepts: Ability to develop flexible and scalable concept.<br/>Strong understanding of GoF Design Patterns, J2EE Patterns and anti-patterns.<br/>&nbsp;&nbsp;<b>Nice to Have:</b><br/>Experience working with coherent, terracotta technology.<br/>Experience in Subversion, Maven.<br/>Outstanding analytical and communication skills.<br/><br/>Unix/Linux Experience.<br/>Client contact details: first@gmail.com<br/>Email your resume in Word to: second@gmail.com
     But we need to hide the addresses from the UI (so that they do not appear in plain text within HTML) and replace to anchors with text "Send an email message". 
     Next I will show the code in chunks, with a bit of comments for each chunk.
The first things we should do its write a method that replaces each email address that matches the regular expression.
  1. /**
  2. * How to extract all emails from string and replace them.
  3. * Search and replacement e-mails.
  4. *
  5. * @author Dmitry Nikolaenko
  6. *
  7. */
  8. public final class StringUtils {
  9.     public static final String EMAIL_REGEXP =
  10.             "([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})";
  11.     
  12.     /**
  13.      * Only constructed by ourselves. Class contains only static methods.
  14.      */
  15.     private StringUtils() {}
  16.  
  17.     /**
  18.      * Replaces each email that matches the regular expression.
  19.      *
  20.      * @param text the <code>String</code> that is contained required text to handle
  21.      * @return the resulting <tt>String</tt>
  22.      */
  23.     public static String replaceEmail(final String text) {
  24.         // array without any emails
  25.         String[] words = text.split(EMAIL_REGEXP);
  26.  
  27.         String emails = text;
  28.         String result = text;
  29.  
  30.         if (words.length > 1) {
  31.             // gather only emails in one string
  32.             for (String word : words) {
  33.                 if (!word.trim().isEmpty()) {
  34.                     emails = emails.replace(word, " ").trim();
  35.                 }
  36.             }
  37.  
  38.             if (!emails.isEmpty()) {
  39.                 // execute replacement for pattern
  40.                 for (String word : emails.split(" ")) {
  41.                     if (text.contains(word)) {
  42.                         result = result.replaceAll(word, constructReplacement(word));
  43.                     }
  44.                 }
  45.             }
  46.         }
  47.  
  48.         return result;
  49.     }
  50.  
  51.     private static String constructReplacement(final String email) {
  52.         // String#format() doesn't work in GWT
  53.         //return String.format("<a href=\"mailto:%s\">%s</a>", email, email);
  54.         return new StringBuilder("<a href=mailto:").append(email).
  55.                   append(">").append("Send email").append("</a>").toString();
  56.     }
  57. }
     Next step we will find all <a></a> elements and convert them into GWT#anchors.
  1. RootPanel.get().add(new Button("Change click handler for emails") {{
  2.     addClickHandler(new ClickHandler() {
  3.         @Override
  4.         public void onClick(ClickEvent event) {
  5.             NodeList<Element> anchors = html.getElement().getElementsByTagName("a");
  6.             for (int i = 0; i < anchors.getLength(); i++) {
  7.                 Element anchor = anchors.getItem(i);
  8.                 final Anchor email = new Anchor(anchor.getInnerHTML());
  9.                 email.addClickHandler(new ClickHandler() {
  10.                     @Override
  11.                     public void onClick(ClickEvent event) {
  12.                         Window.alert("Send an email message");
  13.                     }
  14.                 });
  15.                 html.addAndReplaceElement(email, anchor);
  16.             }
  17.         }
  18.     });
  19. }});     
Before(reply from server side):

     After(after data processing):

     Here's a link to the source code.

понедельник, 17 июня 2013 г.

Java game development with LWJGL/OpenGL and OpenAL

     This is an example game that recreates the classic game ping pong but with my personal vision. I called it gravity ping pong. The game uses LWJGL(for graphics) and OpenAL(for sound effects) technology. Let's take a closer look at them.
     1) What is LWJGL? 
    LWJGL (Lightweight Java Game Library) provides developers access to different high performance crossplatform libraries. It provides not just a graphics binding but a binding to OpenAL(open standards sound system). In addition, it also gives you access to input devices. This means that your game could be controlled from a gamepad, all from one library. LWJGL provides it’s own keyboard handling objects, so we don’t need use for that AWT anymore. We can simple using Keyboard class. Drawing a sprite on the screen is identical to the JOGL. It’s very easy. 
     2) What is OpenAL? 
    OpenAL (Open Audio Library) is a library for creation of a virtual world of sound. It easily combined with OpenGL 3D world and can very well be used to create games. The OpenAL API is designed to be cross-platform and easy to use. 
     For more information, see: 
     3) So let's look at the game! 
     What the goal of the game? Ping pong is one of the most famous games of the world. The game rules are very simple. You play this game with the arrow keys on your keyboard. Two players hit a ball back and forth using table tennis rackets(in the game it's simple rectangles with different colors). Points are scored when a player fails to return the ball within the rules. In my version of this game if player(from the left side) fails to return the ball, the surface is turning clockwise or vice versa by 10 degrees(it's a random rotation) and player rectangle is reduced, but the opponent rectangle is increased. But if the opponent misses the ball, the platform is rotated by 10 degrees and tends to the horizontal position. In the title of the window you can see current frame rate(FPS) of the game and the game score. That's it :) 
    Controls: 
  - Esc - quit game 
  - Enter - enable/disable fullscreen mode 
  - Arrow keys (up, down, left, right) or (W, S, A, D) - spaceship movement 
    Audio: 
    The game has a background music and the sound of the collision. The magic of the sound was done using OpenAL. Here you can find the package with implementation of the sound
     4) My ideas how to improve the game?
  - Add Sprite/Texture to the game 
  - DIfferent collision object effects 
  - Draw a trajectory of the ball and the gradual disappearance 
  - More real physics based on some realtime physics engine 
  - Powerups or bonuses that will allow to add extra abilities to the player for some time as a game mechanism, they can help in difficult situations or add some dynamic scene to the gameplay 
  - Additional barriers during gameplay 
  - Ability to fire at enemy objects 
We are done. It's a simple example how to build a game with OpenGL.
Here is the link to gravity ping pong game. Have fun with the code!