Saturday, 14 January 2017

Sending xml(JAXB) and json(Jackson) response with Spring MVC @ResponseBody annotation

Background

In some of our earlier posts we saw examples of how Spring controllers work. 

In those examples we returned a view name from controller method and subsequently corresponding JSP was returned and rendered. In this post we will see how we can send a xml or a json response instead of a JSP.


 Sending xml(JAXB) and json(Jackson) response with Spring MVC @ResponseBody annoatation

Your controller would look like below -

package com.osfg.controllers;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.osfg.model.Employee;

/**
 * 
 * @author athakur
 * Controller to handle employee information
 */
@Controller
public class EmployeeController {

    Logger logger = LoggerFactory.getLogger(EmployeeController.class);

    
    @RequestMapping(value = "/getEmployeeInfoData", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    @ResponseBody
    public Employee getEmployeeInfo(HttpServletRequest request) {
        logger.debug("Receive GET request for employee data information");
        Employee empForm = new Employee();
        empForm.setName("Aniket Thakur");
        empForm.setAge(25);
        return empForm;
    }

}
 
 Most of annotations and code you would already know from previous examples. New thing here is the produces field which is set to 
  • MediaType.APPLICATION_JSON_VALUE,
  • MediaType.APPLICATION_XML_VALUE
which mean your controller method can give response in json or xml. 
NOTE : Spring framework matches this produces field with  accepts header of incoming request.

and your Employee model object would look like -

package com.osfg.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 
 * @author athakur
 * Model class for Employee
 */
@XmlRootElement(name = "employee")
public class Employee implements Serializable {
    
    private static final long serialVersionUID = 1L;
    
    private String name;
    private int age;
     
    @XmlElement
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    @XmlElement
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
     
}


Notice the annotations used. Those are required for XML transformation by JAXB library.

NOTE : Don't forget to add <mvc:annotation-driven/>  tag in your spring configuration file.

Once above code and configurations are in place all you have to do is put JAXB and jackson jars on classpath. I am using ivy so add following dependency on youe ivy xml -

<dependency org="com.fasterxml.jackson.core" name="jackson-databind" rev="2.8.5"/>

NOTE : I am using Java 8. JAXB is inbuilt in java since java 7. So no need to explicitly add it.






You can find the working snippet of above code in my github repo -
https://github.com/aniket91/WebDynamo/blob/master/src/com/osfg/controllers/EmployeeController.java
file of
https://github.com/aniket91/WebDynamo

 Related Links

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

Background

With Spring 3.0 came mvc name space and along with it came a lot of simplifications in Spring framework. The one that we are going to discuss today is - <mvc:annotation-driven />

This is the simplest tag you can add in your spring configuration file to enable many new features.

This is obvious you spring configuration xml tag. For java equivalent you can add the annotation @EnableWebMvc to one of your @Configuration classes.

@Configuration
@EnableWebMvc
public class WebConfig {
}

The above registers a 
  • RequestMappingHandlerMapping, 
  • a RequestMappingHandlerAdapter, and 
  • an ExceptionHandlerExceptionResolver 
(among others) in support of processing requests with annotated controller methods using annotations such as @RequestMapping, @ExceptionHandler, and others.


What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

With <mvc:annotation-driven /> following features get enabled -


