📄 flickrservice.java
字号:
/**
*
*/
package com.ftrd.flickr.service;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import org.xml.sax.SAXException;
import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.people.User;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.Size;
import com.aetrion.flickr.photosets.Photoset;
import com.aetrion.flickr.photosets.Photosets;
import com.aetrion.flickr.photosets.PhotosetsInterface;
import com.aetrion.flickr.uploader.UploadMetaData;
import com.aetrion.flickr.uploader.Uploader;
import com.aetrion.flickr.util.AuthStore;
import com.aetrion.flickr.util.FileAuthStore;
import com.ftrd.Service;
/**
* This POJO implements the service that delivers photos from <a
* href="http://www.flickr.com">Flicr</a>. Implementation is based on the <a
* href="http://www.flickr.com/services/api/">Flickr API</a>, abstracted by the
* <a href="http://sourceforge.net/projects/flickrj">flickrj</a> library.
*
* @author <a href="mailto:tuyun1984@gmail.com">Daniel Tu</a>
* @since 2008-10-6
*/
public class FlickrService implements Service {
private Flickr flickr;
private REST Rest;
private AuthStore authStore = null;
/**
* Flag set to determine if we have a valid connection to Flickr
*/
private boolean Connected = false;
public FlickrService(){
// Connect to flickr
try {
Connect();
} catch (Exception ex) {
System.out.println("Can not connect to flickr!");
ex.printStackTrace();
}
}
/**
* connect to flickr by flickr_api_key and secret.
* operate CONNECT_RETRY times, else connect errot.
*
* @throws Exception
*/
private void Connect() throws Exception {
// Try to connect at most 'CONNECT_RETRY' times before throwing an
// exception
Exception latestEx = null;
for (int i = 0; !Connected && i < ConflickrConstants.CONNECT_RETRY; i++){
try {
// Initialize
Rest = new REST();
Rest.setHost(ConflickrConstants.HOST);
System.out.println("connecting...........");
flickr = new Flickr(ConflickrConstants.FLICKR_API_KEY,
ConflickrConstants.FLICKR_SECRET, Rest);
System.out.println("print the flickr obj: " + flickr.getApiKey() + ", "
+ flickr.getSharedSecret() + ", " + flickr.toString());
Connected = true;
} catch (Exception ex) {
latestEx = ex;
}
}
System.out.println("Connected...............");
if (!Connected)
throw latestEx;
}
public static void main(String args[]){
System.out.println("New Flickrservice.................");
FlickrService fs = new FlickrService();
try {
User user = fs.flickr.getPeopleInterface().findByEmail(ConflickrConstants.DEFAULT_USERNAME);
System.out.println("### " + user.getId());
fs.getTotalPhotosCount(ConflickrConstants.USERID);
fs.downloadPhoto("2921340940");
System.out.println("Downloaded.................");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* authorize whether user has the permission to write, used in upload.
*
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
private void authorize() throws IOException, SAXException, FlickrException {
AuthInterface authInterface = flickr.getAuthInterface();
String frob = "";
try {
frob = authInterface.getFrob();
} catch (FlickrException e) {
e.printStackTrace();
}
System.out.println("frob: " + frob);
// grant the write permission by user at the first time
URL authUrl = this.flickr.getAuthInterface().buildAuthenticationUrl( Permission.READ, frob);
System.out.println("Please visit: " + authUrl.toExternalForm() + " then, hit enter.");
System.in.read();
try {
Auth auth = authInterface.getToken(frob);
RequestContext.getRequestContext().setAuth(auth);
// store the auth permission to local
this.authStore.store(auth);
System.out.println("Authentication success");
// This token can be used until the user revokes it.
System.out.println("Token: " + auth.getToken());
System.out.println("nsid: " + auth.getUser().getId());
System.out.println("Realname: " + auth.getUser().getRealName());
System.out.println("Username: " + auth.getUser().getUsername());
System.out.println("Permission: " + auth.getPermission());
} catch (FlickrException e) {
System.out.println("Authentication failed");
e.printStackTrace();
}
}
/**
* get total photo count by userid
*
* @param userId
* @return
* @throws Exception
*/
public int getTotalPhotosCount(String userId) throws Exception {
int count = 0;
try {
User user = flickr.getPeopleInterface().getInfo(userId);
System.out.println("username: " + user.getUsername());
System.out.println("userID: " + user.getId());
count = user.getPhotosCount();
} catch (Exception e) {
System.out.println("The flickr email is wrong!");
e.printStackTrace();
}
return count;
}
/**
* list all photosets by userid
*
* @param userid
*/
public void listUsersPhotosets(String userid) {
PhotosetsInterface setiface = flickr.getPhotosetsInterface();
try {
Photosets photosets = setiface.getList(userid);
Collection sets = photosets.getPhotosets();
Iterator it = sets.iterator();
while (it.hasNext()) {
Photoset pset = (Photoset) it.next();
System.out.print(pset.getId() + " - ");
System.out.println(pset.getTitle());
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (FlickrException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
}
}
public void addAlbum(String album_id) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.ftrd.Service#uploadPhoto(java.lang.String, java.lang.String)
*/
public void uploadPhoto(String album_id, String filename) throws Exception {
FileInputStream photo = null;
try {
photo = new FileInputStream(filename);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
RequestContext rc = RequestContext.getRequestContext();
// Check if local exist the auth file
this.authStore = new FileAuthStore(new File("D:\\flickrtest\\"));
if (this.authStore != null) {
Auth auth = this.authStore.retrieve(ConflickrConstants.USERID);
if (auth == null)
this.authorize();
else
rc.setAuth(auth);
}
Uploader flickrUploader = new Uploader(flickr.getApiKey(), flickr
.getSharedSecret());
String photo_Id = flickrUploader
.upload(photo, new UploadMetaData());
flickr.getPhotosetsInterface().addPhoto(album_id, photo_Id);
} catch (IOException e) {
System.out.println("check the filename.");
e.printStackTrace();
} catch (FlickrException e) {
System.out.println("upload photo to flickr error.");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("can not get photo_id of the photo uploaded.");
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see com.ftrd.Service#addTags(java.lang.String, java.lang.String)
*/
public void addTags(String photo_id, String tag) throws Exception {
// split the tag by breakspace
String[] tags = tag.split(" ");
try {
flickr.getPhotosInterface().addTags(photo_id, tags);
} catch (IOException e) {
System.out.println("check the tag.");
e.printStackTrace();
} catch (FlickrException e) {
System.out.println("add tag to photo error.");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("can not add tag to photo.");
e.printStackTrace();
}
}
public void connect(String username, String password, String apiKey)
throws Exception {
// Try to connect at most 'CONNECT_RETRY' times before throwing an
// exception
Exception latestEx = null;
for (int i = 0; !Connected && i < ConflickrConstants.CONNECT_RETRY; i++)
try {
// Initialize
Rest = new REST();
Rest.setHost(ConflickrConstants.HOST);
flickr = new Flickr(apiKey);
Connected = true;
} catch (Exception ex) {
latestEx = ex;
}
if (!Connected)
throw latestEx;
}
public void deleteAlbum(String album_id) throws Exception {
try {
flickr.getPhotosetsInterface().delete(album_id);
} catch (IOException e) {
System.out.println("check the album_id.");
e.printStackTrace();
} catch (FlickrException e) {
System.out.println("delete photoset error.");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("can not delete photoset.");
e.printStackTrace();
}
}
public void deletePhoto(String album_id, String photo_id) {
try {
flickr.getPhotosInterface().delete(photo_id);
} catch (IOException e) {
System.out.println("check the photo_id.");
e.printStackTrace();
} catch (FlickrException e) {
System.out.println("delete photo error.");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("can not delete photo.");
e.printStackTrace();
}
}
public void download(String album_id, String photo_id) {
// TODO Auto-generated method stub
}
public int downloadAlbum(String album_id) {
// TODO Auto-generated method stub
return 0;
}
public void downloadContentsInAlbum(String album_id) {
// TODO Auto-generated method stub
}
public Object getAlbum(String album_id) throws Exception {
PhotosetsInterface photosetsInter = flickr.getPhotosetsInterface();
Photoset photoset = photosetsInter.getInfo(album_id);
// TODO Auto-generated method stub
return photoset;
}
public List getAlbumTags(String album_id) {
// TODO Auto-generated method stub
return null;
}
public Object getPhoto(String album_id, String photo_id) throws Exception {
Photo photo = null;
try {
photo = flickr.getPhotosInterface().getPhoto(photo_id);
} catch (IOException e) {
System.out.println("check the photo_id.");
e.printStackTrace();
} catch (FlickrException e) {
System.out.println("get photo error.");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("can not get photo.");
e.printStackTrace();
}
return photo;
}
public List getPhotoComments(String photo_id) {
List<String> comments = new ArrayList<String>();
try {
comments = (ArrayList<String>)flickr.getPhotosetsCommentsInterface().getList(photo_id);
} catch (IOException e) {
System.out.println("check the photo_id.");
e.printStackTrace();
} catch (FlickrException e) {
System.out.println("get photo comments error.");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("can not get photo comments.");
e.printStackTrace();
}
return comments;
}
public List getPhotoTags(String photo_id) {
Photo photo = null;
List<String> tags = new ArrayList<String>();
try {
photo = flickr.getPhotosInterface().getPhoto(photo_id);
tags = (ArrayList<String>)photo.getTags();
} catch (IOException e) {
System.out.println("check the photo_id.");
e.printStackTrace();
} catch (FlickrException e) {
System.out.println("get photo tags error.");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("can not get photo tags.");
e.printStackTrace();
}
return tags;
}
/* (non-Javadoc)
* @see com.ftrd.Service#getPhotots(java.lang.String)
*/
public List getPhotots(String album_id) throws Exception {
List<Photo> photosList = new ArrayList<Photo>();
PhotosetsInterface setsInterface = flickr.getPhotosetsInterface();
try {
Collection photos = setsInterface.getPhotos(album_id, 0, 0);
Iterator it = photos.iterator();
while (it.hasNext()) {
Photo photo = (Photo) it.next();
photosList.add(photo);
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (FlickrException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
}
return photosList;
}
public void modifyAlbum(String album_id) {
// TODO Auto-generated method stub
}
public void removeTags(String photo_id, String tag) throws Exception {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.ftrd.Service#saveToFile(java.lang.Object, java.lang.String)
*/
public void saveToFile(Object object, String author) {
// TODO Auto-generated method stub
Photo photo = (Photo) object;
String title = photo.getTitle();
try {
BufferedImage bufImage = flickr.getPhotosInterface().getImage(
photo, Size.MEDIUM);
ImageIO.write(bufImage, "jpg", new File("D:\\flickrtest\\" + title
+ ".jpg"));
} catch (IOException ioe) {
// TODO: handle exception
} catch (FlickrException fce) {
// TODO: handle exception
}
}
/**
* download the plickr photo and save it to local
*
* @param photo_id
* @throws Exception
*/
public void downloadPhoto(String photo_id) throws Exception {
Photo photo = flickr.getPhotosInterface().getPhoto(photo_id);
saveToFile(photo, "");
System.out.println("download successful!");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -