PageRenderTime 38ms CodeModel.GetById 14ms app.highlight 19ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/advanced/flickrMT/FlickrLoader.java

http://mt4j.googlecode.com/
Java | 591 lines | 242 code | 99 blank | 250 comment | 40 complexity | 062f40578fd74a762ea20b853fd46c1c MD5 | raw file
  1/***********************************************************************
  2 * mt4j Copyright (c) 2008 - 2009 C.Ruff, Fraunhofer-Gesellschaft All rights reserved.
  3 *  
  4 *   This program is free software: you can redistribute it and/or modify
  5 *   it under the terms of the GNU General Public License as published by
  6 *   the Free Software Foundation, either version 3 of the License, or
  7 *   (at your option) any later version.
  8 *
  9 *   This program is distributed in the hope that it will be useful,
 10 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *   GNU General Public License for more details.
 13 *
 14 *   You should have received a copy of the GNU General Public License
 15 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 16 *
 17 ***********************************************************************/
 18package advanced.flickrMT;
 19
 20import java.io.IOException;
 21import java.util.ArrayList;
 22import java.util.List;
 23
 24import javax.xml.parsers.ParserConfigurationException;
 25
 26import org.mt4j.components.visibleComponents.widgets.progressBar.AbstractProgressThread;
 27import org.xml.sax.SAXException;
 28
 29import processing.core.PApplet;
 30import processing.core.PImage;
 31
 32import com.aetrion.flickr.Flickr;
 33import com.aetrion.flickr.FlickrException;
 34import com.aetrion.flickr.REST;
 35import com.aetrion.flickr.RequestContext;
 36import com.aetrion.flickr.auth.AuthInterface;
 37import com.aetrion.flickr.photos.GeoData;
 38import com.aetrion.flickr.photos.Photo;
 39import com.aetrion.flickr.photos.PhotoList;
 40import com.aetrion.flickr.photos.PhotosInterface;
 41import com.aetrion.flickr.photos.SearchParameters;
 42import com.aetrion.flickr.photos.geo.GeoInterface;
 43import com.aetrion.flickr.places.Place;
 44import com.aetrion.flickr.places.PlacesInterface;
 45import com.aetrion.flickr.places.PlacesList;
 46
 47/**
 48 * The Class FlickrLoader.
 49 */
 50public class FlickrLoader extends AbstractProgressThread {
 51	/** The images. */
 52	private PImage[] images;
 53	
 54	/** The pa. */
 55	private PApplet pa;
 56	
 57	/** The use places for geo search. */
 58	private boolean usePlacesForGeoSearch;
 59	
 60//	private ImageCard mtFotos[];
 61	
 62	
 63//	private FlickrHelper flickHelper;
 64	
 65	/** The search parameters. */
 66private SearchParameters searchParameters;
 67	
 68	/** The foto count. */
 69	private int fotoCount;
 70	
 71	/** The search page offset. */
 72	private int searchPageOffset;
 73	
 74	/** The flickr key. */
 75	private String flickrKey;
 76	
 77	/** The flickr secret. */
 78	private String flickrSecret;
 79	
 80	// A Flickr object for making requests
 81	/** The f. */
 82	private Flickr f;
 83	
 84	/** The auth interface. */
 85	private AuthInterface authInterface;
 86	
 87	/** The request context. */
 88	private RequestContext requestContext;
 89	
 90	/** The photos. */
 91	private List<Photo> photos;
 92	
 93	/**
 94	 * The Constructor.
 95	 * 
 96	 * @param pa the pa
 97	 * @param flickrKey the flickr key
 98	 * @param flickrSecret the flickr secret
 99	 * @param sleepTime the sleep time
100	 */
101	public FlickrLoader(PApplet pa, String flickrKey, String flickrSecret, long sleepTime) {
102		this(pa, flickrKey, flickrSecret, new String[]{}, sleepTime);
103	}
104	
105	
106	/**
107	 * The Constructor.
108	 * 
109	 * @param pa the pa
110	 * @param flickrKey the flickr key
111	 * @param flickrSecret the flickr secret
112	 * @param photoSearchString the photo search string
113	 * @param sleepTime the sleep time
114	 */
115	public FlickrLoader(PApplet pa, String flickrKey, String flickrSecret, String photoSearchString, long sleepTime) {
116		this(pa, flickrKey, flickrSecret, new String[]{photoSearchString}, sleepTime);
117	}
118	
119	/**
120	 * The Constructor.
121	 * 
122	 * @param pa the pa
123	 * @param flickrKey the flickr key
124	 * @param flickrSecret the flickr secret
125	 * @param photoSearchString the photo search string
126	 * @param sleepTime the sleep time
127	 */
128	public FlickrLoader(PApplet pa, String flickrKey, String flickrSecret, String[] photoSearchString, long sleepTime) {
129		this(pa, flickrKey, flickrSecret, new SearchParameters(), sleepTime);
130		
131		SearchParameters sp = new SearchParameters();
132		// Simple example, just looking for a single tag
133		sp.setTags(photoSearchString);
134		this.setSearchParameters(sp);
135	}
136	
137	/**
138	 * The Constructor.
139	 * 
140	 * @param pa the pa
141	 * @param flickrKey the flickr key
142	 * @param flickrSecret the flickr secret
143	 * @param sleepTime the sleep time
144	 * @param sp the sp
145	 */
146	public FlickrLoader(PApplet pa, String flickrKey, String flickrSecret, SearchParameters sp, long sleepTime) {
147		super(sleepTime);
148		this.pa = pa;
149		
150		try {
151			f = new Flickr(flickrKey, flickrSecret, new REST());
152		} catch (ParserConfigurationException e) {
153			e.printStackTrace();
154		}
155		authInterface	= f.getAuthInterface();
156		requestContext 	= RequestContext.getRequestContext();
157		
158		this.searchParameters 	= sp;
159		this.fotoCount 			= 5;
160		this.searchPageOffset 	= 0;
161		
162		this.photos = new ArrayList<Photo>();
163		
164		this.usePlacesForGeoSearch = true;
165	}
166
167	
168	/* (non-Javadoc)
169	 * @see com.jMT.components.visibleComponents.progressBar.AbstractProgressThread#run()
170	 */
171	@Override
172	public void run() {
173		if (this.getSearchParameters() != null){
174			
175			/*
176			//Print search tags
177			System.out.print("\nSearching for flickr tags: " );
178			String[] tags = this.getSearchParameters().getTags();
179			if (tags != null){
180				for (int i = 0; i < tags.length; i++) {
181					String string = tags[i];
182					System.out.print(string + ", ");
183				}
184				System.out.println();
185			}
186			*/
187			
188			boolean isGeoSearch = this.isGeoSearch(this.getSearchParameters());
189			PhotoList fotoList = this.getSearchedFotoList(this.getSearchParameters(), this.getFotoLoadCount(), this.getSearchPageOffset(), isGeoSearch);
190			
191			if (fotoList != null && fotoList.size() > 0){
192//				System.out.println("Found " + fotoList.size() + " fotos.");
193				
194				this.setTarget(fotoList.size());
195//				mtFotos = new ImageCard[fotoList.size()];
196				
197				//Go through all found fotos
198				for (int i = 0; i < fotoList.size(); i++) {
199					
200					try {
201						Thread.sleep(this.getSleepTime()); 
202					} catch (InterruptedException e) {
203						e.printStackTrace();
204						//pa.unregisterPre(this);
205						this.setFinished(true);
206						break;
207					}
208					
209					Photo foto = (Photo) fotoList.get(i);
210					String fotoName = foto.getTitle();
211					
212					/*
213					if (foto.hasGeoData()){
214						System.out.println("Foto: " + fotoName + " has geodata.");
215						System.out.println(fotoName + "-> Lat:" + foto.getGeoData().getLatitude() + " Lon:" + foto.getGeoData().getLongitude() + " PlaceID: " + foto.getPlaceId());
216					}
217					*/
218					
219					this.setCurrentAction("Loading: " + fotoName);
220					
221					this.processFoto(foto);
222
223					this.setCurrent(i+1);
224				}
225			}else{
226				System.err.println("Foto list returned null or list is empty!");
227				//Fire event that all loaded
228				this.setFinished(true);
229			}
230		}//if sp != null
231		else{
232			System.err.println("No search parameters for flickr search specified!");
233			//Fire event that all loaded
234			this.setFinished(true);
235		}
236//		this.setFinished(true);
237	}
238	
239	
240	/**
241	 * This method gets called in the loading thread of the fotos. This
242	 * method can be overridden and used to process the newly loaded foto in different ways.
243	 * 
244	 * @param foto the foto
245	 */
246	protected void processFoto(Photo foto){
247	}
248
249	
250	/**
251	 * Searches fotos on flickr with the specified searchparameters.
252	 * 
253	 * @param sp the sp
254	 * @param n number of fotos to search for
255	 * @param startPage offset of the result pages to start from
256	 * @param isGeoSearch the is geo search
257	 * 
258	 * @return the searched foto list
259	 * 
260	 * the list of found fotos
261	 */
262	public PhotoList getSearchedFotoList(SearchParameters sp, int n, int startPage, boolean isGeoSearch) {
263		PhotoList photoList = null;
264		//Interface with Flickr photos
265		PhotosInterface photoInterface = f.getPhotosInterface();
266		
267		try {
268			//TODO was kann man damit machen?
269			//GeoInterface g = photos.getGeoInterface();
270			//search results for exact location, display on map
271			
272			/*
273			//Search in a location bounding box
274			sp.setBBox(
275					"16.3680536232", "48.2057162608", 
276					"16.3760536232", "48.2111162608");
277			sp.setAccuracy(1);
278			sp.setHasGeo(true);
279			*/
280			
281			//Search in a location with a radius
282			/*
283			sp.setLatitude("48.7771056");
284			sp.setLongitude("9.1807688");
285			sp.setRadius(5);
286			sp.setRadiusUnits("km");
287			sp.setHasGeo(true);
288			sp.setAccuracy(Flickr.ACCURACY_REGION);
289			*/
290			
291			
292//			/*
293			//Instead of taking the location, search for a nearby flickr "place"
294			if (isGeoSearch && sp.getLongitude() != null && sp.getLatitude() != null
295				&& usePlacesForGeoSearch
296			){
297				//TODO TEST DISABLE FIXME
298				//Search for places at a location
299				PlacesInterface p = f.getPlacesInterface();
300				PlacesList placesList = null;
301//				placesList = p.findByLatLon(48.7771056f, 	9.1807688f, 14);
302//				placesList = p.findByLatLon(40.689, -74.044, 12); //liberty islang
303				placesList = p.findByLatLon(Double.parseDouble(sp.getLatitude()), Double.parseDouble(sp.getLongitude()), sp.getAccuracy());
304
305				sp.setLatitude(null);
306				sp.setLongitude(null);
307				
308				System.out.println("Places found: " + placesList.size());
309                for (Object aPlacesList : placesList) {
310                    Place place = (Place) aPlacesList;
311                    String placeID = place.getPlaceId();
312                    //System.out.println("Place ID: " + placeID);
313
314                    sp.setPlaceId(placeID);
315                    sp.setWoeId(place.getWoeId());
316
317//					Location placeResolved = p.resolvePlaceURL(place.getPlaceUrl());
318//					System.out.println("Place: " + placeResolved);
319
320//					sp.setBBox(
321//					48.5129f, 2.1740f, 
322//					48.5130f, 2.1741f);
323                }
324			}
325//			else if (isGeoSearch && sp.getLongitude() != null && sp.getLatitude() != null
326//					&& !usePlacesForGeoSearch){
327//				
328//			}
329//			*/
330			
331			//We're looking for n images, starting at "page" startPage
332			//PhotoList 
333			photoList = photoInterface.search(sp, n, startPage);
334			
335			//Check if no fotos were found and search again with reduced accurracy
336			if (isGeoSearch
337				&&	photoList 		!= null
338				){
339				System.out.println("Found " + photoList.size() + " fotos.");
340				
341				if (photoList.size() <= 0){
342					System.out.println("Found no fotos, reducing accuracy and trying again.");
343					int a = sp.getAccuracy();
344					
345					for (int i = 1; i < 6; i++) {
346						a--;
347						if (a < 1){
348							a++;
349							break;
350						}
351					}
352					
353					System.out.println("Using new accuracy: " + a);
354					sp.setAccuracy(a);
355					photoList = photoInterface.search(sp, n, startPage);
356					if (photoList != null)
357						System.out.println("Found " + photoList.size() + " fotos.");
358				}
359			}
360			
361			if (isGeoSearch){
362				//System.out.println("Trying to attach geo information:");
363				if (photoList != null){
364					GeoInterface g = photoInterface.getGeoInterface();
365					
366					//Nullpointer error - bug in flickj library,
367					//photosForLocation return aber evtl nur eigene fotos!
368//					PhotoList fot = g.photosForLocation(new GeoData( new Float(48.7771056f).toString(), new Float(9.1807688f).toString(), new Integer(1).toString()), null, 5, 0);
369//					System.out.println("photosForLocation (location = stutgart mitte) returned fotos: " +  fot.size());
370					
371					//Go through all found fotos
372                    for (Object aPhotoList : photoList) {
373                        Photo foto = (Photo) aPhotoList;
374                        //Add to result list
375                        photos.add(foto);
376
377                        String id = foto.getId();
378                        try {
379                            GeoData loc = g.getLocation(id);
380                            if (loc != null) {
381                                foto.setGeoData(loc);
382                            }
383                        } catch (Exception e) {
384                            System.err.println("Error fetching geodata for foto");
385                            e.printStackTrace();
386                        }
387                    }
388				}
389			}else{
390				//Add to result list
391				if (photoList != null){
392                    for (Object aPhotoList : photoList) {
393                        photos.add((Photo) aPhotoList);
394                    }
395				}
396			}
397			
398			//Geht nur mit eigenen fotos!?
399//			photos.getWithGeoData(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
400
401			return photoList;
402		} catch (IOException e) {
403			e.printStackTrace();
404		} catch (SAXException e) {
405			e.printStackTrace();
406		} catch (FlickrException e) {
407			e.printStackTrace();
408		}
409		return photoList;
410	}
411	
412	
413	/**
414	 * Checks if is geo search.
415	 * 
416	 * @param sp the sp
417	 * 
418	 * @return true, if is geo search
419	 */
420	private boolean isGeoSearch(SearchParameters sp){
421		return
422		(
423			   (sp.getLatitude() != null //TODO is it null when not set?
424			&&	!sp.getLatitude().equalsIgnoreCase(""))
425			||
426				(sp.getLongitude() != null
427			&& 	!sp.getLongitude().equalsIgnoreCase(""))
428			||
429				(sp.getBBox() != null
430			&&	 sp.getBBox().length > 0)
431			||
432			(sp.getWoeId() != null
433			&& 	!sp.getWoeId().equalsIgnoreCase(""))
434			||
435			(sp.getPlaceId() != null
436			&& 	!sp.getPlaceId().equalsIgnoreCase(""))
437			|| sp.getRadius() != -1
438		);
439	}
440	
441	/**
442	 * Gets the foto urls.
443	 * 
444	 * @param list the list
445	 * 
446	 * @return the foto urls
447	 */
448	private String[] getFotoUrls(PhotoList list){
449		//Grab all the image paths and store in String array
450		String[] smallURLs = new String[list.size()];
451		for (int i = 0; i < list.size(); i++) {
452			Photo p = (Photo) list.get(i);
453//			smallURLs[i] = p.getSmallUrl();
454//			smallURLs[i] = p.getUrl();
455			smallURLs[i] = p.getMediumUrl();
456		}
457		return smallURLs;
458	}
459	
460	
461	
462	/**
463	 * Gets the foto load count.
464	 * 
465	 * @return the foto load count
466	 */
467	public int getFotoLoadCount() {
468		return fotoCount;
469	}
470	
471	/**
472	 * Sets the foto load count.
473	 * 
474	 * @param fotosCount the new foto load count
475	 */
476	public void setFotoLoadCount(int fotosCount) {
477		this.fotoCount = fotosCount;
478	}
479
480	
481	/**
482	 * Gets the search parameters.
483	 * 
484	 * @return the search parameters
485	 */
486	public SearchParameters getSearchParameters() {
487		return searchParameters;
488	}
489	
490	/**
491	 * Sets the search parameters.
492	 * 
493	 * @param searchParameters the new search parameters
494	 */
495	public void setSearchParameters(SearchParameters searchParameters) {
496		this.searchParameters = searchParameters;
497	}
498	
499	
500	/**
501	 * Gets the search page offset.
502	 * 
503	 * @return the search page offset
504	 */
505	private int getSearchPageOffset() {
506		return this.searchPageOffset;
507	}
508	
509	/**
510	 * Sets the search page offset.
511	 * 
512	 * @param searchPageOffset the new search page offset
513	 */
514	public void setSearchPageOffset(int searchPageOffset) {
515		this.searchPageOffset = searchPageOffset;
516	}
517
518	
519	/**
520	 * Gets the flickr key.
521	 * 
522	 * @return the flickr key
523	 */
524	public String getFlickrKey() {
525		return flickrKey;
526	}
527	
528	/**
529	 * Sets the flickr key.
530	 * 
531	 * @param flickrKey the new flickr key
532	 */
533	public void setFlickrKey(String flickrKey) {
534		this.flickrKey = flickrKey;
535	}
536
537
538	/**
539	 * Gets the flickr secret.
540	 * 
541	 * @return the flickr secret
542	 */
543	public String getFlickrSecret() {
544		return flickrSecret;
545	}
546	
547	/**
548	 * Sets the flickr secret.
549	 * 
550	 * @param flickrSecret the new flickr secret
551	 */
552	public void setFlickrSecret(String flickrSecret) {
553		this.flickrSecret = flickrSecret;
554	}
555	
556
557	/**
558	 * Gets the photos.
559	 * 
560	 * @return the photos
561	 */
562	public Photo[] getPhotos() {
563		return this.photos.toArray(new Photo[this.photos.size()]);
564	}
565
566
567	/**
568	 * Checks if is use places for geo search.
569	 * 
570	 * @return true, if is use places for geo search
571	 */
572	public boolean isUsePlacesForGeoSearch() {
573		return usePlacesForGeoSearch;
574	}
575
576
577	/**
578	 * Uses flickr "places" for the geo search
579	 * 
580	 * @param usePlacesForGeoSearch the new use places for geo search
581	 */
582	public void setUsePlacesForGeoSearch(boolean usePlacesForGeoSearch) {
583		this.usePlacesForGeoSearch = usePlacesForGeoSearch;
584	}
585	
586
587	
588
589
590
591}