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.

Generating QR Code

Step 01:

Add below to your maven repository.

<!-- https://mvnrepository.com/artifact/net.glxn/qrgen -->
<dependency>
    <groupId>net.glxn</groupId>
    <artifactId>qrgen</artifactId>
    <version>1.4</version>
</dependency>

Step 02:

Add below java util class in to your project and use it as you want. Please note this util class is coded as I wanted, you can amend the code as you want; anyway I added comments to describe the code for you.

package lk.pwc.cult.fund.common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

//importing libraries
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class QRCodeUtil {

  //pass a string generated code to embed in the qr code
  public String retrieveQRCodeImageName(String code) {

    try {
      //generating the qr code in png format and get to Byte Array Output Stream
      ByteArrayOutputStream out = QRCode.from(code).to(ImageType.PNG).stream();

      //get file path from the property file to save the created qr code png
      String filePath = CommonUtil.getValueFromFile("application", "qrcode.file.location");
      //generate a random string to save the qr coded png file
      String fileName = UUID.randomUUID().toString() + ".png";
      String imagePath = filePath + fileName;

      //this set of code uses to create the specific file path if it's not exist
      File theDir = new File(filePath);
      if (!theDir.exists()) {
        try {
          theDir.mkdirs();
          System.out.println("DIR created");
        } catch (SecurityException se) {
          se.printStackTrace();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      FileOutputStream fout = new FileOutputStream(new File(imagePath));

      //Use file output stream to write the qr code png image to a file
      fout.write(out.toByteArray());
      fout.flush();
      fout.close();

      return imagePath;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

  }

}

WildFly/Jboss Server Configuration

WildFly is the open source series of the jboss server. Latest WildFly version is 9.0.

If you are planning to use WildFly, below configuration will be very useful.

when you add the server double click the server and do the below configurations.

Publishing: choose “Automatically publish after a build event”. I like to change the publishing interval to 1 second too.
Application Reload Behavior: check the “Customize application reload …” checkbox and edit the regex pattern to \.jar$|\.class$
Then,

When enabled option Automatically publish when resource change then changes inside *.html, *.xhtml files are immediately reflected as soon as you refresh the browser.
To make hot deployment work for *.jsp files too, then you should inside ${wildfly-home}/standalone/configuration/standalone.xml make following change:

replace with:

Install JAVA in Linux

download .bin file from oracle site.


chmod a+x [bin file name].bin

./[bin file name].bin

mv jdk1.6.0_30 java-6-oracle

sudo mkdir /usr/lib/jvm

sudo mv java-6-oracle /usr/lib/jvm

sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/java-6-oracle/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/java-6-oracle/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/java-6-oracle/bin/javaws" 1

sudo chmod a+x /usr/bin/java
sudo chmod a+x /usr/bin/javac
sudo chmod a+x /usr/bin/javaws
sudo chown -R java6admin:java6admin /usr/lib/jvm/java-6-oracle