Pages

Monday, 10 December 2012

Deferred Binding

Coding Basics - Deferred Binding

Deferred binding is a feature of the GWT compiler that works by generating many versions of code at compile time, only one of which needs to be loaded by a particular client during bootstrapping at runtime. Each version is generated on a per browser basis, along with any other axis that your application defines or uses. For example, if you were to internationalize your application using GWT's Internationalization module, the GWT compiler would generate various versions of your application per browser environment, such as "Firefox in English", "Firefox in French", "Internet Explorer in English", etc... As a result, the deployed JavaScript code is compact and quicker to download than hand coded JavaScript, containing only the code and resources it needs for a particular browser environment.
  1. Deferred Binding Benefits
  2. Defining Deferred Binding Rules
  3. Directives in Module XML files
  4. Deferred Binding Using Replacement
  5. Example Class Hierarchy using Replacement
  6. Deferred Binding using Generators
  7. Generator Configuration in Module XML
  8. Generator Implementation

Deferred Binding Benefits

Deferred Binding is a technique used by the GWT compiler to create and select a specific implementation of a class based on a set of parameters. In essence, deferred binding is the Google Web Toolkit answer to Java reflection. It allows the GWT developer to produce several variations of their applications custom to each browser environment and have only one of them actually downloaded and executed in the browser.
Deferred binding has several benefits:
  • Reduces the size of the generated JavaScript code that a client will need to download by only including the code needed to run a particular browser/locale instance (used by the Internationalization module)
  • Saves development time by automatically generating code to implement an interface or create a proxy class (used by the GWT RPC module)
  • Since the implementations are pre-bound at compile time, there is no run-time penalty to look up an implementation in a data structure as with dynamic binding or using virtual functions.
Some parts of the toolkit make implicit use of deferred binding, that is, they use the technique as a part of their implementation, but it is not visible to the user of the API. For example, many widgets and panels as well as the DOM class use this technique to implement browser specific logic. Other GWT features require the API user to explicity invoke deferred binding by designing classes that follow specific rules and instantiating instances of the classes with GWT.create(Class), including GWT RPC and I18N.
As a user of the Google Web Toolkit, you may never need to create a new interface that uses deferred binding. If you follow the instructions in the guide for creating internationalized applications or GWT RPC calls you will be using deferred binding, but you will not have to actually write any browser dependent or locale dependent code.
The rest of the deferred binding section describes how to create new rules and classes using deferred binding. If you are new to the toolkit or only intend to use pre-packaged widgets, you will probably want to skip on to the next topic. If you are interested in programming entirely new widgets from the ground up or other functionality that requires cross-browser dependent code, the next sections should be of interest.

Defining Deferred Binding Rules

There are two ways in which types can be replaced via deferred binding:
  • Replacement: A type is replaced with another depending on a set of configurable rules.
  • Code generation: A type is substituted by the result of invoking a code genreator at compile time.

Directives in Module XML files

The deferred binding mechanism is completely configurable and does not require editing the GWT distributed source code. Deferred binding is configured through the <replace-with> and <generate-with> elements in the module XML files. The deferred binding rules are pulled into the module build through <inherits> elements.
For example, the following configuration invokes deferred binding for the PopupPanel widget:
Inside the PopupPanel module XML file, there happens to be some rules defined for deferred binding. In this case, we're using a replacement rule.

Deferred Binding Using Replacement

