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

Install Oracle JDK in Fedora 18

1. Download JDK from oracle

2. Install it as root:

[root@fc18]# rpm -i jdk-7u17-linux-x64.rpm

3. Define the alternatives

[root@fc18]# alternatives --install /usr/bin/java java /usr/java/jdk1.7.0_17/bin/java 2
[root@fc18]# alternatives --install /usr/bin/javac javac /usr/java/jdk1.7.0_17/bin/javac 2
[root@fc18]# alternatives --install /usr/bin/jar jar /usr/java/jdk1.7.0_17/bin/jar 2
[root@fc18]# alternatives --install /usr/bin/javaws javaws /usr/java/jdk1.7.0_17/bin/javaws 2

4. Configure the alternatives for java

[root@fc18]# alternatives --config java

There are 2 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
*  1           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
 + 2           /usr/java/jdk1.7.0_17/bin/java
Enter to keep the current selection[+], or type selection number:

Enter 2, the jdk from oracle.

5. Repeat for all the alternatives:

[root@fc18]# alternatives --config javac
[root@fc18]# alternatives --config jar
[root@fc18]# alternatives --config javaws

Java plugin for Chrome:

1. Create the directory /opt/google/chrome/plugins

[root@fc18]# mkdir /opt/google/chrome/plugins

2. In /opt/google/chrome/plugins create the following soft links:

[root@fc18]# ln -s /usr/java/jdk1.7.0_17/jre/lib/amd64/libnpjp2.so 
[root@fc18]# ln -s /usr/java/jdk1.7.0_17/jre/lib/amd64/libjavaplugin_jni.so

3. Check the plugin appears in your chrome by entering the following url: chrome://plugins/

4. Test if your plugin is working by clicking on: http://www.java.com/en/download/testjava.jsp