Tuesday, March 8, 2011

Spring MVC - MultipartFile

Hey...

Today I am going to work with files and do it with spring mvc including uploading, saving and downloading files. Here we can practice spring-mvc and its features more and learn how to work with files in spring mvc.

Use case scenario
This is a file repository application. This application is an extension of simpleSpringSecurity application relating Spring Security post. Users can log in to the application. Then the file list page will be shown.

image 1
User can navigate to folders and download them. current directory is shown anywhere user is in.
image 2

User can create or edit or delete files and folders. both of them are available in the same way. If a folder contains file(s) or folder(s), deleting will not be available and error will be shown. After clicking add button, user see this page
image 3

If user check the tick, so the input entry is file otherwise is folder. folders will be shown as link in list page. but files will be downloadable.
Note: each user has his or her own repository and others are not able to visit it.
Design and Class diagram
Files and Folders domain are the same. So we seperate them with a flag. isFile() method will determite if entry is file or folder. we should save file data in database. so in File table we should create a field with LONGBLOB datatype. In domain we use java.sql.Blob datatype. The class diagram is available here:

image 4
Spring MVC
Most of techniques are the same in past posts. But there are 4 points here:
  1. Configuration: In spring-servlet.xml we should create a bean:
    ...
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxUploadSize" value="100000000"></property>
    </bean>
    This class will prepare you org.springframework.web.multipart.MultipartFile in your controller class if you have an uploaded file in your request. As you see, you can limit the uploaded size. the scale is in bite. For example above sample allows less than about 100MB to be uploaded.
  2. Upload: This phase is so easy. you should just create an input file in your jsp:
    <form:form id="fileForm" enctype="multipart/form-data">
        <form:hidden path="file.id" id="fileId"/>
        <form:hidden path="parentFolder.id" id="fileId"/>
        <table>
            <tr>
                <td><label for="name">name</label></td>
                <td><form:input path="file.name" id="name" maxlength="45"/></td>
            </tr>
            <tr>
                <td><label for="file">file</label></td>
                <td><input type="file" id="file" name="file"/></td>
            </tr>
            <tr>
                <td><label for="isFile">is file</label></td>
                <td><form:checkbox id="isFile" path="file.file"/></td>
            </tr>
        </table>
        <input type="submit" value="save" onclick="setFormAction('<spring:url value="/file/save.html"/>')"/>
        <input type="submit" value="back" onclick="setFormAction('<spring:url value="/file/list.html"/>')"/>
    </form:form>
    then in your uploading method of the controller you can just receive the file in your parameter:
        @RequestMapping("/save")
        public String save(@RequestParam(value = "file", required = false) MultipartFile inputFile) throws IOException, SQLException {
            if (inputFile.getSize() > 0) {
                file.setFileData(getBlobData(inputFile));
            }

            if (parentFolder != null && parentFolder.getId() != null) {
                file.setParentFolder(fileService.findById(parentFolder.getId()));
                getModel().addAttribute("parentFolder.id", parentFolder.getId());
            }

            file.setOwner(getCurrentUser());
            fileService.saveOrUpdate(file);
            return "redirect:list.html";
        }
    Its data type is MultipartFile but should be converted to Blob to be saved.
  3. Save: Here you can convert MultipartFile to Blob:
        public Blob getBlobData(MultipartFile file) throws IOException, SQLException {
            byte[] bytes = file.getBytes();
            return new SerialBlob(bytes);
        }
    now you can set it in your entity bean and lets hibernate save it:
    if (inputFile.getSize() > 0) {
                file.setFileData(getBlobData(inputFile));
            }
  4. Download: Nothing changes in download. we should do everything that is done in classic servlet to download a file:
        @RequestMapping("/download")
        public void download() throws IOException, SQLException {
            file = fileService.findById(file.getId());
            if (file.getOwner().getId().equals(getCurrentUser().getId())) {
                getResponse().setContentType("APPLICATION/OCTET-STREAM");
                getResponse().addHeader("Content-Disposition", "attachment; filename=" + file.getName());
                OutputStream out = getResponse().getOutputStream();
                out.write(file.getFileData().getBytes(1, (int) file.getFileData().length()));
            }
        }
