Spring File Down-loader

File download is very common to any type of web application. Let’s see how this done in spring framework and java. This is pretty easy and you can add/remove code segments as you want. The given code segments are written as I thought and comments will give you an idea about each code.

Let’s go then, Please follow below simple steps to create your own file down-loader;

Step 1:

Create the spring controller.

  @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
  public void getUserProfilePage(@RequestParam("fileName") String fileName,
  HttpServletRequest request, HttpServletResponse response) {
    FileDownloadManager downloadManager = new FileDownloadManager();
    try {
      downloadManager.downloadFile(fileName, response);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

Step 2:

Create a java Class “DownloadManager” and create below method.

public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
    // reads input file from an absolute path
    try {
      //get fixed file path from the property file of the project
      String filePath = CommonUtil.getValueFromFile("application", "file.upload.location") + fileName;
      File downloadFile = new File(filePath);
      FileInputStream inStream = new FileInputStream(downloadFile);

      // gets MIME type of the file
      String mimeType = new MimetypesFileTypeMap().getContentType(downloadFile);
      if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
      } else if (StringUtils.equals(FilenameUtils.getExtension(filePath), "pdf")
          || StringUtils.equals(FilenameUtils.getExtension(filePath), "PDF")) {
        mimeType = "application/pdf";
      }
      System.out.println("MIME type: " + mimeType);

      // modifies response
      response.setContentType(mimeType);
      response.setHeader("Content-Disposition", "inline; filename=" + downloadFile.getName());
      response.setContentLength((int) downloadFile.length());

      // if you want to forces download you can use below
      // String headerKey = "Content-Disposition";
      // String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
      // response.setHeader(headerKey, headerValue);

      // obtains response's output stream
      OutputStream outStream = response.getOutputStream();

      byte[] buffer = new byte[4096];
      int bytesRead = -1;

      while ((bytesRead = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
      }

      inStream.close();
      outStream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

For mime type; you can use different java libraries like MimeMagic, Tika or use URLConnection. But I have used simple MimetypesFileTypeMap which is available form java 1.7 as I know.

Now you can enjoy the file down-loader by accessing the spring controller via browser. Please contact me for further information.

Create JSON Response in Spring MVC Project

If you finding trouble making json response in your spring project, Please find below simple steps to do that,

Step 01

Add below code snippets in your pom.xml file
<!-- Jackson JSON Mapper -->
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
 <version>1.9.13</version>
 </dependency>
 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.4.1</version>
 </dependency>
 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.4.1.1</version>
 </dependency>

Step 02

Add below code in you spring configuration xml file

 
<!-- Configure to plugin JSON as request and response in method handler --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 
<property name="messageConverters"> 
<list> 
<ref bean="jsonMessageConverter"/> 
</list> 
</property> 
</bean> 

<!-- Configure bean to convert JSON to POJO and vice versa --> 
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> 

Step 03:

Below is the simple example of a controller methode which convert SystemUser Java entity class map returns as a json.

@RequestMapping(value="getSystemUser", method=RequestMethod.GET)
 public @ResponseBody Map<String, Object> getSystemUser(@RequestParam("userId") long userId, HttpServletRequest request){
 SystemUser systemUser = systemUserService.getSystemUser(userId);
 return systemUser.toMap();
 }

If you want to refer my SystemUser object , please find it below.

package com.isd.sappu.savari.domains;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name="users")
public class SystemUser implements Serializable{

 private static final long serialVersionUID = 5489679679570043539L;

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private long userId;
 
 private String username;
 
 private String password;
 
 private String firstName;
 
 private String lastName;
 
 private String address;
 
 private String profilePic;
 
 private Date dateOfBirth;
 
 private String mobileNo;
 
 private String workNo;
 
 private String homeNo;
 
 private double latitude;
 
 private double longtitude;
 
 private int accuracy;
 
 private int activeStatus;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Favorite> favoriteList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Comment> commentList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Rating> ratingList;
 
 @OneToMany(mappedBy="sender")
 @Cascade(CascadeType.ALL)
 private List<Message> messageSentList;
 
 @OneToMany(mappedBy="receiver")
 @Cascade(CascadeType.ALL)
 private List<Message> messageRecievedList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<Product> productList;

 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<SystemUserRole> systemUserRoleList;
 
 @OneToMany(mappedBy="user")
 @Cascade(CascadeType.ALL)
 private List<SearchRequest> searchRequestList;
 
 
 
 public long getUserId() {
 return userId;
 }

 public void setUserId(long userId) {
 this.userId = userId;
 }

 public String getUsername() {
 return username;
 }

 public void setUsername(String username) {
 this.username = username;
 }

 public String getPassword() {
 return password;
 }

 public void setPassword(String password) {
 this.password = password;
 }

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastName() {
 return lastName;
 }

 public void setLastName(String lastName) {
 this.lastName = lastName;
 }

 public String getAddress() {
 return address;
 }

 public void setAddress(String address) {
 this.address = address;
 }

 public String getProfilePic() {
 return profilePic;
 }

 public void setProfilePic(String profilePic) {
 this.profilePic = profilePic;
 }

 public Date getDateOfBirth() {
 return dateOfBirth;
 }

 public void setDateOfBirth(Date dateOfBirth) {
 this.dateOfBirth = dateOfBirth;
 }

 public String getMobileNo() {
 return mobileNo;
 }

 public void setMobileNo(String mobileNo) {
 this.mobileNo = mobileNo;
 }

 public String getWorkNo() {
 return workNo;
 }

 public void setWorkNo(String workNo) {
 this.workNo = workNo;
 }

 public String getHomeNo() {
 return homeNo;
 }

 public void setHomeNo(String homeNo) {
 this.homeNo = homeNo;
 }

 public List<Favorite> getFavoriteList() {
 return favoriteList;
 }

 public void setFavoriteList(List<Favorite> favoriteList) {
 this.favoriteList = favoriteList;
 }

 public List<Comment> getCommentList() {
 return commentList;
 }

 public void setCommentList(List<Comment> commentList) {
 this.commentList = commentList;
 }

 public List<Rating> getRatingList() {
 return ratingList;
 }

 public void setRatingList(List<Rating> ratingList) {
 this.ratingList = ratingList;
 }

 public List<Message> getMessageSentList() {
 return messageSentList;
 }

 public void setMessageSentList(List<Message> messageSentList) {
 this.messageSentList = messageSentList;
 }

 public List<Message> getMessageRecievedList() {
 return messageRecievedList;
 }

 public void setMessageRecievedList(List<Message> messageRecievedList) {
 this.messageRecievedList = messageRecievedList;
 }

 public List<Product> getProductList() {
 return productList;
 }

 public void setProductList(List<Product> productList) {
 this.productList = productList;
 }

 public List<SystemUserRole> getSystemUserRoleList() {
 return systemUserRoleList;
 }

 public void setSystemUserRoleList(List<SystemUserRole> systemUserRoleList) {
 this.systemUserRoleList = systemUserRoleList;
 }

 public int getActiveStatus() {
 return activeStatus;
 }

 public void setActiveStatus(int activeStatus) {
 this.activeStatus = activeStatus;
 }

 public List<SearchRequest> getSearchRequestList() {
 return searchRequestList;
 }

 public void setSearchRequestList(List<SearchRequest> searchRequestList) {
 this.searchRequestList = searchRequestList;
 }

 public double getLatitude() {
 return latitude;
 }

 public void setLatitude(double latitude) {
 this.latitude = latitude;
 }

 public double getLongtitude() {
 return longtitude;
 }

 public void setLongtitude(double longtitude) {
 this.longtitude = longtitude;
 }

 public int getAccuracy() {
 return accuracy;
 }

 public void setAccuracy(int accuracy) {
 this.accuracy = accuracy;
 }
 
 public Map<String, Object> toMap() {
 Map<String, Object> map = new HashMap<String, Object>();
 map.put("userId", userId);
 map.put("username", username);
 map.put("address", address);
 map.put("mobileNo", mobileNo);
 map.put("latitude", latitude);
 map.put("longtitude", longtitude);
 map.put("accuracy", accuracy);
 map.put("activeStatus", activeStatus);
 return map;
 }
 
}

That’s all, Enjoy your json experience.

Thank you…!!!

Enable File uploading in your Spring application

If you are struggling make file uploading in your spring application, most of the time this may be the cause. We always forgot small things when we configure and setup our project.

Add below code in your application context xml file. This will do the magic you want



<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />


Now you can use CommonsMultipartFile in your controller just like below,


@RequestMapping(value="userprofile", method=RequestMethod.POST)
public String getUserProfile(@RequestParam("inputProfilePic") @Null CommonsMultipartFile profilePicture, HttpServletRequest request){

return "profilepage";

}

That’s all, Enjoy file uploading.

Thanks