JGiven with Spring

In a previous post we talked about how to create a basic Spring MVC web with junit for test driven development (TDD). Here we are going to include behavior driven development (BDD). To accomplish this goal we will use the JGiven library.

Continue reading

Advertisements

How to use cookies with spring

Writting a cookie

You can make the browser to save a cookie by adding it to the response like is shown in this snipplet:

@RequestMapping("/general")
@Controller
public class GeneralController {	
    @RequestMapping(value = "/mycookie/{type}", produces = "text/html")
    public String changeType(@PathVariable("type") String type, 
                             Model uiModel,
                             HttpServletResponse response){
    	Cookie c=new Cookie("mode", type);  
   	c.setPath("/");
    	response.addCookie(c);
    	return "redirect:/";
    }        
}

The property c.setPath(“/”); is done because we want that cookie valid over the whole web domain.

Reading from a controller

If you want to read the value of a cookie from a controller you can use the @CookieValue annotation:

public @ResponseBody String fileuploader(@PathVariable("fileid") String id, 
    HttpServletRequest request,
    HttpServletResponse response,
    @CookieValue("mode") String cookieMode) 
    throws IOException{    	    	                       
[...]
    		if (!"expectedCookieValue".equals(cookieMode)){
		    //Do something
    		}
[...]
}

In this case the String variable cookieMode will have the content of the cookie mode, if that cookie is not present its value will be null

Reading from JSTL

It is also possible to read the cookie from JSTL and change the view accordingly. Here is an example of how to do it:

<c:if test="${cookie.mode.value!='expectedCookieValue'}">
   <p> The cookie has the expected Value</p>
</c:if>

Create a JPEG dynamically in JAVA with Spring

The problem:

I have a JAVA Spring web application running in a Tomcat and I want to display in a web page a jpeg created dynamically from the content of a double[][] java array.

The solution:

First we create a method which creates a BufferedImage object from a double[][] array where our data will be stored. We pass as arguments the width and height in pixels.

public static BufferedImage generate(double[][] data, int pixelsWidth, int pixelsHeight ) throws Exception{

        double x =0,y = 0;
        BufferedImage bi = new BufferedImage( pixelsWidth, pixelsHeight,  BufferedImage.TYPE_3BYTE_BGR );
        Graphics2D g=(Graphics2D)bi.getGraphics();

        int w=data[0].length;
        int l=data.length;
        double Dy=(double)pixelsHeight/(double)l;
        double Dx=(double)pixelsWidth/(double)w;
        int height = (int)Math.ceil(Dy);
        int width = (int)Math.ceil(Dx);	
        int gap=(int)Math.ceil(width/4);

    	double max=-Double.MAX_VALUE;
    	for (int i=0;i<l;i++){
    		for (int j=0;jmax) max=data[i][j];    	
    		}
    	}    	
        int norm=(int)(Integer.MAX_VALUE/max);

        g.setColor( Color.WHITE);
        g.fillRect( 0, 0 , pixelsWidth,pixelsHeight); 
        for( int i =0; i < l; i++ ){        	
            for( int j =0; j < w; j++ ){            	
               g.setColor( new Color((int)data[i][j]*norm));                
               g.fillRect( (int)x, (int)y , width-gap,height);        
               x+=Dx;
            }
            y+=Dy;
            x=0;
        }
        g.dispose();

        return bi;
}

Now we need to create a method inside a Spring controller which will listen for the HTTP petitions for the JPEG image. This method will call the previous generate method for converting the double[][] array into a BufferedImage object and will redirect to the HTTP output stream.

@RequestMapping(value = "/image/{id}", method=RequestMethod.GET)
public ResponseEntity matrixMinPlus(@PathVariable("id") Long id,@RequestParam(value="width", required = false) Integer width, @RequestParam(value="height", required = false) Integer height){
    	DataMatrix dataMatrix = DataMatrix.findDataMatrix(id);		
	try {
		if (width==null) width=100;
		if (height==null) height=100;

		BufferedImage img=ArrayUtils.generate(dataMatrix.getRawData(),width,height);
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		ImageIO.write(img, "jpg", baos );
		byte[] imageInByte=baos.toByteArray();

		final HttpHeaders headers = new HttpHeaders();
		headers.setContentType(new MediaType("image","jpeg"));			
		return new ResponseEntity(imageInByte, headers, HttpStatus.CREATED);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

Now all the HTTP request that will go to the relative URL defined by /image/{id} where {id} is an identifier of our desired DataMatrix object will receive as response a JPEG.

The final jpeg image can be something like this:

Matrix without predefined colormap