Now you are able to work with files. It's the time to download the source code and try it yourselves. The application database script is available in [app-root]/db/filerepository.sql. you can restore it in your mysql server. the connection datasource properties is in [app-root]/src/database.properites. and after you deploy the project in you application server (like tomcat) the start page will be: http://localhost:8080/home/view.html
the admin user specification is:
username: administrator
password: 123456
you can use it to log in for the first time.
You may have exception whenever you'd like to upload a large file. you should change your server and database server configuration to be able to do it. You should increase the value of maxUploadSize field  in multipartResolver bean. Then refer to your DBMS configuration and change it to make it able to handle large files. For example in mysql server, open "my.cnf" file (/etc/my.cnf in Linux and [window drive]\Program Files\MySQL\MySQL Server 5.0\my.cnf in MS Windows) then add or change this key:
[mysqld]
...

max_allowed_packet=100M
Then restart mysqld service.

Ok. Try yourselves.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Sunday, March 6, 2011

JQuery-CSS-JavaScript

Hi everybody...

We have been working on JQuery-Core and JQuery-DOM yet. Here I am going to explain JQuery-CSS and JQuery-JavaScript.

3. JQuery-CSS

3.1 css(String)
css(String name) returns String

Access a style property on the first matched element. This method makes it easy to retrieve a
style property value from the first matched element.

Example:
Retrieves the color style of the first paragraph
$("p").css("color");
HTML:
<p style="color:red;">Test Paragraph.</p>
Result:
"red"

Example:
Retrieves the font-weight style of the first paragraph.
$("p").css("font-weight");
HTML:
<p style="font-weight: bold;">Test Paragraph.</p>
Result:
"bold"

3.2 css(Map)
css(Map properties) returns jQuery

Set a key/value object as style properties to all matched elements.
This serves as the best way to set a large number of style properties on all matched
elements.

Example:
Sets color and background styles to all p elements.
$("p").css({ color: "red", background: "blue" });
HTML:
<p>Test Paragraph.</p>
Result:
<p style="color:red; background:blue;">Test Paragraph.</p>

3.3 css(String,String|Number)
css(String key, String|Number value) returns jQuery

Set a single style property to a value, on all matched elements. If a number is provided, it is
automatically converted into a pixel value.

Example:
Changes the color of all paragraphs to red
$("p").css("color","red");
HTML:
<p>Test Paragraph.</p>
Result:
<p style="color:red;">Test Paragraph.</p>

Example:
Changes the left of all paragraphs to "30px"
$("p").css("left",30);
HTML:
<p>Test Paragraph.</p>
Result:
<p style="left:30px;">Test Paragraph.</p>

3.4 width()
width() returns String

Get the current computed, pixel, width of the first matched element.

Example:
$("p").width();
HTML:
<p>This is just a test.</p>
Result:
300

3.5 width(String|Number)
width(String|Number val) returns jQuery

Set the CSS width of every matched element. If no explicit unit was specified (like 'em' or '%')
then "px" is added to the width.

Example:
$("p").width(20);
HTML:
<p>This is just a test.</p>
Result:
<p style="width:20px;">This is just a test.</p>

Example:
$("p").width("20em");
HTML:
<p>This is just a test.</p>
Result:
<p style="width:20em;">This is just a test.</p>

3.6 height()
height() returns String

Get the current computed, pixel, height of the first matched element.

Example:
$("p").height();
HTML:
<p>This is just a test.</p>
Result:
300

3.7 height(String|Number)
height(String|Number val) returns jQuery

Set the CSS width of every matched element. If no explicit unit was specified (like 'em' or '%')
then "px" is added to the width.

Example:
$("p").height(20);
HTML:
<p>This is just a test.</p>
Result:
<p style="height:20px;">This is just a test.</p>

Example:
$("p").height("20em");
HTML:
<p>This is just a test.</p>
Result:
<p style="height:20em;">This is just a test.</p>

