View Javadoc

1   package org.springframework.security.oauth.examples.tonr.mvc;
2   
3   import java.awt.image.BufferedImage;
4   import java.io.InputStream;
5   import java.util.Iterator;
6   
7   import javax.imageio.ImageIO;
8   import javax.imageio.ImageReadParam;
9   import javax.imageio.ImageReader;
10  import javax.imageio.stream.MemoryCacheImageInputStream;
11  import javax.servlet.UnavailableException;
12  
13  import org.springframework.http.HttpHeaders;
14  import org.springframework.http.HttpStatus;
15  import org.springframework.http.MediaType;
16  import org.springframework.http.ResponseEntity;
17  import org.springframework.http.converter.HttpMessageNotReadableException;
18  import org.springframework.security.oauth.examples.tonr.SparklrService;
19  import org.springframework.stereotype.Controller;
20  import org.springframework.ui.Model;
21  import org.springframework.web.bind.annotation.PathVariable;
22  import org.springframework.web.bind.annotation.RequestMapping;
23  
24  /**
25   * @author Ryan Heaton
26   * @author Dave Syer
27   */
28  @Controller
29  public class SparklrRedirectController {
30  
31  	private SparklrService sparklrService;
32  
33  	@RequestMapping("/sparklr/redirect")
34  	public String photos(Model model) throws Exception {
35  		model.addAttribute("photoIds", sparklrService.getSparklrPhotoIds());
36  		model.addAttribute("path", "redirect");
37  		return "sparklr";
38  	}
39  
40  	@RequestMapping("/sparklr/trigger")
41  	public String trigger(Model model) throws Exception {
42  		return photos(model);
43  	}
44  
45  	@RequestMapping("/sparklr/redirect/{id}")
46  	public ResponseEntity<BufferedImage> photo(@PathVariable String id) throws Exception {
47  		InputStream photo = sparklrService.loadSparklrPhoto(id);
48  		if (photo == null) {
49  			throw new UnavailableException("The requested photo does not exist");
50  		}
51  		BufferedImage body;
52  		MediaType contentType = MediaType.IMAGE_JPEG;
53  		Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
54  		if (imageReaders.hasNext()) {
55  			ImageReader imageReader = imageReaders.next();
56  			ImageReadParam irp = imageReader.getDefaultReadParam();
57  			imageReader.setInput(new MemoryCacheImageInputStream(photo), true);
58  			body = imageReader.read(0, irp);
59  		} else {
60  			throw new HttpMessageNotReadableException("Could not find javax.imageio.ImageReader for Content-Type ["
61  					+ contentType + "]");
62  		}
63  		HttpHeaders headers = new HttpHeaders();
64  		headers.setContentType(MediaType.IMAGE_JPEG);
65  		return new ResponseEntity<BufferedImage>(body, headers, HttpStatus.OK);
66  	}
67  
68  	public void setSparklrService(SparklrService sparklrService) {
69  		this.sparklrService = sparklrService;
70  	}
71  
72  }