Pages

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);
    }

}