Showing posts with label J2ee. Show all posts
Showing posts with label J2ee. Show all posts

03 October 2013

Using POJO DataSource in BIRT 4.3



To create a report in BIRT 4.3 we can use POJO dataSource. In 4.3 this DataSource is supported. To use this we need to create a dataset class. We can check this with one example. The following example is done keeping web applications in mind. with little modifications it can be used in the standard-alone applications as well.


To retrieve a student with a specific id we need to have two POJO classes. One is Student.java and the other one is StudentDataSet.java.


Student.java:-


package com.ymd;


public class Student {

private String studentId;
private String name;
private String mobile;
private String email;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}


StudentDataSet.java:-


package com.ymd;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import org.eclipse.birt.report.engine.api.EngineConstants;



import com.ymd.Student;


public class StudentDataSet {
private Iterator<Student> iterator;
public List<Student> getStudents(String studentId){
List<Student> studs=new ArrayList<Student>();
try{
Student stud=getStudent(studentId);
studs.add(stud);
}catch(Exception e){
e.printStackTrace();
}
return studs;
}
private Student getStudent(String studentId){
Student std=new Student();
// your logic to get the details of the student
//goes here. Fetch the student details and populate
// the Student.
return std;
}


//The following method will be called by BIRT engine once when
// the report is invoked. It is also a mandatory method.
@SuppressWarnings(value = { "unchecked" })
public void open(Object appContext, Map<String,Object> map) {
Map<String,Object> mur=(Map<String,Object>) appContext;
HttpServletRequest request=(HttpServletRequest)mur.get(EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST);
String studentId=request.getParameter("studentId");
iterator = getStudents(studentId).iterator();
}
//this method is a mandatory method. It must be implemented. This method
// is used by the BIRT Reporting engine.
public Object next() {
   if (iterator.hasNext())
       return iterator.next();
   return null;
}
//The following method is also a mandatory method. This will be
//called by the BIRT engine once at the end of the report.
public void close() { }
}


In the dataset class the three methods, “public void open(Object obj, Map<String,Object> map)”, “public Object next()” and “public void close()” must be implemented. They will be used by the BIRT Reporting Engine using reflection to generate the report. So in the dataset class we can get the request parameters in the “open” method. so we can pass any number of parameters in the URL and can get the parameters here and use to fetch the data required for the reports. 

The final step is to pack the two classes into a jar file. The name of the jar file can be anything. This jar file will be used by the report designer just to design the report. At run time the classes will be taken from the classpath. I mean in web applications they will be taken from “WEB-INF/classes” folder.


The remaining part of tutorial on how to use POJO Datasource can be read from the following link.

24 September 2013

Uploading a File Using Jsp

The following is the code in html to upload a file.
<html>
<body>
<form action="xxxServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" />
</form>
</body>
</html>


The following is the code for xxxServlet:-


     String saveFile = "";
     String contentType = request.getContentType();
     if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
           DataInputStream in = new DataInputStream(request.getInputStream());
           int formDataLength = request.getContentLength();
           byte dataBytes[] = new byte[formDataLength];
           int byteRead = 0;
           int totalBytesRead = 0;
           while (totalBytesRead < formDataLength) {
                 byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                 totalBytesRead += byteRead;
           }
           String file = new String(dataBytes);
           saveFile = file.substring(file.indexOf("filename=\"") + 10);
           saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
           saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
           int lastIndex = contentType.lastIndexOf("=");
           String boundary = contentType.substring(lastIndex + 1, contentType.length());
           int pos;
           pos = file.indexOf("filename=\"");
           pos = file.indexOf("\n", pos) + 1;
           pos = file.indexOf("\n", pos) + 1;
           pos = file.indexOf("\n", pos) + 1;
           int boundaryLocation = file.indexOf(boundary, pos) - 4;
           int startPos = ((file.substring(0, pos)).getBytes()).length;
           int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
           saveFile = "C:/himanshu/" + saveFile;
           File ff = new File(saveFile);
           FileOutputStream fileOut = new FileOutputStream(ff);
           fileOut.write(dataBytes, startPos, (endPos - startPos));
           fileOut.flush();
           fileOut.close();


If you don’t want to write the code to parse the input stream taken from the request you can use “commons upload” utility provided by apache.


For using commons upload we have to keep the “commons-fileupload.x.x.jar” and “commons-io-x.x.jar” files in the “WEB-APP / lib” folder. These files can be downloaded from http://commons.apache.org/fileupload/ and http://commons.apache.org/io/ .

 The following is the code to place in the xxxServlet:-

 File file ;
int maxFileSize = 5000 * 1024;   
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");

 // Verify the content type
 String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
         DiskFileItemFactory factory = new DiskFileItemFactory();   
         ServletFileUpload upload = new ServletFileUpload(factory);
         // maximum file size to be uploaded.
          upload.setSizeMax( maxFileSize );
          try{          
               List fileItems = upload.parseRequest(request);
              // Process the uploaded file items
              Iterator i = fileItems.iterator();         
              while ( i.hasNext() ){
                   FileItem fi = (FileItem)i.next();
                    if ( !fi.isFormField() ){
     // Get the uploaded file parameters
      String fieldName = fi.getFieldName();
       String fileName = fi.getName();
       boolean isInMemory = fi.isInMemory();
       long sizeInBytes = fi.getSize();    
       // Write the file
      if( fileName.lastIndexOf("\\") >= 0 ){
    file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
       }else{
    file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
        }
                             fi.write( file ) ;
 }//end of if
        }//end of while
    }catch(Exception ex) {
         ex.printStackTrace();
      }
}

Holding the binary data:-
To hold the binary data we have to use InputStream object. This is the object that can hold large binary data. If you pass the InputStream to Statement.setBlob() that saves the binary data to the database.

Getting the real path of the computer on which server is running:-
getServletContext().getRealPath("/upload/files/");

References:-
http://corejavaexample.blogspot.in

19 September 2013

Invoking a Filter By Calling a Servlet

If we need to invoke a Filter when calling a particular servlet the following is the snippet for doing as such


   <filter>
         <filter-name>ViewerFilter</filter-name>
        <filter-class>org.xxx.ViewerFilter</filter-class>
    </filter>
   <filter-mapping>
        <filter-name>ViewerFilter</filter-name>
        <servlet-name>ViewerServlet</servlet-name>
   </filter-mapping>


<servlet>
<servlet-name>ViewerServlet</servlet-name>
<servlet-class>org.xxx.ViewerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewerServlet</servlet-name>
<url-pattern>/frameset</url-pattern>
</servlet-mapping>


So with the above snippet in “web.xml” if we call the “ViewerServlet” the  “ViewerFilter” is automatically executed.