display formatted json in the page

To Display formatted json we need to use
<pre> tag and stringify the js object.

Use JSON.Stringify

JSON.stringify(value[, replacer [, space]])

Parameters

  • value The value to convert to a JSON string.
  • replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
  • space Causes the resulting string to be pretty-printed.

For example:

JSON.stringify({a:1,b:2,c:{d:3, e:4}},null,"    ")

will give you following result:

"{
    "a": 1,
    "b": 2,
    "c": {
        "d": 3,
        "e": 4
    }
}"

Use angularjs built-in filter

If you are using angularjs, you can leverage the build in ‘| json’ filter.

<pre>{{data | json}}</pre>

Note the use of the pre-tag to conserve whitespace and linebreaks

Demo: http://plnkr.co/edit/lwqajlWvJGTaH0HTfnJd?p=preview

There’s also an angular.toJson method, but I haven’t played around with that (Docs)

Converting Nested Json files to CSV in java with reflection

Objective:

convert nested json to csv. The csv header should contain fields from each level and separated by ‘_’.

Example:

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "9513 Key west ave",
    "city": "Rockville",
    "state": "MD",
    "postalCode": "20874"
  },
  "phoneNumbers": 
    {
      "type": "home",
      "number": "212 555-1234"
    },
  "children": {},
  "spouse": null
}

Header should become: firstName, lastName, isAlive, age, address_streeAddress, address_city, address_state, address_postalCode, phoneNumbers_type….etc

Actions:

1. deserialize the json to the mapped java object using gson or jackson.

2. append header first using reflection

    StringBuilder sb = new StringBuilder();
    appendAllDeclaredFields(YourClass.class, YourClass.class.getPackage().getName(), "", sb);
    /**
     *
     * @param c The class to get fields from
     * @param rootPackage The root package to compare(we only get fields from the same package to exclude other java class)
     * @param parentName The parent class name so that we could combine all its path.
     * @param sb the string builder to append values with comma delimited
     * <p/>
     * This function will search recursively and append all the fields
     * MyObject{int fileld1, OtherObject, other}, OtherObject{int filed2, String filed3}  --> filed1,other_filed2,otherfield3
     */
    void appendAllDeclaredFields(Class c, String rootPackage, String parentName, StringBuilder sb)
    {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields)
        {
            Class filedClass = field.getType();
            String fieldName = field.getName();
            //if we have declaredfileds and the filed is in in the same package  as root and filed is not Enum, we continue search
            if (filedClass.getDeclaredFields().length > 0 && filedClass.getPackage().getName().contains(rootPackage) && !filedClass.isEnum())
            {
                appendAllDeclaredFields(filedClass, rootPackage, getCombinedName(parentName, fieldName), sb);
            }
            //If it is plain fields like String/int/bigDecimal, we append the filed name.
            else
            {
                sb.append(",").append(getCombinedName(parentName, fieldName));
            }
        }
    }

    private String getCombinedName(String parentName, String fieldName)
    {
        return "".equals(parentName) ? fieldName : parentName + "_" + fieldName;
    }

3. append values with reflection

This is usually called in a loop of all your target data objects needed to be dumped.

    /**
     *
     * @param c The class to get fields from
     * @param rootPackage The root package to compare(we only get fields from the same package to exclude other java class)
     * @param target the target object to get value from
     * @param sb the string builder to append values with comma delimited
     *
     * @throws IllegalAccessException This function will search recursively and append all the values of the 'target' Object.
     */
    void appendDeclaredFieldValues(Class c, String rootPackage, Object target, StringBuilder sb) throws IllegalAccessException
    {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields)
        {
            Class filedClass = field.getType();
            field.setAccessible(true);
            Object childObject = null;
            try
            {
                //try to get the object value from the 'target' Object
                childObject = field.get(target);
            }
            catch (Exception e)
            {
                //do nothing, just a try to get value, exception is expected with empty columns
            }
            //if we have declaredfileds and the filed is in in the same package  as root and filed is not Enum, we continue search
            if (filedClass.getDeclaredFields().length > 0 && filedClass.getPackage().getName().contains(rootPackage) && !filedClass.isEnum())
            {
                appendDeclaredFieldValues(filedClass, rootPackage, childObject, sb);
            }
            //If it is plain fields like String/int/bigDecimal, we append the filed value.
            else
            {
                //Since this is served as CSV, we do not want the object value contains comma which would break the formatting.
                sb.append(",").append(String.valueOf(childObject).replaceAll(",", "").replaceAll("(\r\n|\n)", ""));
            }

        }
    }