The first type of deferred binding uses replacement. Replacement means overriding the implementation of one java class with another that is determined at compile time. For example, this technique is used to conditionalize the implementation of some widgets, such as the PopupPanel. The use of <inherits> for the PopupPanel class is shown in the previous section describing the deferred binding rules. The actual replacement rules are specified in Popup.gwt.xml, as shown below:
<module> 
 
  <!--  ... other configuration omitted ... --> 
 
  <!-- Fall through to this rule is the browser isn't IE or Mozilla --> 
  <replace-with class="com.google.gwt.user.client.ui.impl.PopupImpl"> 
    <when-type-is class="com.google.gwt.user.client.ui.impl.PopupImpl"/> 
  </replace-with> 
 
  <!-- Mozilla needs a different implementation due to issue #410 --> 
  <replace-with class="com.google.gwt.user.client.ui.impl.PopupImplMozilla"> 
    <when-type-is class="com.google.gwt.user.client.ui.impl.PopupImpl" /> 
    <any> 
      <when-property-is name="user.agent" value="gecko"/> 
      <when-property-is name="user.agent" value="gecko1_8" /> 
    </any> 
  </replace-with> 
 
  <!-- IE has a completely different popup implementation --> 
  <replace-with class="com.google.gwt.user.client.ui.impl.PopupImplIE6"> 
    <when-type-is class="com.google.gwt.user.client.ui.impl.PopupImpl"/> 
    <when-property-is name="user.agent" value="ie6" /> 
  </replace-with> </module>
These directives tell the GWT compiler to swap out the PoupImpl class code with different class implementations according to the the user.agent property. The Popup.gwt.xml file specifies a default implementation for the PopupImpl class, an overide for the Mozilla browser (PopupImplMozilla is substituted for PopupImpl), and an override for Internet Explorer version 6 (PopupImplIE6 is substituted for PopupImpl). Note that PopupImpl class or its derived classes cannot be instantiated directly. Instead, the PopupPanel class is used and the GWT.create(Class) technique is used under the hood to instruct the compiler to use deferred binding.

Example Class Hierarchy using Replacement

To see how this is used when designing a widget, we will examine the case of the PopupPanel widget further. The PopupPanel class implements the user visible API and contains logic that is common to all browsers. It also instantiates the proper implementation specific logic using the GWT.create(Class) as follows:
  private static final PopupImpl impl = GWT.create(PopupImpl.class);
The two classes PopupImplMozilla and PopupImplIE6 extend the PopupImpl class and override some PopupImpl's methods to implement browser specific behavior.
Then, when the PopupPanel class needs to switch to some browser dependent code, it accesses a member function inside the PopupImpl class:
  public void setVisible(boolean visible) { 
    // ... common code for all implementations of PopupPanel ... 
 
    // If the PopupImpl creates an iframe shim, it's also necessary to hide it 
    // as well. 
    impl.setVisible(getElement(), visible); 
  }
