Monday, July 20, 2015

How to create a function in Jquery and added into an element? (jquery delegation)

I have a json data, and want to process it in Javascript and meanwhile generate a grid to append in  <form id="supplierFilter">.

The code is as following.

Javascript code:

 $(document).ready(function() {  
      var DTclass = ${class};  
      $.fn.classfunction = function() {  
            console.log("classes json:"+DTclass);  
          var columndiv;  
          var classes;  
          for (var i = 0; i < DTclass.length; i++) {  
               columndiv = $("<div class='col-sm-3'>");  
               classes = $("<div class='checkbox'>");  
               classes.append("<label> <input name='filter' value='"+DTclass[i].IMG_FILE_ID+"' type='checkbox'/>     <img src='${pageContext.request.contextPath}/download/"+DTclass[i].IMG_FILE_ID+"' alt='"+DTclass[i].DISPLAY_NAME+"' title='"+DTclass[i].DISPLAY_NAME+"'' /> "+DTclass[i].DISPLAY_NAME);  
               columndiv.append(classes);  
            $('#supplierFilter').append(columndiv);   
          }  
        };   
             $('#supplierFilter').classfunction();            
      )}    


HTML code:

 <form id="supplierFilter"></form>  


At beginning, I just use a regular javascript function, it did generate the html code, but when I clicked on the checkbox function, the function won't be triggered. This is caused by jquery delegation. There are more detail information from :
http://learn.jquery.com/events/event-delegation/

Wednesday, July 15, 2015

How to get last inserted id in DB2?

I have two tables in db2, one child, one parent. I would like to insert data into one table, and get the id (which auto generated in the db2,) then insert the id into another table as a foreign key by using ETL tool, Talend open studio.

After a long time research I found out a solution.
Within the same connection and same transaction use tDB2Input with this select:

 SELECT Identity_val_Local() as id FROM sysibm.sysdummy1  

The Talend job is like this:





Tuesday, July 14, 2015

How to create a dynamic bootstrap grid by using json data from a URL?


I want to display the above dynamic data by using bootstrap grid . The data is in Json format from a  server side URL. Json format data is as below.

 [{"DISPLAY_NAME":"Agreement Supplier","IMG_FILE_ID":138},  
  {"DISPLAY_NAME":"Subrecipient","IMG_FILE_ID" :102},  
  {"DISPLAY_NAME":"California Supplier","IMG_FILE_ID":103},  
  {"DISPLAY_NAME":"Certified Small Business Concern","IMG_FILE_ID":162},  
  {"DISPLAY_NAME":"HUBZone Small Business","IMG_FILE_ID":163},  
  {"DISPLAY_NAME":"Minority-Owned Business","IMG_FILE_ID":164},  
  {"DISPLAY_NAME":"Service-Disabled Veteran-Owned","IMG_FILE_ID" :165},  
  {"DISPLAY_NAME":"Small Business","IMG_FILE_ID":166},  
  {"DISPLAY_NAME":"Small Disadvantaged Business","IMG_FILE_ID":167},  
  {"DISPLAY_NAME":"Veteran-Owned Small Business","IMG_FILE_ID":168},  
  {"DISPLAY_NAME":"Women-Owned Small Business","IMG_FILE_ID":169},  
  {"DISPLAY_NAME":"AbilityOne","IMG_FILE_ID":139},  
  {"DISPLAY_NAME":"8(a)","IMG_FILE_ID":170},  
  {"DISPLAY_NAME":"Catering Supplier","IMG_FILE_ID":171},  
  {"DISPLAY_NAME":"Individual","IMG_FILE_ID":116}]   



I used jQuery to read data from URL and generate the HTML code. The code is as following.

 $(document).ready(function() {  
 // top classes selection  
      $.getJSON("${pageContext.request.contextPath}/download/${classesfileId}",  
             function (json) {  
               console.log(json);  
               var columndiv;  
               var classes;  
               for (var i = 0; i < json.length; i++) {  
                    columndiv = $("<div class='col-sm-3'>");  
                    classes = $("<div class='checkbox'>");  
                    classes.append("<label> <input name='filter' value='"+json[i].IMG_FILE_ID+"' type='checkbox'/><img src='${pageContext.request.contextPath}/download/"+json[i].IMG_FILE_ID+"' alt='"+json[i].DISPLAY_NAME+"' title='"+json[i].DISPLAY_NAME+"'' /> "+json[i].DISPLAY_NAME);  
                    columndiv.append(classes);  
                $('#supplierFilter').append(columndiv);   
               }  
             });  
 });  

In the HTML, I have code as this:

 <form id="supplierFilter">  
 </form>  


When it display in browser, the HTML is generated as this:

 <form id="supplierFilter">  
      <div class="col-sm-3">  
           <div class="checkbox">  
           <label>  
                <input type="checkbox" value="138" name="filter">  
                <img title="Agreement Supplier" alt="Agreement Supplier" src="/supsearch/download/138">  
                Agreement Supplier  
           </label>  
           </div>  
      </div>  
      <div class="col-sm-3">  
           <div class="checkbox">  
           <label>  
                <input type="checkbox" value="102" name="filter">  
                <img title="Subrecipient" alt="Subrecipient" src="/supsearch/download/102">  
                Subrecipient  
           </label>  
           </div>  
      </div>  
      <div class="col-sm-3">  
           <div class="checkbox">  
                <label>  
                <input type="checkbox" value="103" name="filter">  
                <img title="California Supplier" alt="California Supplier" src="/supsearch/download/103">  
                California Supplier  
                </label>  
           </div>  
      </div>  
      <div class="col-sm-3">  
           <div class="checkbox">  
                <label>  
                <input type="checkbox" value="162" name="filter">  
                <img title="Certified Small Business Concern" alt="Certified Small Business Concern" src="/supsearch/download/162">  
                Certified Small Business Concern  
                </label>  
           </div>  
      </div>  
      ......  
 </form>  




