1 package org.springframework.security.oauth.examples.tonr.impl;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.net.URI;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 import javax.xml.parsers.ParserConfigurationException;
11 import javax.xml.parsers.SAXParser;
12 import javax.xml.parsers.SAXParserFactory;
13
14 import org.springframework.security.oauth.consumer.client.OAuthRestTemplate;
15 import org.springframework.security.oauth.examples.tonr.GoogleService;
16 import org.xml.sax.Attributes;
17 import org.xml.sax.SAXException;
18 import org.xml.sax.helpers.DefaultHandler;
19
20
21
22
23 public class GoogleServiceImpl implements GoogleService {
24
25 private OAuthRestTemplate googleRestTemplate;
26
27 public List<String> getLastTenPicasaPictureURLs() {
28
29 byte[] bytes = getGoogleRestTemplate().getForObject(URI.create("https://picasaweb.google.com/data/feed/api/user/default?kind=photo&max-results=10"), byte[].class);
30 InputStream photosXML = new ByteArrayInputStream(bytes);
31 final List<String> photoUrls = new ArrayList<String>();
32 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
33 parserFactory.setValidating(false);
34 parserFactory.setXIncludeAware(false);
35 parserFactory.setNamespaceAware(true);
36 try {
37 SAXParser parser = parserFactory.newSAXParser();
38 parser.parse(photosXML, new DefaultHandler() {
39 @Override
40 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
41 if ("http://search.yahoo.com/mrss/".equals(uri)
42 && "thumbnail".equalsIgnoreCase(localName)) {
43 int width = 0;
44 try {
45 width = Integer.parseInt(attributes.getValue("width"));
46 if (width > 100 && width < 200) {
47
48 photoUrls.add(attributes.getValue("url"));
49 }
50 }
51 catch (NumberFormatException e) {
52
53 }
54 }
55 }
56 });
57 return photoUrls;
58 }
59 catch (ParserConfigurationException e) {
60 throw new IllegalStateException(e);
61 }
62 catch (SAXException e) {
63 throw new IllegalStateException(e);
64 }
65 catch (IOException e) {
66 throw new IllegalStateException(e);
67 }
68 }
69
70 public OAuthRestTemplate getGoogleRestTemplate() {
71 return googleRestTemplate;
72 }
73
74 public void setGoogleRestTemplate(OAuthRestTemplate googleRestTemplate) {
75 this.googleRestTemplate = googleRestTemplate;
76 }
77 }