  1. Configures the Spring 3 Type ConversionService (alternative to PropertyEditors)
  2. Adds support for formatting Number fields with @NumberFormat
  3. Adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath
  4. Adds support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath
  5. Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with @RequestBody/@ResponseBody)
  6. Adds support for reading and writing JSON, if Jackson is on the classpath (along the same lines as #5)
This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:

  1.  ByteArrayHttpMessageConverter converts byte arrays.  
  2.  StringHttpMessageConverter converts strings. 
  3.  ResourceHttpMessageConverter converts to/from org.springframework.core.io.Resource for all media types. 
  4.  SourceHttpMessageConverter converts to/from a javax.xml.transform.Source. 
  5.  FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>. 
  6.  Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present and Jackson 2 XML extension is not present on the classpath. 
  7.  MappingJackson2HttpMessageConverter converts to/from JSON — added if Jackson 2 is present on the classpath. 
  8.  MappingJackson2XmlHttpMessageConverter converts to/from XML — added if Jackson 2 XML extension is present on the classpath. 
  9.  AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath. 
  10.  RssChannelHttpMessageConverter converts RSS feeds — added if Rome is present on the classpath.

context:annotation-config on the other hand looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.


Related Links



Sunday, 25 December 2016

Combine multiple PDF files into one in your Mac OS

Background

Couple of days back I had to upload a signed copy of an online document So I took it's printout and then scanned each page as a PDF. TO re upload I had to make it back into a single pdf file. Well of its a generic document you can use online pdf tools. But in my case the document was somewhat private and well it had my sign. So I could not do it online. In mac you can do it offline with in in built application called preview. Let us see how we can do it.


Combine multiple PDF files into one in your Mac OS

  • First open your PDF file with preview application. To do so you can right click and select over with preview.

  • Next go to View and Enable Thumbnails. You should see your current pfd in thumbnail panel on the left.

  • Now go to edit and select edit -> Page from file and then select other pdf file you need to combine. Do this for as many pdf files as you need to combine.

  • You can also drag and reorder pdf files in the thumbnail panel. You can also select pdf in this panel and click delete to delete the page.

  • Finally click on File -> Save to save the combined PDF.

Sunday, 18 December 2016

Greasemonkey script to dim white background webpages in Firefox

Background

In some of the previous posts we saw some greasemomkey scripts -
 This is a similar script.

Bright white pages strain your eyes. I love dark black/grey themes and they dont strain your eyes as well. So was looking out for an addon to do this.
Chrome has a beautiful addon called -
Unfortunately there is no such good plugin available on Firefox. Hence this script. You can configure RGB to the background color you wish to have. The script will be executed when your DOM(Document object model) is loaded.

Greasemonkey script to dim white background webpages in Firefox

I am not going to paste the code here. It is available on my Github gists page -
Feel free to fork it and change it as per you need. Google homepage looks like below post this change -


It has sort of greyish background.


NOTE : This is not a script originally written by me. I have just modified it to suit my needs. Feel free to edit it and use as per your requirements.

Related Links

Saturday, 17 December 2016

Introduction to crontab - scheduling tasks in Linux

Background

Cron is a daemon that runs in background and helps executing commands or set of commands at a predefined time. You can use to to schedule your commands at regular intervals. For example a batch job to pull all your unread mails.

Crontab


This will be per user. So each user can have their cron jobs and are stored in separate files called crontab files. To handle these the command used is crontab. The crontab file is often stored in

  • /var/spool/cron/crontabs/<user> (Unix/Slackware/*BSD),
  • /var/spool/cron/<user> (RedHat) or 
  • /var/cron/tabs/<user> (SuSE),
but might be kept elsewhere depending on what Un*x flavor you're running. Though these files are in var they are not supposed to be edited directly. As mentioned earlier you should use crontab commands.
  • crontab [ -u user ] file
  • crontab [ -u user ] { -l | -r | -e }
Options are as follows -
  • The -l option causes the current crontab to be displayed  on  standard output. 
  • The -r option causes the current crontab to be removed.
  • The  -e option is used to edit the current crontab using the editor specified by the VISUAL or EDITOR environment variables.  After you exit  from the editor, the modified crontab will be installed auto‐matically. If neither of the environment variables is defined, then the default editor /usr/bin/editor is used.
For more details see
  • man crontab 


 As mentioned in the usage of edit crontab option you need to first set your editor -
  • aniket@aniket-Compaq-610:~$ export EDITOR=vi

 Creating a new cron job

Edit your crontab file with command -
  •  aniket@aniket-Compaq-610:~$ crontab -e
Now your crontab file should be opened in vi. Enter following command, press enter and save your file.

  • */1 * * * * date >> /tmp/log.txt 2>&1
This essentially puts current date every 2 mins in /tmp/log.txt file (combines standard output and error streams to stdout)

You should see following output -
crontab: installing new crontab

Post saving you can check the contents of your crontab file with command -
  • crontab -l



You can now check /tmp/log.txt file for output -



 
Finally you can delete your crontab file using command -
  • crontab -r


Format of crontab file command line

Syntax is as follows -
  • minute hour day-of-month month day-of-week command 
Possible values -
  • The asterisk (*) operator specifies all possible values for a field. e.g. every hour.
  • The comma (,) operator specifies a list of values. For eg every 2nd and 10th hour of the day.
  • The dash (-) operator specifies a range of values, Eg: "1-4", which is equivalent to "1,2,3,4".
  • The slash (/) operator, can be used to skip a given number of values. Eg "*/4" in the hour part of syntax would be equivalent to "0,4,8,12,16,20". "*" specifies 'every hour' but the "/4" means that skip 4 and try.
 Now lets revisit the command we used -
  • */1 * * * * date >> /tmp/log.txt 2>&1 
It means execute command every minute, every hour, every day of month, every year, each day of a week.

There are also special string that you can use instead of above syntax -

 

NOTES

  • As mentioned earlier each user has his/her crontab file. If you want to do operations that require root permissions you need to use root crontab file. To use that you can execute 
    • sudo crontab -e
  • In the /etc directory you will probably find some sub directories called  
    • 'cron.hourly', 
    • 'cron.daily', '
    • cron.weekly' and 
    • 'cron.monthly'.
      If you place a script into one of those directories it will be run either hourly, daily, weekly or monthly, depending on the name of the directory. 
  • Cron will email to the user all output of the commands it runs, to silence this, redirect the output to a log file or to /dev/null.
    • Eg. */1 * * * * date >> /dev/null 2>&1
  • For Cron permissions these two files play an important role:
    • /etc/cron.allow - If this file exists, it must contain your username for you to use cron jobs.
    • /etc/cron.deny - If the cron.allow file does not exist but the /etc/cron.deny file does exist then, to use cron jobs, you must not be listed in the /etc/cron.deny file.

Related Links

t> UA-39527780-1 back to top