Spring 4 MVC ContentNegotiatingViewResolver example

This article demonstrates supporting multiple output formats for your Spring 4 MVC application using Spring’sContentNegotiatingViewResolver. We will be generating application output in XML, JSON, PDF, XLS and HTML format, all using Annotation based configuration.

ContentNegotiatingViewResolver is an implementation of ViewResolver, which uses the requested media type (based on filetype extension, URL parameter specifying type of output format or accept header) to select a suitable View for a request. ContentNegotiatingViewResolver does not resolve view by itself but delegates to other ViewResolver you can configure to handle specific views(XML,JSON,PDF,XLS,HTML,..).


Following technologies being used:

  • Spring 4.0.6.RELEASE
  • jackson-databind 2.4.1.3
  • jackson-annotations 2.4.1
  • lowagie itext 4.2.1
  • Apache POI 3.10-beta2
  • Maven 3
  • JDK 1.6
  • Tomcat 7.0.54
  • Eclipse JUNO Service Release 2

Let’s begin.

Step 1: Create the directory structure

Following will be the final directory structure for this example:

We will be using Spring Java Configuration(Annotations). Now let’s add/update the content mentioned in above project structure.

Step 2: Update pom.xml with required dependencies

<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.websystique.springmvc</groupId>
    <artifactId>Spring4MVCContentNegotiatingViewResolverExample</artifactId>
    <packaging>war</packaging>
    <version>1.0.0</version>
    <name>Spring4MVCContentNegotiatingViewResolverExample</name>
 
    <properties>
        <springframework.version>4.0.6.RELEASE</springframework.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
 
        <!-- Needed for XML View (with JAXB2) -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${springframework.version}</version>
        </dependency>
 
        <!-- Needed for JSON View -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.4.1</version>
        </dependency>
 
        <!-- Needed for PDF View -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>4.2.1</version>
        </dependency>
         
        <!-- Needed for XLS View -->     
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-beta2</version>
        </dependency>
 
        <!-- Servlet dependencies -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
 
    </dependencies>
 
 
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>Spring4MVCContentNegotiatingViewResolverExample</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
 
        <finalName>Spring4MVCContentNegotiatingViewResolverExample</finalName>
    </build>
</project>

spring-oxm is included to support XML output generation (using JAXB2). jackson-databind & jackson-annotations provide JSON output support. itext provide PDF generation library to support PDF output.Apache POI will help producing XLS output format.

Step 3: Create Spring Configuration Class

com.websystique.springmvc.configuration.AppConfig

package com.websystique.springmvc.configuration;
 
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
 
import com.websystique.springmvc.model.Pizza;
import com.websystique.springmvc.viewresolver.ExcelViewResolver;
import com.websystique.springmvc.viewresolver.JsonViewResolver;
import com.websystique.springmvc.viewresolver.Jaxb2MarshallingXmlViewResolver;
import com.websystique.springmvc.viewresolver.PdfViewResolver;
 
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.websystique.springmvc")
public class AppConfig extends WebMvcConfigurerAdapter {
 
