23 Apr 2011 @ 5:26 AM 

Sometimes, you may need to traverse a directory and enlist all the files, directories inside it.
Suppose we want to print the list of all files and folders under the directory “/home/data/weather”. We can do this in a simple way:

path = '/home/data/weather/'
    dir = os.listdir(path)
    for file in dir:
        if os.path.isdir(path+file) == False :
            print file, "is a file"
        else:
            print file, "is a directory"
Tags Tags: , ,
Categories: Python
Posted By: Hillol
Last Edit: 23 Apr 2011 @ 05 26 AM

EmailPermalinkComments (0)

There are several ways to read a file in Python. The most commonly used way is:

file = open('some file','r')
for line in file.readlines():
    print line
file.close()

The readlines() method reads the whole file at once and loads it in memory. It reduces the disk access frequency, so after loading the file, it would work faster. For small or average sized files, this method is okay. But, whenever you need to read from a huge file, this is not a good way at all. A better way is:

file = open('some file','r')
for line in file:
    print line
file.close()

Only one line is read at a time here. So, you don’t need to be worried about the size of the file.

Tags Tags: , , ,
Categories: Technology
Posted By: Hillol
Last Edit: 23 Apr 2011 @ 04 50 AM

EmailPermalinkComments (0)

JAXB provides a great way for dynamic data-binding. It will be a very handy tool if you want to write a code-generator which will generate codes from XML input files. I’ll show how to do it on Netbeans.

Follow these steps:

  1. Create a new Java Project from Netbeans.
  2. Right click on the project and click new-> Other…

     

     

  3. Choose “JAXB Binding” from XML category.

     

     

  4. Give a binding name, Choose the XML schema file(example: shiporder.xsd) from your file system, choose “XML Schema” in the “Scema Type” option (you can also choose the “XML DTD” if you like to use DTD instead of schema files for Data Type Definition). Chexk the “verbose” option in compiler option.

     

     

    I am using the following XML schema file:

     

    <?xml version=”1.0″ encoding=”ISO-8859-1″ ?>

    <xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema”>

     

    <xs:element name=”shiporder”>

    <xs:complexType>

    <xs:sequence>

    <xs:element name=”orderperson” type=”xs:string”/>

    <xs:element name=”shipto”>

    <xs:complexType>

    <xs:sequence>

    <xs:element name=”name” type=”xs:string”/>

    <xs:element name=”address” type=”xs:string”/>

    <xs:element name=”city” type=”xs:string”/>

    <xs:element name=”country” type=”xs:string”/>

    </xs:sequence>

    </xs:complexType>

    </xs:element>

    <xs:element name=”item” maxOccurs=”unbounded”>

    <xs:complexType>

    <xs:sequence>

    <xs:element name=”title” type=”xs:string”/>

    <xs:element name=”note” type=”xs:string” minOccurs=”0″/>

    <xs:element name=”quantity” type=”xs:positiveInteger”/>

    <xs:element name=”price” type=”xs:decimal”/>

    </xs:sequence>

    </xs:complexType>

    </xs:element>

    </xs:sequence>

    <xs:attribute name=”orderid” type=”xs:string” use=”required”/>

    </xs:complexType>

    </xs:element>

     

    </xs:schema>

     

  5. Click finish. You’ll see some generated classes added to your project.

     

     

  6. Now, goto the main method (static void main) of your project and add the following lines:

     

    “try

    {

    JAXBContext jaxbCtx = JAXBContext.newInstance(Shiporder.class.getPackage().getName());

    Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();

    Shiporder shiporder = (Shiporder) unmarshaller.unmarshal(new File(”shiporder.xml”));

     

    System.out.println(”From XML —> “+shiporder.getOrderperson());

    }

    catch (JAXBException ex)

    {

    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

    }”

     

    Here, Shiporder is the generated class from the Schema file. Now you can use the class and its elements as needed like it is used in the System.out.println() method in the upper code snippet.

     

  7. Your project is ready now. Let’s test the dynamicity of the JAXB binding. Goto the shiporder.xsd file and add “<xs:element name=”state” type=”xs:string”/>” in the “ship to” element so that it looks like the following:

     

     

    That is, we are adding an element named “state” to the “shipto” data type.

     

  8. Now look at the “Shipto” class inside the generated “ShipOrder.java” file. It looks like:

     

     

    Note that still the “state” element is not added to the class.

     

  9. Now, clean and build the project or right click on the “JAXB Bindings” in your project and select “Regenerate Java Code”. And again look at the “Shipto” class. You’ll see that the ShipOrder.java is re-generated and now the element “state” is added.

     

     

    So, now you have a dynamic Data-Binding project using JAXB. You can use it as your necessity.

 