4. JavaScript
4.1 $.extend(Object,Object,Object)
$.extend(Object target, Object prop1, Object propN)
returns Object

Extend one object with one or more others, returning the original, modified, object. This is a
great utility for simple inheritance.

Example:
Merge settings and options, modifying settings
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
Result:
settings == { validate: true, limit: 5, name: "bar" }
 
Example:
Merge defaults and options, without modifying the defaults
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = jQuery.extend({}, defaults, options);
Result:
settings == { validate: true, limit: 5, name: "bar" }

4.2 $.each(Object,Function)
$.each(Object obj, Function fn) returns Object

A generic iterator function, which can be used to seemlessly iterate over both objects and
arrays. This function is not the same as $().each() - which is used to iterate, exclusively, over
a jQuery object. This function can be used to iterate over anything.
The callback has two arguments:the key (objects) or index (arrays) as first the first, and the
value as the second.

Example:
This is an example of iterating over the items in an array, accessing both the current item and
its index.
$.each( [0,1,2], function(i, n){
 alert( "Item #" + i + ": " + n );
});

Example:
This is an example of iterating over the properties in an Object, accessing both the current
item and its key.
$.each( { name: "John", lang: "JS" }, function(i, n){
 alert( "Name: " + i + ", Value: " + n );
});

4.3 $.trim(String)
$.trim(String str) returns String

Remove the whitespace from the beginning and end of a string.

Example:
$.trim("  hello, how are you?  ");
Result:
"hello, how are you?"

4.4 $.merge(Array,Array)
$.merge(Array first, Array second) returns Array

Merge two arrays together, removing all duplicates.
The result is the altered first argument with the unique elements from the second array
added.

Example:
Merges two arrays, removing the duplicate 2
$.merge( [0,1,2], [2,3,4] )
Result:
[0,1,2,3,4]

Example:
Merges two arrays, removing the duplicates 3 and 2
var array = [3,2,1];
$.merge( array, [4,3,2] )
Result:
array == [3,2,1,4]

4.5 $.grep(Array,Function,Boolean)
$.grep(Array array, Function fn, Boolean inv) returns
Array

Filter items out of an array, by using a filter function.
The specified function will be passed two arguments: The current array item and the index of
the item in the array. The function must return 'true' to keep the item in the array,  false to
remove it.

Example:
$.grep( [0,1,2], function(i){
 return i > 0;
});
Result:
[1, 2]

4.6 $.map(Array,Function)
$.map(Array array, Function fn) returns Array

Translate all items in an array to another array of items.
The translation function that is provided to this method is  called for each item in the array
and is passed one argument:  The item to be translated.
The function can then return the translated value, 'null' (to remove the item), or  an array of
values - which will be flattened into the full array.

Example:
Maps the original array to a new one and adds 4 to each value.
$.map( [0,1,2], function(i){
 return i + 4;
});
Result:
[4, 5, 6]

Example:
Maps the original array to a new one and adds 1 to each value if it is bigger then zero,
otherwise it's removed-
$.map( [0,1,2], function(i){
 return i > 0 ? i + 1 : null;
});
Result:
[2, 3]

Example:
Maps the original array to a new one, each element is added with it's original value and the
value plus one.
$.map( [0,1,2], function(i){
 return [ i, i + 1 ];
});
Result:
[0, 1, 1, 2, 2, 3]

4.7 $.browser()
$.browser() returns Boolean

Contains flags for the useragent, read from navigator.userAgent. Available flags are: safari,
opera, msie, mozilla
This property is available before the DOM is ready, therefore you can use it to add ready
events only for certain browsers.
There are situations where object detections is not reliable enough, in that cases it makes
sense to use browser detection. Simply try to avoid both!
A combination of browser and object detection yields quite reliable results.

Example:
Returns true if the current useragent is some version of microsoft's internet explorer
$.browser.msie

Example:
Alerts "this is safari!" only for safari browsers
if($.browser.safari) { $( function() { alert("this is safari!"); } ); }



all rights reserved by Mostafa Rastgar and Programmer Assistant weblog