Wednesday, September 4, 2013

Creating Simple 'Hello World' Django web application

Creating Simple Hello World Django/python web application

# Download the Django from: https://www.djangoproject.com/download/

# untar the application tar
$ tar xvf Django-1.5.2.tar

$ cd Django-1.5.2

# Setup django
$ python setup.py install
- this will install django web framework

# Create the new site using following command
$ django-admin.py startproject mysite
- after you run this command, it will create the following folder structure
- mysite
--- manage.py
--- mysite
------ urls.py
------ __init__.py
------ wsgi.py
------ settings.py
------ views.py (add new file as shown below)

# Create new python file in mysite/ directory as views.py and add following line
#!/usr/bin/python
from django.http import HttpResponse
def hello(request):
    html = "<html><body><b>Hello World!</b></body></html>"
    return HttpResponse(html)

# Update the urls.py file in mysite/ directory as
#!/usr/bin/python
from django.conf.urls import patterns, include, url
from mysite.views import hello
urlpatterns = patterns('',
    url(r'^$', hello),
)

# Finally from inside mysite/ directory run this command
$ python manage.py runserver

# Open the browser and type this url http://localhost:8000

Friday, August 23, 2013

Hot Deployment/Republishing the JSF Facelet in Tomcat/Eclipse Environment

Today I was trying to update/republish the JSF pages without redeploying in the tomcat server again and again but couldn't get success.

After few minutes of google, I figured what was the issue. In my web application web.xml file, the FACELETS_REFRES_PERIOD is set as -1 as:

    <context-param>
      <param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
      <param-value>-1</param-value>
    </context-param>

I changed it to '1' and also changed
    <context-param>
      <param-name>javax.faces.PROJECT_STAGE</param-name>
      <param-value>Production</param-value>
    </context-param>



to

    <context-param>
      <param-name>javax.faces.PROJECT_STAGE</param-name>
      <param-value>Development</param-value>
    </context-param>

and VOILA! it worked and I am happy. Now I can change the static resources without module redeploy.




Tuesday, August 20, 2013

Configure ssh login information in config file

How to configure the ssh login information in Config file

Usually we connect the remote host using ssh by giving following command in terminal

$ssh -i filename.pem user@ipaddress 

(if there is the pem file for the security key)

Or

$ssh user@ipaddress

Instead of doing this we can add these information in Config file and just type in

$ssh <host>

The config file reside in .ssh/ folder as .ssh/config and add the following:
Host <HostName/AnyName>
HostName <ipaddress>
User <username>
IdentityFile <if there are any pem file> (Optional)

eg:
Host MyHost
HostName 192.168.1.101
User user

Thursday, March 14, 2013

Setting tomcat server in debug mode

To set up tomcat server in debug mode add the following line in the VM argument

Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

In eclipse configuration you can add the Edit configuration window as shown below:



Setting Maximum Perm Size for JVM

Maximun Perm Memory is the memory where most of the classes and class loader reside. To adjust or increment the maximum perm gen size, just add the following line as VM arguments when starting server.

XX:MaxPermSize=256m

Where 256 is the memory MB, you can adjust this value as per your application requirement.

Sunday, July 15, 2012

Reading file in Java

