



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"




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.




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:
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>
“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.
That is, we are adding an element named “state” to the “shipto” data type.
Note that still the “state” element is not added to the class.
So, now you have a dynamic Data-Binding project using JAXB. You can use it as your necessity.




Sometimes you may need to programmatically reload a page. There are two easy way to do that.
public native void reload() /*-{
$wnd.location.reload();
}-*/;
And then call it where necessary.
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.




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.
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.
void sendMail(String recipient, AsyncCallback<String> callback);
String sendMail(String recipient);
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.
<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>
Your Mail Testing Application is done now. Now, Let’s check it.
That’s all for Today.




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.
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("Hello World");
button.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
SC.say("Hello World from SmartGWT");
}
});
button.draw();
}
}
That’s all for the 1st tutorial of SmartGWT.




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:
Draggable draggable = new Draggable(testPanel);
Here, “testPanel” is the FormPanel which you want to make draggable. This will make the form draggable.
draggable.setConstrainHorizontal(true);
draggable.setConstrainVertical(true);
To make a GXT FormPanel resizable:
Resizable resizable = new Resizable(testPanel);
That’s all for today. Happy Coding with GWT+GXT !!!




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”.




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.
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+")}";
}
}
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.




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:
This is created by using FormPanel of GXT. Now, let’s see how to use it:
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);
TextField<String> nameBox = new TextField<String>();
nameBox.setEnabled(true);
nameBox.setEmptyText("Enter your name...");
nameBox.setFieldLabel("Name");
testpanel.add(nameBox,new FormData(-10));
testPanel.addButton(new Button("Submit", new SelectionListener<ButtonEvent>()
{
public void componentSelected(ButtonEvent ce)
{
//write the actions here…..
}
}));
RootPanel.get().add(testPanel);
If you have follwed the previous steps, then you have successfully created a GXT FormPanel with your desired fields.


More Options ...
Categories
Tag Cloud
Blog RSS
Comments RSS

Void « Default
Life
Earth
Wind
Water
Fire
Light 