Tags Tags: , ,
Categories: Java, Technology
Posted By: Hillol
Last Edit: 05 Jul 2010 @ 01 30 PM

EmailPermalinkComments (0)

 13 Jan 2010 @ 1:56 PM 

Sometimes you may need to programmatically reload a page. There are two easy way to do that.

  • You can write a native method like this:

     

     public native void reload() /*-{ 
            $wnd.location.reload(); 
        }-*/;

    And then call it where necessary.

  • The second method is preferable. You can reload a page by calling this:

     

    com.google.gwt.user.client.Window.Location.reload();

     

    You can call Window.Location.replace(String newURL) to replace the current URL with a new one.


Tags Tags: , ,
Categories: GWT
Posted By: Hillol
Last Edit: 13 Nov 2010 @ 06 48 AM

EmailPermalinkComments (0)

Sometimes, you’ll need to send mail to users from your web application on behalf of the app’s administrator. If your application is deployed in Google App Engine (GAE), then it’s a piece of cake. GAE provides the mail service. I’ll show you today, how to send mail from a GWT application.

  • First of all, create a GWT application named “MailTest”. Follow the first portion of this blog. Don’t delete the default generated RPC service (GreetingServiceAsync.java, GreetingService.java, GreetingServiceImpl.java).
  • Now add the following method in the GreetingServiceImpl.java (in the server package):

public String sendMail(String recipient)
{
     String msgBody = "It’s a test mail generated by GAE Mail Service….";
     Properties props = new Properties();
     Session session = Session.getDefaultInstance(props, null);
     try
     {
         Message msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress("inflames077@gmail.com", "Hillol Admin"));
         msg.addRecipient(Message.RecipientType.TO,
                          new InternetAddress(recipient, "Mr. User"));
         msg.setSubject("Test Mail…");
         msg.setText(msgBody);
         Transport.send(msg);

     }
     catch (AddressException e)
     {
      e.printStackTrace();
      return e.getLocalizedMessage();
     }
     catch (MessagingException e)
     {
      e.printStackTrace();
      return e.getLocalizedMessage();
     }
     catch (UnsupportedEncodingException e)
     {
       e.printStackTrace();
       return e.getLocalizedMessage();
     }
     return "Success";
}

Here, msg.setFrom() method call is to set the Sender’s Info. One thing is to note here, “for security purposes, the sender address of a message must be the email address of an administrator for the application, or the Google Account email address of the current user who is signed in. The message can also include a "reply to" address, which must also meet these restrictions.”  So, give the mail address that you use to log in and deploy to to Google App Engine.

And, the recipient can be of 3 types: TO, CC, BCC.

The second parameter of the InternetAddress("inflames077@gmail.com", "Hillol Admin") is optional. A personal name can be provided as a string for the second parameter.

  • Now add the following line in the GreetingServiceAsync inteface in the GreetingServiceAsync.java (in the client package):

void sendMail(String recipient, AsyncCallback<String> callback);

  • Add the following line to the GreetingService interface in the GreetingService.java :

String sendMail(String recipient);

  • Now, It’s time to edit our EntryPoint class (MailTest.java). Find the “sendNameToServer()” method and modify it like this:

private void sendNameToServer()
{
    sendButton.setEnabled(false);
    String textToServer = nameField.getText();
    textToServerLabel.setText(textToServer);
    serverResponseLabel.setText("");
    greetingService.sendMail(textToServer,new AsyncCallback<String>()
    {
        public void onFailure(Throwable caught)
        {
            dialogBox.setText("Remote Procedure Call - Failure");
            serverResponseLabel.addStyleName("serverResponseLabelError");
            serverResponseLabel.setHTML(SERVER_ERROR);
            dialogBox.center();
            closeButton.setFocus(true);
        }

        public void onSuccess(String result)
        {
            dialogBox.setText("Remote Procedure Call");
            serverResponseLabel.removeStyleName("serverResponseLabelError");
            serverResponseLabel.setHTML(""+result);
            dialogBox.center();
            closeButton.setFocus(true);
        }
    });
}

I am showing the procedure by making minimal change in the generated project. The whole project can be re-organized by renaming or editing variable names, string messages and so on. But, for the simplicity, I am avoiding those.

  • Now Edit the html file ( MailTest.html). Edit the portion below the <h1> tag :

<h1>Mail Test</h1>
<table align="center">
  <tr>
    <td colspan="2" style="font-weight:bold;">Please enter your mail address:</td>       
  </tr>
  <tr>
    <td id="nameFieldContainer"></td>
    <td id="sendButtonContainer"></td>
  </tr>
</table>

  • Deploy the application in the Google App Engine. (suppose it is deployed to xyz.appspot.com)

 

Your Mail Testing Application is done now. Now, Let’s check it.

  • Open “xyz.appspot.com” in your browser.
  • Write a mail address in the text box. (suppose : “test@gmail.com”)
  • Click the send button. A mail would be sent to “test@gmail.com”.
  • Check the mailbox. You’ll see an incoming mail with the content “It’s a test mail generated by GAE Mail Service….”.

That’s all for Today.

Tags Tags: , , , , ,
Categories: Eclipse, GWT, Technology, Tutorial
Posted By: Hillol
Last Edit: 04 Sep 2009 @ 11 38 PM

EmailPermalinkComments (0)

 29 Aug 2009 @ 11:17 PM 

If you are familiar with some very good looking and very nice frameworks built on GWT, then probably you have already seen SmartGWT. It’s a beautiful and very useful framework.

If you are not familiar with it, you can read about it from here and you can watch the showcase.

SmartGWT 1.2 is now compatible with GWT 1.6 and GWT 1.7 .

Now, we’ll see how to use smartGWT in your GWT project, in a step by step approach.

  • First, download the smartGWT library from here. Unzip it.
  • Create a GWT project named “TestSmartGwt”. You can follow my tutorial.
  • Add the “smartgwt.jar” (form the unzipped folder) to your project libraries (Project –> Properties –> Java Build Path).

 add jar

  • Add “<inherits name="com.smartgwt.SmartGwt"/>”  to the module xml file (testsmartgwt.gwt.xml).

gwt xml

  • Add “<script> var isomorphicDir = "testsmartgwt/sc/"; </script>” in your host HTML file (inside the war).

html

script

  •   Now open the main java file in your client package.

client

  • Remove the default generated code and add the following line of codes to it:

package org.hillol.smartclient.client;
import com.google.gwt.core.client.EntryPoint;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;

public class TestSmartGwt implements EntryPoint
{
	public void onModuleLoad()
	{
		IButton button = new IButton(&quot;Hello World&quot;);
		button.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				SC.say(&quot;Hello World from SmartGWT&quot;);
			}
		});
		button.draw();
	}
}

  • Now, run the project and you’ll see a button on the hosted page. If you click the button, a dialog box will be shown.

run

That’s all for the 1st tutorial of SmartGWT.

Tags Tags: , , , ,
Categories: Eclipse, GWT, Technology, Tutorial
Posted By: Hillol
Last Edit: 13 Nov 2010 @ 06 47 AM