The default implementation of PopupImpl.setVisible() is empty, but PopupImplIE6 has some special logic implemented as a JSNI method:
  public native void setVisible(Element popup, boolean visible) /*-{ 
    if (popup.__frame) { 
      popup.__frame.style.visibility = visible ? 'visible' : 'hidden'; 
    } 
  }-*/;{
After the GWT compiler runs, it prunes out any unused code. If your application references the PopupPanel class, the compiler will create a separate JavaScript output file for each browser, each containing only one of the implementations: PopupImpl, PopupImplIE6 or PopupImplMozilla. This means that each browser only downloads the implementation it needs, thus reducing the size of the output JavaScript code and minimizing the time needed to download your application from the server.

Deferred Binding using Generators

The second technique for deferred binding consists of using generators. Generators are classes that are invoked by the GWT compiler to generate a Java implementation of a class during compilation. When compiling for production mode, this generated implementation is directly translated to one of the versions of your application in JavaScript code that a client will download based on its browser environment.
The following is an example of how a deferred binding generator is specified to the compiler in the module XML file hierarchy for the RemoteService class - used for GWT-RPC:

Generator Configuration in Module XML

The XML element <generate-with> tells the compiler to use a Generator class. Here are the contents of the RemoteService.gwt.xml file relevant to deferred binding:
<module> 
 
 <!--  ... other configuration omitted ... --> 
 
 <!-- Default warning for non-static, final fields enabled --> 
 <set-property name="gwt.suppressNonStaticFinalFieldWarnings" value="false" /> 
 
 <generate-with class="com.google.gwt.user.rebind.rpc.ServiceInterfaceProxyGenerator"> 
   <when-type-assignable class="com.google.gwt.user.client.rpc.RemoteService" /> 
 </generate-with> </module>
These directives instruct the GWT compiler to invoke methods in a Generator subclass (ServiceInterfaceProxyGenerator) in order to generate special code when the deferred binding mechanism GWT.create() is encountered while compiling. In this case, if the GWT.create() call references an instance of RemoteService or one of its subclasses, the ServiceInterfaceProxyGenerator's generate()` method will be invoked.

Generator Implementation

Defining a subclass of the Generator class is much like defining a plug-in to the GWT compiler. The Generator gets called to generate a Java class definition before the Java to JavaScript conversion occurs. The implementation consists of one method that must output Java code to a file and return the name of the generated class as a string.
The following code shows the Generator that is responsible for deferred binding of a RemoteService interface:
/** 
 * Generator for producing the asynchronous version of a 
 * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService} interface. 
 */ public class ServiceInterfaceProxyGenerator extends Generator { 
 
  /** 
   * Generate a default constructible subclass of the requested type. The 
   * generator throws <code>UnableToCompleteException</code> if for any reason 
   * it cannot provide a substitute class 
   * 
   * @return the name of a subclass to substitute for the requested class, or 
   *         return <code>null</code> to cause the requested type itself to be 
   *         used 
   * 
   */ 
  public String generate(TreeLogger logger, GeneratorContext ctx, 
      String requestedClass) throws UnableToCompleteException { 
 
    TypeOracle typeOracle = ctx.getTypeOracle(); 
    assert (typeOracle != null); 
 
    JClassType remoteService = typeOracle.findType(requestedClass); 
    if (remoteService == null) { 
      logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" 
          + requestedClass + "'", null); 
      throw new UnableToCompleteException(); 
    } 
 
    if (remoteService.isInterface() == null) { 
      logger.log(TreeLogger.ERROR, remoteService.getQualifiedSourceName() 
          + " is not an interface", null); 
      throw new UnableToCompleteException(); 
    } 
 
    ProxyCreator proxyCreator = new ProxyCreator(remoteService); 
 
    TreeLogger proxyLogger = logger.branch(TreeLogger.DEBUG, 
        "Generating client proxy for remote service interface '" 
            + remoteService.getQualifiedSourceName() + "'", null); 
 
    return proxyCreator.create(proxyLogger, ctx); 
  } }
The typeOracle is an object that contains information about the Java code that has already been parsed that the generator may need to consult. In this case, the generate() method checks it arguments and the passes off the bulk of the work to another class (ProxyCreator).
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License.

Thursday, 1 November 2012

GWT Google Map

Source: http://code.google.com/p/gwt-google-maps-v3/wiki/GettingStarted

Maps Getting Started

Using Google Maps in a GWT project

Getting Started

The Google Maps API provides a convenient JavaScript API which allows you to add mapping functionality to your application. The Google Maps library for GWT allows you to access this JavaScript API from Java code compiled with the GWT compiler.

Assumptions

Downloading the Google Maps Library for GWT

Download latest release from project's download page. Copy downloaded library jar to your projects lib folder(create one if not already present).

Creating a new GWT Project

Start by creating a new GWT project named SimpleMaps as described in the Google Plugin for Eclipse user's guide.
Since we are working with an additional library, add gwt-maps3.jar to the Java classpath. Then, add the inherits line for com.google.gwt.maps.Maps to your module i.e com.example.google.gwt.mapstutorial.SimpleMaps.gwt.xml in our case.
  <inherits name='com.google.gwt.maps.Maps' />

Adding the Maps script tag to your module XML file

Your GWT application will need access to the Maps API, as well as the API key. In order to do this, you must include a
<script>
tag in your module's SimpleMaps.gwt.xml file. Include the script tag shown in your module.xml file above the automatically generated stylesheet reference.
  <script src="http://maps.google.com/maps/api/js?sensor=false" />

Update the HTML host file

Replace the body of the HTML host file war/SimpleMaps.html with a <div> tag that we can use for the GWT application.
  <body>

    <h1>SimpleMaps</h1>

    <div id="mapsTutorial"></div>

  </body>

Add a map object to .java source

To complete the src/com/example/google/gwt/mapstutorial/client/SimpleMaps.java file, add some imports, a member to store a MapWidget instance, and replace the body of the onModuleLoad() method.