    /*
     * Configure ContentNegotiationManager
     */
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.ignoreAcceptHeader(true).defaultContentType(
                MediaType.TEXT_HTML);
    }
 
    /*
     * Configure ContentNegotiatingViewResolver
     */
    @Bean
    public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
        resolver.setContentNegotiationManager(manager);
 
        // Define all possible view resolvers
        List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
 
        resolvers.add(jaxb2MarshallingXmlViewResolver());
        resolvers.add(jsonViewResolver());
        resolvers.add(jspViewResolver());
        resolvers.add(pdfViewResolver());
        resolvers.add(excelViewResolver());
         
        resolver.setViewResolvers(resolvers);
        return resolver;
    }
 
    /*
     * Configure View resolver to provide XML output Uses JAXB2 marshaller to
     * marshall/unmarshall POJO's (with JAXB annotations) to XML
     */
    @Bean
    public ViewResolver jaxb2MarshallingXmlViewResolver() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setClassesToBeBound(Pizza.class);
        return new Jaxb2MarshallingXmlViewResolver(marshaller);
    }
 
    /*
     * Configure View resolver to provide JSON output using JACKSON library to
     * convert object in JSON format.
     */
    @Bean
    public ViewResolver jsonViewResolver() {
        return new JsonViewResolver();
    }
 
    /*
     * Configure View resolver to provide PDF output using lowagie pdf library to
     * generate PDF output for an object content
     */
    @Bean
    public ViewResolver pdfViewResolver() {
        return new PdfViewResolver();
    }
 
    /*
     * Configure View resolver to provide XLS output using Apache POI library to
     * generate XLS output for an object content
     */
    @Bean
    public ViewResolver excelViewResolver() {
        return new ExcelViewResolver();
    }
 
    /*
     * Configure View resolver to provide HTML output This is the default format
     * in absence of any type suffix.
     */
    @Bean
    public ViewResolver jspViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
 
}

Let’s discuss above class in details :

First step is to create the ContentNegotiationManager which is used to determine the requested media types of a request by delegating to a list of ContentNegotiationStrategy instances. By defaultPathExtensionContentNegotiationStrategy is consulted (which uses the URL extension e.g. .xls, .pdf,.json..) , followed by ParameterContentNegotiationStrategy (which uses the request parameter ‘format=xls’ e.g.), followed by HeaderContentNegotiationStrategy (which uses HTTP Accept Headers).

public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.ignoreAcceptHeader(true).defaultContentType(
            MediaType.TEXT_HTML);
}

In our example, we will be using the URL extension to help determine the media types. Also, we have set the default media type to TEXT_HTML in absence of file extension or when the filetype is unknow, that means JSP view resolver will be used when no [known] URL extension found.

Next step is to configure ContentNegotaionViewResolver itself,

public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
    resolver.setContentNegotiationManager(manager);
    // Define all possible view resolvers
    List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
    resolvers.add(jaxb2MarshallingXmlViewResolver());
    resolvers.add(jsonViewResolver());
    resolvers.add(jspViewResolver());
    resolvers.add(pdfViewResolver());
    resolvers.add(excelViewResolver());
    
    resolver.setViewResolvers(resolvers);
    return resolver;
}

We need to set the ContentNegotiationManager which will be injected by Spring, and different resolvers for each possible output format our application might produce.

Finally, we have created different view resolvers for XML, JSON, PDF, XLS and HTML output which we will discuss next.

Step 4: Create Different View Resolvers

Let’s now create tha actual view resolvers itself.

XML View Resolver:

This view resolver relies on JAXB2 Marshalling/unmarshalling to produce XML output. The domain class needs to be annotated with JAXB2 annotations.

com.websystique.springmvc.viewresolver.Jaxb2MarshallingXmlViewResolver

package com.websystique.springmvc.viewresolver;
import java.util.Locale;
import org.springframework.oxm.Marshaller;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.xml.MarshallingView;
public class Jaxb2MarshallingXmlViewResolver implements ViewResolver {
    private Marshaller marshaller;
    
    public Jaxb2MarshallingXmlViewResolver(Marshaller marshaller) {
        this.marshaller = marshaller;
    }
    
    
    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        MarshallingView view = new MarshallingView();
        view.setMarshaller(marshaller);
        return view;
    }
}

Below is the domain object (annotated with standard XML annotations) for our example:

com.websystique.springmvc.model.Pizza

package com.websystique.springmvc.model;
 
import java.util.ArrayList;
import java.util.List;
 
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement(name = "pizza")
public class Pizza {
     
    private String name;
     
    private String flavor;
     
    private List<String> toppings = new ArrayList<String>();
     
    public Pizza(){
         
    }
     
