/** * @author Hyacinthe MENIET * Created on 26 août 07 */ package net.dotmyself.restclient.flickrphotos; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.text.MessageFormat; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; /** * A class designed to wrap the Flickr Photos Web Services. */ public class PhotoMapper { private static final String baseUrl = "http://www.flickr.com/services/rest/"; private static final String appId = "your_own_code"; //replace with your own code private static final String method = "flickr.photos.search"; private static final String urlEncoding = "ISO-8859-1"; /** * Retrieves photographs by tags. * @param tags * Small blocks of text attached to a photograph to identify its content. * @return list of {@link Photo} or null if * no {@link Photo} could be found. * @throws UnsupportedEncodingException * @throws MalformedURLException * @throws JAXBException */ public static List getPhotos(String tags) throws UnsupportedEncodingException, MalformedURLException, JAXBException { StringBuilder sb = new StringBuilder(baseUrl); sb.append("?api_key="); sb.append(URLEncoder.encode(appId, urlEncoding)); sb.append("&method="); sb.append(URLEncoder.encode(method, urlEncoding)); if(tags != null && tags.length() > 1) { sb.append("&tags="); sb.append(URLEncoder.encode(tags, urlEncoding)); } Photos ps = extractPhotos(new URL(sb.toString())); return (ps != null) ? ps.getPhoto() : null; } /** * Uses the JAXB classes to process the returned XML * and returns the corresponding {@link Photos} * @param url * The URL for the query. * @return * {@link Photos} or null if * no {@link Photos} could be found. * @throws JAXBException */ private static Photos extractPhotos(URL url) throws JAXBException { JAXBContext context = JAXBContext.newInstance(Rsp.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Rsp rsp = (Rsp) unmarshaller.unmarshal(url); return (rsp != null) ? rsp.getPhotos() : null; } /** * Creates the photographs thumbnail URL. * @param photo * The {@link Photo} * @return * The thumbnail URL. * @throws UnsupportedEncodingException */ public static String buildThumbnailUrl(Photo photo) throws UnsupportedEncodingException { if(photo == null) { throw new NullPointerException("You should provide a valid Photo in order to ask to thumbnail URL"); } String url = MessageFormat.format("http://farm{0}.static.flickr.com/{1}/{2}_{3}_t.jpg", new Object[] { URLEncoder.encode(photo.getFarm().toString(), urlEncoding), URLEncoder.encode(photo.getServer().toString(), urlEncoding), URLEncoder.encode(photo.getId().toString(), urlEncoding), URLEncoder.encode(photo.getSecret().toString(), urlEncoding) }); return url; } }