package com.example.google.gwt.mapstutorial.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.maps.client.MapOptions;
import com.google.gwt.maps.client.MapTypeId;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.base.LatLng;
import com.google.gwt.user.client.ui.RootPanel;
public class SimpleMaps implements EntryPoint {
  private MapWidget mapWidget;

  // GWT module entry point method.
  public void onModuleLoad() {
    final MapOptions options = new MapOptions();
    // Zoom level. Required
    options.setZoom(8);
    // Open a map centered on Cawker City, KS USA. Required
    options.setCenter(new LatLng(39.509, -98.434));
    // Map type. Required.
    options.setMapTypeId(new MapTypeId().getRoadmap());
    
    // Enable maps drag feature. Disabled by default.
    options.setDraggable(true);
    // Enable and add default navigation control. Disabled by default.
    options.setNavigationControl(true);
    // Enable and add map type control. Disabled by default.
    options.setMapTypeControl(true);
    mapWidget = new MapWidget(options);
    mapWidget.setSize("800px", "600px");
    
    
    // Add the map to the HTML host page
    RootPanel.get("mapsTutorial").add(mapWidget);
  }
}

Run the SimpleMaps sample project

Now you should be able to execute your sample project in dev mode by using the Run configuration from Eclipse.

Tuesday, 30 October 2012

Basic File Upload in GWT

Client: 
 
public class FileUploader{

    private ControlPanel cp;
    private FormPanel form = new FormPanel();
    private FileUpload fu =  new FileUpload();

    public FileUploader(ControlPanel cp) {
     this.cp = cp;
     this.cp.setPrimaryArea(getFileUploaderWidget());
    }

    @SuppressWarnings("deprecation")
    public Widget getFileUploaderWidget() {
     form.setEncoding(FormPanel.ENCODING_MULTIPART);
     form.setMethod(FormPanel.METHOD_POST);
     // form.setAction(/* WHAT SHOULD I PUT HERE */);

     VerticalPanel holder = new VerticalPanel();

     fu.setName("upload");
     holder.add(fu);
     holder.add(new Button("Submit", new ClickHandler() {
      public void onClick(ClickEvent event) {
       GWT.log("You selected: " + fu.getFilename(), null);
       form.submit();
      }
     }));

     form.addSubmitHandler(new FormPanel.SubmitHandler() {
      public void onSubmit(SubmitEvent event) {
       if (!"".equalsIgnoreCase(fu.getFilename())) {
        GWT.log("UPLOADING FILE????", null);
                                        // NOW WHAT????
       }
       else{
        event.cancel(); // cancel the event
       }

      }
     });

     form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
      public void onSubmitComplete(SubmitCompleteEvent event) {
       Window.alert(event.getResults());
      }
     });

     form.add(holder);

     return form;
    }
}
 
Server:
 
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.FileItemIterator; 
import org.apache.commons.fileupload.FileItemStream; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 

public class FileUpload extends HttpServlet{
    public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        ServletFileUpload upload = new ServletFileUpload();

        try{
            FileItemIterator iter = upload.getItemIterator(request);

            while (iter.hasNext()) {
                FileItemStream item = iter.next();

                String name = item.getFieldName();
                InputStream stream = item.openStream();


                // Process the input stream
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int len;
                byte[] buffer = new byte[8192];
                while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                    out.write(buffer, 0, len);
                }

                int maxFileSize = 10*(1024*1024); //10 megs max 
                if (out.size() > maxFileSize) { 
                    throw new RuntimeException("File is > than " + maxFileSize);
                }
            }
        }
        catch(Exception e){
            throw new RuntimeException(e);
        }

    }
} 

web.xml
<servlet>
    <servlet-name>fileUploaderServlet</servlet-name>
    <servlet-class>com.testapp.server.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>fileUploaderServlet</servlet-name>
  <url-pattern>/testapp/fileupload</url-pattern>
</servlet-mapping>
 
 
And: 
form.setAction(GWT.getModuleBaseURL()+"fileupload"); 