    public Pizza(String name){
        this.name = name;
        this.flavor = "spicy";
        this.toppings.add("Cheese");
        this.toppings.add("bakon");
    }
     
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    @XmlElement
    public void setFlavor(String flavor) {
        this.flavor = flavor;
    }
 
    public String getFlavor() {
        return flavor;
    }
 
    public List<String> getToppings() {
        return toppings;
    }
     
    @XmlElement
    public void setToppings(List<String> toppings) {
        this.toppings = toppings;
    }
     
}

JSON View Resolver:

This view resolver is using Spring MappingJackson2JsonView to get the view used to convert POJO to JSON.

com.websystique.springmvc.viewresolver.JsonViewResolver

package com.websystique.springmvc.viewresolver;
import java.util.Locale;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
public class JsonViewResolver implements ViewResolver{
    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setPrettyPrint(true);      
        return view;
      }
}

PDF View Resolver:

This view resolver is using lowagie itext library to actually generate PDF output.Also note that actual view extends from Spring AbstractPdfView which itself internally uses lowagie itext library.

com.websystique.springmvc.viewresolver.PdfView

package com.websystique.springmvc.viewresolver;
 
import java.awt.Color;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.view.document.AbstractPdfView;
 
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.websystique.springmvc.model.Pizza;
 
public class PdfView extends AbstractPdfView {
 
    @Override
    protected void buildPdfDocument(Map<String, Object> model,
            Document document, PdfWriter writer, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
 
        Pizza pizza = (Pizza) model.get("pizza");
 
        PdfPTable table = new PdfPTable(3);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.getDefaultCell().setBackgroundColor(Color.lightGray);
 
        table.addCell("Name");
        table.addCell("Flavor");
        table.addCell("Toppings");
 
        table.addCell(pizza.getName());
        table.addCell(pizza.getFlavor());
 
        StringBuffer toppings = new StringBuffer("");
        for (String topping : pizza.getToppings()) {
            toppings.append(topping);
            toppings.append(" ");
        }
        table.addCell(toppings.toString());
        document.add(table);
 
    }
 
}

com.websystique.springmvc.viewresolver.PdfViewResolver

package com.websystique.springmvc.viewresolver;
import java.util.Locale;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
public class PdfViewResolver implements ViewResolver{
    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        PdfView view = new PdfView();
        return view;
      }
    
}

XLS View Resolver:

This view resolver is using Apache POI library to actually generate Microsoft XLS output.Also note that actual view extends from Spring AbstractExcelView which itself internally uses Apache POI library.

com.websystique.springmvc.viewresolver.ExcelView

package com.websystique.springmvc.viewresolver;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.servlet.view.document.AbstractExcelView;
 
import com.websystique.springmvc.model.Pizza;
 
public class ExcelView extends AbstractExcelView {
 
    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
 
        Pizza pizza = (Pizza) model.get("pizza");
 
        Sheet sheet = workbook.createSheet("sheet 1");
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.index);
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        Row row = null;
        Cell cell = null;
        int rowCount = 0;
        int colCount = 0;
 
        // Create header cells
        row = sheet.createRow(rowCount++);
 
        cell = row.createCell(colCount++);
        cell.setCellStyle(style);
        cell.setCellValue("Name");
 
        cell = row.createCell(colCount++);
        cell.setCellStyle(style);
        cell.setCellValue("Flavor");
 
        cell = row.createCell(colCount++);
        cell.setCellStyle(style);
        cell.setCellValue("Toppings");
 
        // Create data cells
        row = sheet.createRow(rowCount++);
        colCount = 0;
        row.createCell(colCount++).setCellValue(pizza.getName());
        row.createCell(colCount++).setCellValue(pizza.getFlavor());
 
        StringBuffer toppings = new StringBuffer("");
        for (String topping : pizza.getToppings()) {
            toppings.append(topping);
            toppings.append(" ");
        }
        row.createCell(colCount++).setCellValue(toppings.toString());
 
        for (int i = 0; i < 3; i++)
            sheet.autoSizeColumn(i, true);
 
    }
 
}

com.websystique.springmvc.viewresolver.ExcelViewResolver