EmailPermalinkComments (7)

 21 Aug 2009 @ 9:48 PM 

In my previous blog I have given a tutorial – how to create a GXT FormPanel. Sometimes, you would give the flexibility to the user to drag the form or to resize it. Today, I’ll show how to do that. Actually, it is a very simple task.

To make a GXT FormPanel draggable:

drag

  • Simply add the following line after creating the FormPanel:

Draggable draggable = new Draggable(testPanel);

       Here, “testPanel” is the FormPanel which you want to make draggable. This will make the form draggable.

  • Now, if you want to add constraints such as restricting vertical drag or horizontal drag, you have to add just another line of code.
  • If you want your form to be dragged only vertically, that means – you want to restrict the user so that he/she can’t drag it horizontally, then add the following line:

draggable.setConstrainHorizontal(true);

  • Similarly, if you want to restrict vertical dragging, add the following line:

draggable.setConstrainVertical(true);

To make a GXT FormPanel resizable:

resize

  • Just add the following line:

Resizable resizable = new Resizable(testPanel);

That’s all for today. Happy Coding with GWT+GXT !!! :-)

Tags Tags: , , , , , , ,
Categories: GWT, GXT, Technology
Posted By: Hillol
Last Edit: 30 Aug 2009 @ 05 41 PM

EmailPermalinkComments (0)

If you have worked with Java EE, you have used this type of session beans hundreds of times:

@Stateless
public class EmployeeServiceBean implements EmployeeService
{
    @PersistenceContext
    private EntityManager em;
    public Employee createOrUpdate(Employee employee)
    {
        return em.merge(employee);
    }
    public void remove(Employee employee)
    {
        em.remove(em.merge(employee));
    }
    public Employee find(Object id)
    {
        return em.find(org.hillol.Employee.class, id);
    }
}

Notice the line “em.remove(em.merge(employee));” in the remove method. If you try to remove the object without calling the merge method, you would get an exception saying that – you are trying to remove an detached entity. A question may arise here, why the entity has to be merged before removing it?

The reason is if you don’t merge the object, it still remains as a detached entity. That means the EJB container would not be able to map the entity with a database entity. In a simple word, it doesn’t know whom to remove from the database. So, if you call merge() first, the object is first attached with a database entity. Then the remove call would be executed successfully. This approach is called “Seek and Destroy”.

Tags Tags: , ,
Categories: Java, Technology, java EE
Posted By: Hillol
Last Edit: 30 Aug 2009 @ 05 48 PM

EmailPermalinkComments (0)

Fluent Interface is a type of coding practice which is aimed to write more readable codes.

Quoting from Wikipedia:

A fluent interface (as first coined by Eric Evans and Martin Fowler) is a way of implementing an object oriented API in a way that aims to provide for more readable code.

A fluent interface is normally implemented by using method chaining to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining). Generally, the context is

  • defined through the return value of a called method
  • self referential, where the new context is equivalent to the last context
  • terminated through the return of a void context.

That is the theoretical aspects of Fluent Interface. In Java Persistence API (JPA), this practice is followed. If you are familiar with JPA, then you have already seen coding like this one:

entitymanager.createNamedQuery("Student.findByNameAgeGender")
             .setParameter("name", name)
             .setParameter("age", age)
             .setParameter("gender", gender)
             .setFirstResult(1)
             .setMaxResults(30)
             .getResultList();

Now we’ll implement it in java by creating two simple classes.

  • First, we’ll create a class named “Fluent”:

class Fluent
{
    private String name;
    private String address;
    private int age;

    public Fluent()
    {
        this.name = "";
        this.address = "";
        this.age = 0;
    }

    public Fluent addAddress(String address)
    {
        this.address = address;
        return this;
    }

    public Fluent addName(String name)
    {
        this.name = name;
        return this;
    }

    public Fluent addAge(int status)
    {
        this.age = status;
        return this;
    }