3 steps for uploading files in GWT

 Source: http://www.gwttutorial.com/gwt-development/gwt-upload-in-3-easy-steps

3 steps for uploading files in GWT

gwt development There are several very fancy and easy to use GWT Upload libraries that you can use in your applications but sometimes you just need a very simple interface to add an upload functionality to your application.  While the GWT client side of the upload process is the easiest part, many people miss the little tweak that you need to use.
If you want to use one of the fancier upload libraries for cool effects like upload status, I would recommend using GWT-Upload, GwtUpload, or Upload4Gwt.
In order to add this to your page, follow these three easy steps…

Step 1: Create a file upload servlet

There are tons of examples across the internet showing how to do this.  The easiest way is to use the Apache Commons FileUpload library.  An example of a fairly trivial use of this library looks like this:


 Step 2: Modify web.xml

If you are writing a servlet, it goes without saying that you need to add an entry into the web.xml file.
The <servlet> tag tells the web server that you have a class and you want it known by this servlet name.  Then in the <servlet-mapping>, you tell it that the class known by this name, should be invoked when the given URL pattern is requested.
At this point the server is done and all you need is to make the client side of the task

Step 3: GWT Upload Form

Create a FormPanel and add it to your page. The most important part of this code is the FormPanel.ENCODING_MULTIPART and FormPanel.METHOD_POST.

 Conclusion

As you can see, it is simple to an upload functionality to your app.  Now if you do want to add more flash to your look and feel (and who doesn’t like flashy stuff), I would highly recommend using the libraries I suggested above, GWT-UploadGwtUpload, or Upload4Gwt.  They do a fabulous job.  Here is an example of what Upload4Gwt looks like.

gwt development

Tuesday, 23 October 2012

DNS, BIND How to

Source http://www.howtoforge.com/traditional_dns_howto

BIND comes with three components. 
1> named or name-dee. It's a daemon that runs the server side of DNS.

2> resolver library. People think of a resolver as the client side of BIND. The resolver code makes queries of DNS servers in an attempt to translate a friendly name to an IP address. This component uses the resolv.conf file. 
 
3> BIND provides tools for testing you DNS server. We call them tools but they are really a set of command line utilities like dige.g dig yahoo.com

Named lives on a domain name server and answers queries from resolvers. The application reads its data from a configuration file called named.conf. named.conf gets its information from something we call zone files.

 

named.conf