Following is an example how to read the file and display using System.out.println()

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileReader {
    public static void main(String[] args) {
        String file = "C:\\Users\\test.csv";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file)));
            while (reader.readLine() != null) {
                System.out.println(reader.readLine());
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Upload File using JSF 2.0 and Richfaces

Given below is a simple application how we can upload file using JSF 2.0. The example contain three files
1. The main FileUploadController which has much of the funtionalities for uploading saving files
2. The UploadedText is the bean containing information about the file and
3. The upload.xhtml JSF page.
First Create FileUploadController
1:  import java.io.File;  
2:  import java.io.FileOutputStream;  
3:  import java.io.IOException;  
4:  import java.io.OutputStream;  
5:  import java.io.Serializable;  
6:  import java.util.ArrayList;  
7:  import org.apache.log4j.Logger;  
8:  import org.richfaces.event.FileUploadEvent;  
9:  import org.richfaces.model.UploadedFile;  
10:  import org.springframework.context.annotation.Scope;  
11:  import org.springframework.stereotype.Component;  
12:  import com.jsf.app.client.vo.UploadedText;  
13:  // spring managed bean  
14:  @Component("fileUploadController")  
15:  @Scope("session")  
16:  public class FileUploadController implements Serializable {  
17:       private static final long serialVersionUID = -4664762090820133359L;  
18:       private static final Logger logger = Logger.getLogger(FileUploadBean.class  
19:                 .getName());  
20:       private static final String fPath = "C:\\Users\\";  
21:       private ArrayList<UploadedText> files = new ArrayList<UploadedText>();  
22:       public void paint(OutputStream stream, Object object) throws IOException {  
23:            stream.write(getFiles().get((Integer) object).getData());  
24:            stream.close();  
25:       }  
26:       public void listener(FileUploadEvent event) throws Exception {  
27:            UploadedFile item = event.getUploadedFile();  
28:            UploadedText file = new UploadedText();  
29:            file.setLength(item.getData().length);  
30:            file.setName(item.getName());  
31:            file.setData(item.getData());  
32:            files.add(file);  
33:       }  
34:       public String clearUploadData() {  
35:            files.clear();  
36:            return null;  
37:       }  
38:       public int getSize() {  
39:            if (getFiles().size() > 0) {  
40:                 return getFiles().size();  
41:            } else {  
42:                 return 0;  
43:            }  
44:       }  
45:       public long getTimeStamp() {  
46:            return System.currentTimeMillis();  
47:       }  
48:       public ArrayList<UploadedText> getFiles() {  
49:            return files;  
50:       }  
51:       public void setFiles(ArrayList<UploadedText> files) {  
52:            this.files = files;  
53:       }  
54:       public void writeFile() {  
55:            FileOutputStream fop = null;  
56:            File file;  
57:            UploadedText contain = files.size() > 0 ? files.get(0) : null;  
58:            if (contain == null) {  
59:                 return;  
60:            }  
61:            try {  
62:                 file = new File(fPath + contain.getName());  
63:                 fop = new FileOutputStream(file);  
64:                 if (!file.exists()) {  
65:                      file.createNewFile();  
66:                 }  
67:                 fop.write(contain.getData());  
68:                 fop.flush();  
69:                 fop.close();  
70:                 if (logger.isDebugEnabled()) {  
71:                      logger.debug("File Creation Completed Successfuly.");  
72:                 }  
73:            } catch (IOException e) {  
74:                 e.printStackTrace();  
75:            } finally {  
76:                 try {  
77:                      if (fop != null) {  
78:                           fop.close();  
79:                      }  
80:                 } catch (IOException e) {  
81:                      e.printStackTrace();  
82:                 }  
83:            }  
84:       }  
85:  }  

Next Create the UploadText file:
1:  import java.io.Serializable;  
2:  public class UploadedText implements Serializable {  
3:       private static final long serialVersionUID = -3957467715082208719L;  
4:       private String name;  
5:       private String mime;  
6:       private long length;  
7:       private byte[] data;  
8:       public String getName() {  
9:            return name;  
10:       }  
11:       public void setName(String name) {  
12:            int extDot = name.lastIndexOf('.');  
13:            if (extDot > 0) {  
14:                 String extension = name.substring(extDot + 1);  
15:                 if ("txt".equals(extension)) {  
16:                      mime = "text/plain";  
17:                 } else if ("csv".equals(extension)) {  
18:                      mime = "text/csv";  
19:                 } else {  
20:                      mime = "text/unknown";  
21:                 }  
22:            }  
23:            this.name = name;  
24:       }  
25:       public String getMime() {  
26:            return mime;  
27:       }  
28:       public void setMime(String mime) {  
29:            this.mime = mime;  
30:       }  
31:       public long getLength() {  
32:            return length;  
33:       }  
34:       public void setLength(long length) {  
35:            this.length = length;  
36:       }  
37:       public byte[] getData() {  
38:            return data;  
39:       }  
40:       public void setData(byte[] data) {  
41:            this.data = data;  
42:       }  
43:  }  

Finally Create the JSF file:
1:  <?xml version='1.0' encoding='UTF-8' ?>  
2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
3:  <html xmlns="http://www.w3.org/1999/xhtml"  
4:       xmlns:f="http://java.sun.com/jsf/core"  
5:       xmlns:h="http://java.sun.com/jsf/html"  
6:       xmlns:ui="http://java.sun.com/jsf/facelets"  
7:       xmlns:a4j="http://richfaces.org/a4j"  
8:       xmlns:rich="http://richfaces.org/rich">  
9:  <h:body>  
10:       <ui:composition template="template/common/commonLayout.xhtml">  
11:            <ui:define name="content">  
12:                 <h:form>  
13:                      <h:panelGrid columns="2" columnClasses="top,top">  
14:                           <rich:fileUpload fileUploadListener="#{fileUploadController.listener}"  
15:                                id="upload" acceptedTypes="txt,csv"  
16:                                ontyperejected="alert('Only Text and CSV files are accepted');"  
17:                                maxFilesQuantity="1">  
18:                                <a4j:ajax event="uploadcomplete" execute="@none" render="info" />  
19:                           </rich:fileUpload>  
20:                      </h:panelGrid>  
21:                      <h:panelGroup id="info">  
22:                           <rich:dataGrid columns="1" value="#{fileUploadController.files}"  
23:                                var="file" rowKeyVar="row">  
24:                                <rich:panel bodyClass="rich-laguna-panel-no-header">  
25:                                     <h:panelGrid columns="2">  
26:                                          <a4j:mediaOutput element="img" mimeType="image/jpeg"  
27:                                               createContent="#{fileUploadController.paint}" value="#{row}"  
28:                                               style="width:100px; height:100px;" cacheable="false">  
29:                                               <f:param value="#{fileUploadController.timeStamp}" name="time" />  
30:                                          </a4j:mediaOutput>  
31:                                          <h:panelGrid columns="2">  
32:                                               <h:outputText value="File Name:" />  
33:                                               <h:outputText value="#{file.name}" />  
34:                                               <h:outputText value="File Length(bytes):" />  
35:                                               <h:outputText value="#{file.length}" />  
36:                                          </h:panelGrid>  
37:                                     </h:panelGrid>  
38:                                </rich:panel>  
39:                           </rich:dataGrid>  
40:                           <a4j:commandButton action="#{fileUploadController.clearUploadData}"  
41:                                render="info, upload" value="Clear Uploaded Data"  
42:                                rendered="#{fileUploadController.size>0}" />  
43:                           <a4j:commandButton action="#{fileUploadController.writeFile}"  
44:                                value="Write file to Disk" rendered="#{fileUploadController.size>0}" />  
45:                      </h:panelGroup>  
46:                 </h:form>  
47:            </ui:define>  
48:       </ui:composition>  
49:  </h:body>  
50:  </html>