Wednesday, June 3, 2015

How to add leading zeroes in front of a number by using Java?

I have some integers. I would like to add leading zeroes if they are less than 100. For example, If the number is 1,  it would be converted to 001. If the number is 10, it would be as 010.

By using Java 7 and above, we can simply to do this by using the following line.

 int i =0;  
 int n=10;  
 System.out.println(String.format("%03d", i));  
 System.out.println(String.format("%03d", n));  




Wednesday, May 27, 2015

Select one unique record from DB table with the latest date

I have a file_store table like below.



I would like to select the latest records for each filetype_id.



The SQL to do this can be like this.

 SELECT f.file_id,f.FILETYPE_ID, f.file_obj_l,max_date  
 FROM FILE_STORE f inner JOIN   
 (SELECT FILETYPE_ID, max(f1.UPDATETS) as max_date FROM FILE_STORE f1  
 where FILETYPE_ID in (1, 2, 3)   
  group by FILETYPE_ID  
 ) a  
 on a.FILETYPE_ID = f.FILETYPE_ID and a.max_date = f.UPDATETS  



Tuesday, May 26, 2015

How to submit form with file upload field to Spring MVC controller?

Here is a very simple example on how to submit form with file upload field to Spring mvc.



1. Make sure you have org.apache.commons.fileupload.FileItemFactory in your library.
I have two blogs on how to add this jar into jboss environment.
http://jijli.blogspot.com/2015/04/jboss-module-dependency-error-caused-by.html
http://jijli.blogspot.com/2015/05/how-to-add-jar-in-maven-project-in.html

2. Add the following in Spring servlet-context.xml.

 <!-- Enable this for eventual integration of file upload functionality-->  
 <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">  
  <!-- setting maximum upload size -->  
  <property name="maxUploadSize" value="20000000"/>   
 </bean>  

3. HTML form.

 <html>  
 <head>  
 <title>Upload File Request Page</title>  
 </head>  
 <body>  
      <form method="POST" action="uploadFile" enctype="multipart/form-data">  
           File to upload: <input type="file" name="file"><br /> <br />  
           Name: <input type="text" name="name"><br /> <br />   
           <input type="submit" value="Upload"> Press here to upload the file!  
      </form>  
 </body>  
 </html>  


4. Spring MVC controller

 import java.io.BufferedOutputStream;  
 import java.io.File;  
 import java.io.FileOutputStream;  
 import org.slf4j.Logger;  
 import org.slf4j.LoggerFactory;  
 import org.springframework.stereotype.Controller;  
 import org.springframework.ui.ModelMap;  
 import org.springframework.web.bind.annotation.RequestMapping;  
 import org.springframework.web.bind.annotation.RequestMethod;  
 import org.springframework.web.bind.annotation.RequestParam;  
 import org.springframework.web.bind.annotation.ResponseBody;  
 import org.springframework.web.multipart.MultipartFile;  
 /**  
  * Handles requests for the application file upload requests  
  */  
 @Controller  
 public class FileUploadController {  
      private static final Logger logger = LoggerFactory  
                .getLogger(FileUploadController.class);  
      @RequestMapping(value = "/uploadFile", method = RequestMethod.GET )  
      public String uploadfile(ModelMap model)  
      {  
           return "upload";  
      }       
      /**  
       * Upload file using Spring Controller  
       */  
      @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)  
      public @ResponseBody  
      String uploadFileHandler(@RequestParam("name") String name,  
                @RequestParam("file") MultipartFile file) {  
           if (!file.isEmpty()) {  
                try {  
                     byte[] bytes = file.getBytes();  
                     // Creating the directory to store file  
                     String rootPath = System.getProperty("catalina.home");  
                     File dir = new File(rootPath + File.separator + "tmpFiles");  
                     if (!dir.exists())  
                          dir.mkdirs();  
                     // Create the file on server  
                     File serverFile = new File(dir.getAbsolutePath()  
                               + File.separator + name);  
                     BufferedOutputStream stream = new BufferedOutputStream(  
                               new FileOutputStream(serverFile));  
                     stream.write(bytes);  
                     stream.close();  
                     logger.info("Server File Location="  
                               + serverFile.getAbsolutePath());  
                     return "You successfully uploaded file=" + name;  
                } catch (Exception e) {  
                     return "You failed to upload " + name + " => " + e.getMessage();  
                }  
           } else {  
                return "You failed to upload " + name  
                          + " because the file was empty.";  
           }  
      }  
 }  




Wednesday, May 20, 2015

How to test a web service with an attachment by using SoapUI?

"SoapUI is a free and open source cross-platform Functional Testing solution. With an easy-to-use graphical interface, and enterprise-class features, SoapUI allows you to easily and rapidly create and execute automated functional, regression, compliance, and load tests. " 

You can download it and more information from http://www.soapui.org/ .

Here is an example I am using it to test a web service with an attachment.

1. Create a SOAP Project.



2. Right click on the project- test, then choose Add WSDL.








3. Now I am going to send a request with an attachment to the service.
    Double click on Request1 on left side, then there is Request 1 window showing on the right side.
    Click on the Attachment.





4. Click on the button in red circle, then choose the file to attach.



5. Click the run button in red circle. Now you can see the result.