package com.websystique.springmvc.viewresolver;
import java.util.Locale;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
public class ExcelViewResolver implements ViewResolver{
    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        ExcelView view = new ExcelView();
        return view;
      }
    
}

That is all needed for ContentNegotaingViewResolver configuration.

To complete the example and make it runnable, let’s add the missing Spring MVC configuration peaces.

Step 5: Create Controller class

Below is a trivial REST based controller for our example.

com.websystique.springmvc.controller.AppController

package com.websystique.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.websystique.springmvc.model.Pizza;
@Controller
public class AppController {
    @RequestMapping(value="/pizzavalley/{pizzaName}", method = RequestMethod.GET)
    public String getPizza(@PathVariable String pizzaName, ModelMap model) {
 
        Pizza pizza = new Pizza(pizzaName);
        model.addAttribute("pizza", pizza);
 
        return "pizza";
 
    }
    
}

Step 6: Create Initialization Class

Add an initializer class implementing WebApplicationInitializer as shown below(which in this case acts as replacement of any spring configuration defined in web.xml). During Servlet 3.0 Container startup, this class will be loaded and instantiated and its onStartup method will be called by servlet container.

com.websystique.springmvc.configuration.AppInitializer

package com.websystique.springmvc.configuration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class AppInitializer implements WebApplicationInitializer {
    public void onStartup(ServletContext container) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(AppConfig.class);
        ctx.setServletContext(container);
        ServletRegistration.Dynamic servlet = container.addServlet(
                "dispatcher", new DispatcherServlet(ctx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

Step 7: Build and Deploy the application

Now build the war (via eclipse or maven [ mvn clean install]). Deploy the war to a Servlet 3.0 container. Since here i am using Tomcat, i will simply put this war file into tomcat webapps folder and click on start.bat inside tomcat bin directory.

Run it.Below are the snapshot of sample run triggering deffernt outputs (notice URL extensions)

That’s it.

Download Source Code

FROM HERE

spring config custom httpMessageConverter

in spring 4.1.2, the GsonHttpMessageConverter is added so that we could use it to replace the jackson converter for json serialization and deserialization.

To added it, we could config our own RequestMappingHandlerAdapter and add the gson one to the “messageConverters” field. Also we would have to add bean validator for the RequestMappingHandlerAdapter. By doing this, i got several validation error while loading spring context when i start my Tomcat saying type mismatch. The mismatch happens in those xml configed setter for java properties like “velocityProperties” for “VelocityEngineFactoryBean”

	&lt;bean id=&quot;myVelocityEngine&quot;
		class=&quot;org.springframework.ui.velocity.VelocityEngineFactoryBean&quot;&gt;
		&lt;property name=&quot;velocityProperties&quot;&gt;
			&lt;value&gt;
				resource.loader = string
				string.resource.loader.class = org.apache.velocity.runtime.resource.loader.StringResourceLoader
			&lt;/value&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

It complains that the content of “velocityProperties” does not match the java properties. I then change to use the “props -> prop” pattern in xml and also fails. Of course i can avoid this buy config it in the java code.

However The easiest way i found it to added it thru the mvc:annotation-driven.

   &lt;mvc:annotation-driven&gt;
      &lt;mvc:message-converters&gt;
         &lt;bean class=&quot;myOrg.ui.server.controller.converter.ExtendedGsonHttpMessageConverter&quot;/&gt;
      &lt;/mvc:message-converters&gt;
   &lt;/mvc:annotation-driven&gt;

This way we use the namespace-> mvc:annotation-driven to create the HandlerMapping and HandlerAdapter for us. Also we could pass in the desired converter thru the mvc:message-converters.

If you prefer java based config. reference here. We could leverage the ‘WebMvcConfigurerAdapter’ and override the ‘configureMessageConverters()’ to add the GsonHttpMessageConverter.

Here i use the ExtendedGsonHttpMessageConverter because i need it to be able to properly handle my Date format to de/serialize Date.

public class ExtendedGsonHttpMessageConverter extends GsonHttpMessageConverter
{
    protected static final String DATE_FORMAT = &quot;yyyy-MM-dd&quot;;

    public ExtendedGsonHttpMessageConverter()
    {
        super();
        super.setGson(buildGson());
    }
    protected static Gson buildGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        /**
         * set the time format so that new Date Adapters will be created and added to handle 3 Date types: Date, sqlDate and TimpeStamp.
         * These adapters will be at the front of the default adapters so that date will be handled by them.
         */
        gsonBuilder.setDateFormat(DATE_FORMAT);
        return gsonBuilder.create();
    }
}

More Detail here

Angular’s $scope event system $emit, $broadcast and $on

Angular’s $emit, $broadcast and $on fall under the common “publish/subscribe” design pattern, or can do, in which you’d publish an event and subscribe/unsubscribe to it somewhere else. The Angular event system is brilliant, it makes things flawless and easy to do (as you’d expect!) but the concept behind it isn’t so simple to master and you can often be left wondering why things don’t work as you thought they might.

For those who are new to Angular and haven’t used or seen $emit, $broadcast or $on, let’s clarify what they do before we look at $scope and $rootScope event and scope relationships and how to utilise the event system correctly – as well as understand what’s really going on.

$scope.$emit up, $scope.$broadcast down

Using $scope.$emit will fire an event up the $scope. Using $scope.$broadcast will fire an event downthe $scope. Using $scope.$on is how we listen for these events. A quick example:

 

// firing an event upwards
$scope.$emit('myCustomEvent', 'Data to send');

// firing an event downwards
$scope.$broadcast('myCustomEvent', {
  someProp: 'Sending you an Object!' // send whatever you want
});

// listen for the event in the relevant $scope
$scope.$on('myCustomEvent', function (event, data) {
  console.log(data); // 'Data to send'
});

google spreadsheet api json xml html

It is not that straight forward to get the xml/json/html outpt for  a google spreadsheet. 

 

HTML

First thing we need to do is to publish the sheet under File -> publish to the web….

Here is what you may get
https://docs.google.com/spreadsheets/d/YOUR-SHEET_ID/pubhtml

Now you have the html version. 

XML/JSON 

After you get the shee-id, what you need to do is to find the grid id of the sheet use: 

https://spreadsheets.google.com/feeds/worksheets/YOUR-SHEET_ID/public/basic

After open the above URL, we get a summary of the published sheet. Then we can find the grid id under the entry element:

<id>https://spreadsheets.google.com/feeds/worksheets/YOUR-SHEET_ID/public/basic/GRID-ID</id>

Now using the combination of  GRID-ID and YOUR-SHEET_ID, we should be able to get the xml/json output by:

XML —->   http://spreadsheets.google.com/feeds/list/YOUR-SHEET_ID/GRID-ID/public/values

JOSN —->  http://spreadsheets.google.com/feeds/list/YOUR-SHEET_ID/GRID-ID/public/values?alt=json-in-script

parse json file in android from asset

1. The JSON Structure

I am taking an example of following JSON which will give you list of employees and each employee will have details like id, name, city, gender, age etc.

{
"employee": [
{
"id": 101,
"name": "Amar",
"city": "Dausa",
"gender": "M",
"age": 21
},
{
"id": 102,
"name": "Sunil",
"city": "Bharatpur",
"gender": "M",
"age": 22
},
{
"id": 103,
"name": "Uday",
"city": "Bharatpur",
"gender": "M",
"age": 22
},

{
"id": 104,
"name": "Rahul",
"city": "Alwar",
"gender": "M",
"age": 21
}
]
}

Consider that above JSON data is stored in jsondata.txt file which is stored in assetsfolder.

2. Reading Text File (from assets folder)

Before we start parsing the above JSON data, first we need to store data from jsondata.txtfile to a string. Here is the code snippet-

// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsondata.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}

String myjsonstring = sb.toString();

 3. Parsing JSON data from String


In second step we store JSON data from jsondata.txt file to a string called myjsonstring, Now we are ready to parse JSON data from it. Here is the code snippet-

// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);

// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");

// JSONArray has four JSONObject
for (int i = 0; i &lt; jsonArray.length(); i++) {

// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);

// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String city = jsonObj.getString("city");
String gender = jsonObj.getString("gender");
int age = jsonObj.getInt("id");

}

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

FROM HERE