options {
     pid-file "/var/run/bind/run/named.pid";
     directory "/etc/bind";
     // query-source address * port 53; };

//
// a master nameserver config
// The zone statement identifies the location of the hints, localhost, zone and reverse zone files. 
 
zone "." {
     type hint;
     file "db.root";
};

zone "0.0.127.in-addr.arpa" {
     type master;
     file "db.local";
}; 

zone "158.253.70.in-addr.arpa" {
     type master;
     file "pri.158.253.70.in-addr.arpa";
};

zone "centralsoft.org" {
     type master;
     file "pri.centralsoft.org";
};


  • Hints file

  • This file contains the names and addresses of the root servers on the Internet. These know where the authoritative servers for your domain exist - the first one being the Top Level Domain (com, net, org, etc.) and next being the authoritative server for your domain.

  • Local host file

  • Name servers are the masters of their own loopback domain (127.0.0.1). The point of creating local zone files for each aspect of your of localhost is to reduce traffic and allow the same software to work on your system as it does on the network.

  • Zone file

  • This file, also called the domain database, defines most of the information needed to resolve queries about the domain you administer. It maps names to IP addresses and provides information about the services offered by your Internet computer including your web and ftp server, email, telnet, name servers, etc.

    The zone file uses several record types including the SOA or start of authority; NS or name server; A or host name to address map;
    PTR or pointer which maps addresses to names; MX or mail exchanger which identifies the mail servers in the domain; and CNAME or canonical name which defines an alias for a host name.


  • Reverse zone file

  • Another way to talk about zone files is to define them something that links all the IP addresses in your domain to their corresponding server. The reverse zone file maps IP addresses to host files. It's a mirror image of the database file above. You can recognize a reverse zone file because it has the extension of in-addr.arpa.

Now we put all these records in our zone file pri.centralsoft.org. It looks like this:
@ IN SOA server1.centralsoft.org. root.localhost. (
                        2006012103; serial
                        28800; refresh, seconds
                        7200; retry, seconds
                        604800; expire, seconds
                        86400 ); minimum, seconds

;
                   NS server1.centralsoft.org.;
                   NS ns0.centralsoft.org. ;

;
                   MX 10 server1.centralsoft.org.

;

centralsoft.org.   A 70.253.158.42
www                A 70.253.158.42
server1            A 70.253.158.42
ns0                A 70.253.158.45
ftp                CNAME www
centralsoft.org.                  TXT "v=spf1 a mx ~all"
server1.centralsoft.org.          TXT "v=spf1 a -all"





SOA refers to "Start of Authority".  By the time you enter the picture, the system has handed off authority for part of the entire database to you. So, your zone file has to indicate where your authority starts. 

The data field of the SOA record contains several components or fields. They include:
  • Name
  • The root name of the zone. The "@" sign is a shorthand reference to the current origin (zone) in the /etc/named.conf file for that particular database file.
  • Class
  • A number of different DNS classes exist. For our purposes we will use the IN or Internet class used when defining IP address mapping information for BIND. The other classes exist for non Internet protocols and functions.
  • Type
  • The type of DNS resource record. In the example, this is an SOA resource record.
  • Name-server
  • Fully qualified name of your primary name server. Must be followed by a period.
  • Email-address
  • Notice that instead of an @ sign, the address uses a period and is followed by a period. In this case, root@localhost is represented as root.loalhost.
  • Serial-no
  • It is in a date format YYYYMMDD with an incremented double digit number tagged to the end. It's a numeric value that the slave server can use to check whether the zone file has been updated to perform a zone transfer.
  • Refresh
  • This field tells a slave DNS server how often it should check the master and perform a zone transfer. In this file we use 28800s as the value.
  • Retry
  • This field tells the slave how often it should try to connect to the master in the event of a connection failure. The interval in our example is 7200.
  • Expiry
  • Total amount of time a slave should retry to contact the master before expiring the data it contains. Future references will be directed towards the root servers. This is the expiration time, the length of time that the slave server should continue to respond to queries even if it cannot update the zone file. An expiration period exists under the theory that out of date data is worse than no data at all. In our example we use 604800
  • Minimum-TTL  
  • The TTL value defines the caching duration your DNS response. The value is included in your server's response. Because 86400 seconds is one day, the querying cache's record should die in one day.
Next we create NS records. These specify the name servers that are responsible for our domain. You must have at least one, however it is common practice to at least list two.

                   NS server1.centralsoft.org.; 
                   NS ns0.centralsoft.org. ;

 

MX Records

As we want to receive emails on centralsoft.org, we must list the mail exchanger(s) for the domain. This is done with an MX record:
                   MX 10 server1.centralsoft.org.
This record says that emails for centralsoft.org should be delivered to server1.centralsoft.org (which is the mailserver for the domain) with a priority of 10. You can list more than one mail exchanger:
                   MX 10 server1.centralsoft.org.
                   MX 20 mail.someotherdomain.com.
 
Let's say, we have an email address of the form user@subdomain.centralsoft.org. 
Therefore we must create an MX record for subdomain.centralsoft.org:
subdomain.centralsoft.org.        MX 10 server1.centralsoft.org.
 

A Records


centralsoft.org.   A 70.253.158.42

This means that centralsoft.org has the IP address 70.253.158.42.

CNAME Records

CNAME is short for "canonical name", you can think of it as an alias to an A record. For example,
ftp                CNAME www
means, ftp.centralsoft.org is an alias for www.centralsoft.org, so ftp.centralsoft.org points to the same machine as www.centralsoft.org.
A CNAME must always point to an A record; a CNAME must not point to another CNAME! In addition to that, you must not use CNAME records for MX and SOA records. For example,
                   MX 10 ftp   ;not allowed!
is not allowed!

TXT Records

TXT records give you the ability to assign some text/additional information to a zone. Normally this feature is not much in use - with one exception: SPF (Sender Policy Framework) records. These are records that specify from which machines you are allowed to send mail with the sender domain centralsoft.org.
There is a wizard for creating SPF records at http://www.openspf.org/wizard.html?mydomain=&x=26&y=8. We use this wizard to create an SPF record for centralsoft.org, and add this to our zone file:
centralsoft.org.                  TXT "v=spf1 a mx ~all"
server1.centralsoft.org.          TXT "v=spf1 a -all" 

The Reverse Zone File

We need a reverse zone which maps IP addresses to centralsoft.org. This reverse lookup is used by many programs that will refuse to talk to you if the reverse lookup and the forward lookup (i.e. the normal lookup of centralsoft.org) do not match each other.

Therefore we have this in our named.conf file:
zone "158.253.70.in-addr.arpa" {
     type master;
     file "pri.158.253.70.in-addr.arpa";
};





@ IN SOA server1.centralsoft.org. root.localhost. (
                        2006012103; serial
                        28800; refresh, seconds
                        7200; retry, seconds
                        604800; expire, seconds
                        86400 ); minimum, seconds

;
                   NS server1.centralsoft.org.;
                   NS ns0.centralsoft.org. ;

42                 PTR    centralsoft.org.
45                 PTR    ns0.centralsoft.org.

PTR Records

PTR is short for pointer, and that's what it is: it points to a domain name.
centralsoft.org's IP address is 70.253.158.42, and we want 70.253.158.42 to point to centralsoft.org.
The other IP address we use is 70.253.158.45 (for ns0.centralsoft.org)

Secondary Name server

Secondary name server ns0.centralsoft.org

ns0.centralsoft.org's named.conf resembles that of the primary name server very much, with a few differences:
options {
     pid-file "/var/run/bind/run/named.pid";
     directory "/etc/bind";
     // query-source address * port 53;
};


zone "." {
     type hint;
     file "db.root";
};

zone "0.0.127.in-addr.arpa" {
     type master;
     file "db.local";
};

zone "centralsoft.org" {
     type slave;
     file "sec.centralsoft.org";
     masters { 70.253.158.42; };
};


The secondary has contacted the primary name server, and the primary name server has transferred the zone to the secondary.
Now whenever you update the zone on the primary name server, make sure you increase the serial number, otherwise the updated zone will not be transferred to the secondary!
Please make sure you have no firewall on the primary and the secondary name server that blocks port 53 (TCP and UDP) because otherwise zone transfers will fail!

A Word On Security

In our current configuration every name server is allowed to transfer our centralsoft.org zone from our primary name server. Since we want only our secondary name server (70.253.158.45) to be allowed to transfer the zone, we add the following line to the centralsoft.org zone in named.conf on our primary name server server1.centralsoft.org:

So the zone should look like this:
zone "centralsoft.org" {
     type master;
     file "pri.centralsoft.org";
     allow-transfer { 70.253.158.45; };
};




Tuesday, 9 October 2012

GWT Custom Event

Events in general:

Events are always sent to inform about something (e.g. a change of state). Let's take your example with a man and a wall. Here we can imagine that there is a game where a user can walk as a man in a labyrinth. Every time a user hits the wall it should be informed about the collision so that it can react to it (e.g. a wall can render itself as a destroyed wall). This can be achieved by sending a collision event every time the collision with a wall is detected. This event is sent by a man and every object in the system interested in the event receives it and can react to it accordingly. Objects which want to receive events must register themselves as interested with event.
This is how events work in general in every system or framework (not only in GWT). In order to send and receive events in such systems you have to define:
  1. What is sent (what do events look like)
  2. Who receives events (event receivers)
  3. Who sends events (event senders)
Then you can:
  1. Register event receivers which want to receive events
  2. Send events

Events in GWT:

Here I will show an example of using custom events in GWT. I will use an example of a system which is responsible for checking a mailbox and inform a user if there are new mails. Let's assume that in the system there are at least 2 components:
  • message checker responsible for checking the mailbox and
  • message displayer responsible for displaying new mails
Message checker sends events when a new mail is received and message displayer receives these events.

Step 1: Define events

Information about a new mail will be sent as an instance of MessageReceivedEvent class. The class contains a new mail (for the simplicity let's assume it is just a String).
Full source code of this class is presented below (the comment for it is below the source code).
public class MessageReceivedEvent extends GwtEvent<MessageReceivedEventHandler> {

    public static Type<MessageReceivedEventHandler> TYPE = new Type<MessageReceivedEventHandler>();

    private final String message;

    public MessageReceivedEvent(String message) {
        this.message = message;
    }

    @Override
    public Type<MessageReceivedEventHandler> getAssociatedType() {
        return TYPE;
    }

    @Override
    protected void dispatch(MessageReceivedEventHandler handler) {
        handler.onMessageReceived(this);
    }

    public String getMessage() {
        return message;
    }
}
MessageReceivedEventHandler is an interface that represents event receivers. Don't bother with it at the moment, this will be discussed later.
Every class representing a GWT event has to extend GwtEvent class. This class contains two abstract methods which must be implemented: getAssociatedType and dispatch. However in every event class they are usually implemented in a very similar way.
The class stores information about a received message (see constructor). Every event receiver can get it using getMessage method.

Step 2: Define event receivers

Each event type in GWT is associated to an interface representing receivers of this event type. In GWT receivers are called handlers. In the example an event receiver interface for MessageReceivedEvent will be named MessageReceivedEventHandler. The source code is below:
public interface MessageReceivedEventHandler extends EventHandler {
    void onMessageReceived(MessageReceivedEvent event);
}
Each handler has to extend EventHandler interface. It should also define a method which will be invoked when an event occurs (it should take at least one parameter - an event). Here the method is named onMessageReceived. Each receiver can react on an event by implementing this method.
The only event receiver in the example is MessageDisplayer component:
public class MessageDisplayer implements MessageReceivedEventHandler {

    @Override
    public void onMessageReceived(MessageReceivedEvent event) {
        String newMessage = event.getMessage();
        // display a new message
        // ...
    }

}

Step 3: Define event senders

In the example the only event sender is a component responsible for checking mails - EventChecker:
public class MessageChecker implements HasHandlers {

    private HandlerManager handlerManager;

    public MessageChecker() {
        handlerManager = new HandlerManager(this);
    }

    @Override
    public void fireEvent(GwtEvent<?> event) {
        handlerManager.fireEvent(event);
    }

    public HandlerRegistration addMessageReceivedEventHandler(
            MessageReceivedEventHandler handler) {
        return handlerManager.addHandler(MessageReceivedEvent.TYPE, handler);
    }

}
Every event sender has to implement HasHandlers interface.
The most important element here is a HandlerManager field. In GWT HandlerManager as the name suggest manages event handlers (event receivers). As it was said at the beginning every event receiver that wants to receive events must register itself as interested. This is what handler managers are for. They make it possible to register event handlers an they can send a particular event to every registered event handler.
When a HanlderManager is created it takes one argument in its constructor. Every event has a source of origin and this parameter will be used as a source for all events send by this handler manager. In the example it is this as the source of events is MessageChecker.
The method fireEvent is defined in HasHandlers interface and is responsible for sending events. As you can see it just uses a handler manager to send (fire) and event.
addMessageReceivedEventHandler is used by event receivers to register themselves as interested in receiving events. Again handler manager is used for this.

Step 4: Bind event receivers with event senders

When everything is defined event receivers must register themselves in event senders. This is usually done during creation of objects:
MessageChecker checker = new MessageChecker();
MessageDisplayer displayer = new MessageDisplayer();
checker.addMessageReceivedEventHandler(displayer);
Now all events sent by checker will be received by displayer.

Step 5: Send events

To send an event, MessageChecker must create an event instance and send it using fireEvent method. This cane be done in newMailReceived method:
public class MessageChecker implements HasHandlers {

    // ... not important stuff omitted

    public void newMailReceived() {
        String mail = ""; // get a new mail from mailbox
        MessageReceivedEvent event = new MessageReceivedEvent(mail);
        fireEvent(event);
    }

}