    @Override
    public String toString()
    {
        return "You have a Fluent object with: {(Name:"+this.name+"),
           (Address:"+this.address+"),(Age:"+this.age+")}";
    }
}

  • Now, create another class named “FluentTest”:

public class FluentTest
{
    public FluentTest()
    {
        Fluent fluent = new Fluent()
                .addName("Hillol")
                .addAddress("Gulshan-1,Dhaka")
                .addAge(25);
        System.out.println(fluent);
    }

    public static void main(String[] args)
    {
        FluentTest fluentTest= new FluentTest();
    }
}

Notice the method chaining here: “new Fluent().addName(…).addAddress(…).addAge(…);” .

This gives an ease to read the code. It is easily understandable that, we are creating an object of Fluent class and then adding name, address and age to that.

Hope you have grasped the idea of Fluent Interface. Now, you would be able to implement it whenever you feel necessary.

Tags Categories: Java, Technology Posted By: Hillol
Last Edit: 30 Aug 2009 @ 05 57 PM

EmailPermalinkComments (2)

 15 Aug 2009 @ 8:37 PM 

I have given a tutorial, how to add GXT to a GWT project in the previous blog. Now, we’ll see how to use GXT for creating various useful stuffs. Sometimes we need to create a user interface like this one:

formPanel This is created by using FormPanel of GXT. Now, let’s see how to use it:

  • First, create a GWT project and add GXT to it. (follow the previous blog)
  • To create a FormPanel, add the following code:

final FormPanel testPanel = new FormPanel();
testPanel.setHeading("Basic Info");
testPanel.setWidth(300);
testPanel.setPagePosition(200,100);
testPanel.setCollapsible(true);
testPanel.setScrollMode(Scroll.AUTO);
testPanel.setFrame(true);
testPanel.setShadow(true);

  • The methods used are self-explanatory, such as: “testPanel.setHeading(”Basic Info”);” will set the heading of the form as “Basic Info”.
  • The “setCollapsible(true)” method call will make the form collapsible. It’ll create a small button at the top-right corner of the Header, which is used to collapse/expand the form.
  • Now add fields to the form, like this one:

TextField<String> nameBox = new TextField<String>();
nameBox.setEnabled(true);
nameBox.setEmptyText("Enter your name...");
nameBox.setFieldLabel("Name");
testpanel.add(nameBox,new FormData(-10));

  • The “setEmptyText(”Enter your name…”)” method will give you a nice utility. It’ll make the textfield to show the text “Enter your name…” in a light gray color, whenever the textfield is empty (As shown in the picture above). It is used to show help text in the text field. But, when the user types anything in that field, that help text disappears.
  • The “setFieldLabel(”Name”)” method call will create a label with text “Name” for the TextField.
  • “testpanel.add(textBox,new FormData(-10));” One thing you may notice here: the use of “new FormData(-10)”. It’s actually used for alignment and spacing purpose. Just use it as I’ve used.
  • Now you can add as many fields as you want to add. You can add other components like combobox in a similar way.
  • Now, it’s time to add buttons in the form. Use the following code:

testPanel.addButton(new Button("Submit", new SelectionListener<ButtonEvent>()
{
    public void componentSelected(ButtonEvent ce)
    {
          //write the actions here…..
    }
}));

  • Your FormPanel is ready now. Now, add it to the root panel:

RootPanel.get().add(testPanel);

If you have follwed the previous steps, then you have successfully created a GXT FormPanel with your desired fields.

Tags Tags: , , , , ,
Categories: GWT, GXT, Technology, Tutorial
Posted By: Hillol
Last Edit: 28 Dec 2009 @ 02 33 PM

EmailPermalinkComments (3)




\/ More Options ...
Change Theme...
  • Users » 1
  • Posts/Pages » 35
  • Comments » 32
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

Conversate



    No Child Pages.

Calendar



    No Child Pages.

News



    No Child Pages.

Ask me



    No Child Pages.

VisitorMap



    No Child Pages.

Miscellaneous



    No Child Pages.