com.flickr4java.flickr.FlickrException Java Examples

The following examples show how to use com.flickr4java.flickr.FlickrException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FlickrPhotosImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String uploadPhoto(PhotoModel photo, UUID jobId) throws IOException, FlickrException {
  BufferedInputStream inStream = imageStreamProvider.get(photo.getFetchableUrl());
  // TODO: do we want to keep COPY_PREFIX?  I think not
  String photoTitle =
      Strings.isNullOrEmpty(photo.getTitle()) ? "" : COPY_PREFIX + photo.getTitle();
  String photoDescription = cleanString(photo.getDescription());

  UploadMetaData uploadMetaData =
      new UploadMetaData()
          .setAsync(false)
          .setPublicFlag(false)
          .setFriendFlag(false)
          .setFamilyFlag(false)
          .setTitle(photoTitle)
          .setDescription(photoDescription);
  perUserRateLimiter.acquire();
  String uploadResult = uploader.upload(inStream, uploadMetaData);
  inStream.close();
  monitor.debug(() -> String.format("%s: Flickr importer uploading photo: %s", jobId, photo));
  return uploadResult;
}
 
Example #2
Source File: FlickrPhotosExporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public ExportResult<PhotosContainerResource> export(
    UUID jobId, AuthData authData, Optional<ExportInformation> exportInformation) {
  Auth auth;
  try {
    auth = FlickrUtils.getAuth(authData, flickr);
  } catch (FlickrException e) {
    return new ExportResult<>(e);
  }

  RequestContext.getRequestContext().setAuth(auth);

  PaginationData paginationData =
      exportInformation.isPresent() ? exportInformation.get().getPaginationData() : null;
  IdOnlyContainerResource resource =
      exportInformation.isPresent()
          ? (IdOnlyContainerResource) exportInformation.get().getContainerResource()
          : null;
  if (resource != null) {
    return getPhotos(resource, paginationData);
  } else {
    return getAlbums(paginationData, auth);
  }
}
 
Example #3
Source File: FlickrUtils.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
public static Auth getAuth(AuthData authData, Flickr flickr) throws FlickrException {
  checkArgument(
      authData instanceof TokenSecretAuthData,
      "authData expected to be TokenSecretAuthData not %s",
      authData.getClass().getCanonicalName());
  TokenSecretAuthData tokenAuthData = (TokenSecretAuthData) authData;
  Token requestToken = new Token(tokenAuthData.getToken(), tokenAuthData.getSecret());
  return flickr.getAuthInterface().checkToken(requestToken);
}
 
Example #4
Source File: FlickrPhotosExporter.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private ExportResult<PhotosContainerResource> getPhotos(
    IdOnlyContainerResource resource, PaginationData paginationData) {
  String photoSetId = resource.getId();
  int page = paginationData == null ? 1 : ((IntPaginationToken) paginationData).getStart();
  PhotoList<Photo> photoSetList;

  try {
    if (photoSetId == null) {
      RequestContext.getRequestContext().setExtras(EXTRAS);
      perUserRateLimiter.acquire();
      photoSetList = photosInterface.getNotInSet(PHOTO_PER_PAGE, page);
      RequestContext.getRequestContext().setExtras(ImmutableList.of());
    } else {
      perUserRateLimiter.acquire();
      photoSetList =
          photosetsInterface.getPhotos(
              photoSetId, ImmutableSet.copyOf(EXTRAS), 0, PHOTO_PER_PAGE, page);
    }
  } catch (FlickrException e) {
    return new ExportResult<>(e);
  }

  boolean hasMore = photoSetList.getPage() != photoSetList.getPages() && !photoSetList.isEmpty();

  Collection<PhotoModel> photos =
      photoSetList.stream().map(p -> toCommonPhoto(p, photoSetId)).collect(Collectors.toList());

  PaginationData newPage = null;
  if (hasMore) {
    newPage = new IntPaginationToken(page + 1);
  }

  // Get result type
  ResultType resultType = ResultType.CONTINUE;
  if (newPage == null) {
    resultType = ResultType.END;
  }

  PhotosContainerResource photosContainerResource = new PhotosContainerResource(null, photos);
  return new ExportResult<>(resultType, photosContainerResource, new ContinuationData(newPage));
}
 
Example #5
Source File: FlickrPhotosExporter.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private ExportResult<PhotosContainerResource> getAlbums(
    PaginationData paginationData, Auth auth) {
  ImmutableList.Builder<PhotoAlbum> albumBuilder = ImmutableList.builder();
  List<IdOnlyContainerResource> subResources = new ArrayList<>();

  int page = paginationData == null ? 1 : ((IntPaginationToken) paginationData).getStart();
  Photosets photoSetList;

  try {
    perUserRateLimiter.acquire();
    photoSetList =
        photosetsInterface.getList(
            auth.getUser().getId(), PHOTO_SETS_PER_PAGE, page, PHOTOSET_EXTRAS);
  } catch (FlickrException e) {
    return new ExportResult<>(e);
  }

  for (Photoset photoSet : photoSetList.getPhotosets()) {
    // Saving data to the album allows the target service to recreate the album structure
    albumBuilder.add(
        new PhotoAlbum(photoSet.getId(), photoSet.getTitle(), photoSet.getDescription()));
    // Adding subresources tells the framework to recall export to get all the photos
    subResources.add(new IdOnlyContainerResource(photoSet.getId()));
  }

  PaginationData newPage = null;
  boolean hasMore =
      photoSetList.getPage() != photoSetList.getPages() && !photoSetList.getPhotosets().isEmpty();
  if (hasMore) {
    newPage = new IntPaginationToken(page + 1);
  }

  PhotosContainerResource photosContainerResource =
      new PhotosContainerResource(albumBuilder.build(), null);
  ContinuationData continuationData = new ContinuationData(newPage);
  subResources.forEach(resource -> continuationData.addContainerResource(resource));

  // Get result type
  ResultType resultType = ResultType.CONTINUE;
  if (newPage == null) {
    resultType = ResultType.END;
  }

  return new ExportResult<>(resultType, photosContainerResource, continuationData);
}
 
Example #6
Source File: FlickrPhotosImporterTest.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
@Test
public void importStoresAlbumInJobStore() throws FlickrException, Exception {
  UUID jobId = UUID.randomUUID();

  PhotosContainerResource photosContainerResource =
      new PhotosContainerResource(
          Collections.singletonList(PHOTO_ALBUM), Collections.singletonList(PHOTO_MODEL));

  // Setup Mock
  when(user.getId()).thenReturn("userId");
  when(authInterface.checkToken(any(Token.class))).thenReturn(auth);

  when(flickr.getPhotosetsInterface()).thenReturn(photosetsInterface);
  when(flickr.getUploader()).thenReturn(uploader);
  when(flickr.getAuthInterface()).thenReturn(authInterface);
  when(imageStreamProvider.get(FETCHABLE_URL)).thenReturn(bufferedInputStream);
  when(uploader.upload(any(BufferedInputStream.class), any(UploadMetaData.class)))
      .thenReturn(FLICKR_PHOTO_ID);

  String flickrAlbumTitle = FlickrPhotosImporter.COPY_PREFIX + ALBUM_NAME;
  Photoset photoset =
      FlickrTestUtils.initializePhotoset(FLICKR_ALBUM_ID, ALBUM_DESCRIPTION, FLICKR_PHOTO_ID);
  when(photosetsInterface.create(flickrAlbumTitle, ALBUM_DESCRIPTION, FLICKR_PHOTO_ID))
      .thenReturn(photoset);

  // Run test
  FlickrPhotosImporter importer =
      new FlickrPhotosImporter(
          flickr,
          jobStore,
          imageStreamProvider,
          monitor,
          TransferServiceConfig.getDefaultInstance());
  ImportResult result =
      importer.importItem(
          jobId, EXECUTOR, new TokenSecretAuthData("token", "secret"), photosContainerResource);

  // Verify that the image stream provider got the correct URL and that the correct info was
  // uploaded
  verify(imageStreamProvider).get(FETCHABLE_URL);
  ArgumentCaptor<UploadMetaData> uploadMetaDataArgumentCaptor =
      ArgumentCaptor.forClass(UploadMetaData.class);
  verify(uploader).upload(eq(bufferedInputStream), uploadMetaDataArgumentCaptor.capture());
  UploadMetaData actualUploadMetaData = uploadMetaDataArgumentCaptor.getValue();
  assertThat(actualUploadMetaData.getTitle())
      .isEqualTo(FlickrPhotosImporter.COPY_PREFIX + PHOTO_TITLE);
  assertThat(actualUploadMetaData.getDescription()).isEqualTo(PHOTO_DESCRIPTION);

  // Verify the photosets interface got the command to create the correct album
  verify(photosetsInterface).create(flickrAlbumTitle, ALBUM_DESCRIPTION, FLICKR_PHOTO_ID);

  assertThat((String) EXECUTOR.getCachedValue(ALBUM_ID)).isEqualTo(FLICKR_ALBUM_ID);
}
 
Example #7
Source File: FlickrPhotosExporterTest.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
@Test
public void exportAlbumInitial() throws FlickrException {
  // set up auth, flickr service
  when(user.getId()).thenReturn("userId");
  when(authInterface.checkToken(any(Token.class))).thenReturn(auth);
  when(flickr.getPhotosetsInterface()).thenReturn(photosetsInterface);
  when(flickr.getPhotosInterface()).thenReturn(photosInterface);
  when(flickr.getAuthInterface()).thenReturn(authInterface);

  // setup photoset
  Photoset photoset = FlickrTestUtils.initializePhotoset("photosetId", "title", "description");

  // setup photoset list (aka album view)
  int page = 1;
  Photosets photosetsList = new Photosets();
  photosetsList.setPage(page);
  photosetsList.setPages(page + 1);
  photosetsList.setPhotosets(Collections.singletonList(photoset));
  when(photosetsInterface.getList(anyString(), anyInt(), anyInt(), anyString()))
      .thenReturn(photosetsList);

  // run test
  FlickrPhotosExporter exporter =
      new FlickrPhotosExporter(flickr, TransferServiceConfig.getDefaultInstance());
  AuthData authData = new TokenSecretAuthData("token", "secret");
  ExportResult<PhotosContainerResource> result =
      exporter.export(UUID.randomUUID(), authData, Optional.empty());

  // make sure album and photo information is correct
  assertThat(result.getExportedData().getPhotos()).isEmpty();
  Collection<PhotoAlbum> albums = result.getExportedData().getAlbums();
  assertThat(albums.size()).isEqualTo(1);
  assertThat(albums).containsExactly(new PhotoAlbum("photosetId", "title", "description"));

  // check continuation information
  ContinuationData continuationData = (ContinuationData) result.getContinuationData();
  assertThat(continuationData.getPaginationData()).isInstanceOf(IntPaginationToken.class);
  assertThat(((IntPaginationToken) continuationData.getPaginationData()).getStart())
      .isEqualTo(page + 1);

  Collection<? extends ContainerResource> subResources = continuationData.getContainerResources();
  assertThat(subResources.size()).isEqualTo(1);
  assertThat(subResources).containsExactly(new IdOnlyContainerResource("photosetId"));
}
 
Example #8
Source File: FlickrPhotosExporterTest.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
@Test
public void exportPhotosFromPhotoset() throws FlickrException {
  // set up auth, flickr service
  when(user.getId()).thenReturn("userId");
  when(authInterface.checkToken(any(Token.class))).thenReturn(auth);
  when(flickr.getPhotosetsInterface()).thenReturn(photosetsInterface);
  when(flickr.getPhotosInterface()).thenReturn(photosInterface);
  when(flickr.getAuthInterface()).thenReturn(authInterface);

  // getting photos from a set with id photosetsId and page 1
  int page = 1;
  String photosetsId = "photosetsId";
  ExportInformation exportInformation =
      new ExportInformation(null, new IdOnlyContainerResource(photosetsId));

  // make lots of photos and add them to PhotoList (also adding pagination information)
  int numPhotos = 4;
  PhotoList<Photo> photosList = new PhotoList<>();
  for (int i = 0; i < numPhotos; i++) {
    photosList.add(
        FlickrTestUtils.initializePhoto("title" + 1, "url" + i, "description" + i, MEDIA_TYPE));
  }
  photosList.setPage(page);
  photosList.setPages(page + 1);

  when(photosetsInterface.getPhotos(anyString(), anySet(), anyInt(), anyInt(), anyInt()))
      .thenReturn(photosList);

  // run test
  FlickrPhotosExporter exporter =
      new FlickrPhotosExporter(flickr, TransferServiceConfig.getDefaultInstance());
  ExportResult<PhotosContainerResource> result =
      exporter.export(
          UUID.randomUUID(),
          new TokenSecretAuthData("token", "secret"),
          Optional.of(exportInformation));
  assertThat(result.getExportedData().getPhotos().size()).isEqualTo(numPhotos);
  assertThat(result.getExportedData().getAlbums()).isEmpty();

  ContinuationData continuationData = (ContinuationData) result.getContinuationData();
  assertThat(continuationData.getContainerResources()).isEmpty();
  assertThat(((IntPaginationToken) continuationData.getPaginationData()).getStart())
      .isEqualTo(page + 1);
}
 
Example #9
Source File: FindPicture.java    From Java-for-Data-Science with MIT License 4 votes vote down vote up
public FindPicture() {
    try {
        String apikey = "Your API key";
        String secret = "Your secret";

        Flickr flickr = new Flickr(apikey, secret, new REST());

        SearchParameters searchParameters = new SearchParameters();
        searchParameters.setBBox("-180", "-90", "180", "90");
        searchParameters.setMedia("photos");
        PhotoList<Photo> list = flickr.getPhotosInterface().search(searchParameters, 10, 0);

        out.println("Image List");
        for (int i = 0; i < list.size(); i++) {
            Photo photo = list.get(i);
            out.println("Image: " + i
                    + "\nTitle: " + photo.getTitle()
                    + "\nMedia: " + photo.getOriginalFormat()
                    + "\nPublic: " + photo.isPublicFlag()
                    + "\nPublic: " + photo.isPublicFlag()
                    + "\nUrl: " + photo.getUrl()
                    + "\n");
        }
        out.println();

        PhotosInterface pi = new PhotosInterface(apikey, secret, new REST());
        out.println("pi: " + pi);
        Photo currentPhoto = list.get(0);
        out.println("currentPhoto url: " + currentPhoto.getUrl());

        // Get image using URL
        BufferedImage bufferedImage = pi.getImage(currentPhoto.getUrl());
        out.println("bi: " + bufferedImage);

        // Get image using Photo instance
        bufferedImage = pi.getImage(currentPhoto, Size.SMALL);

        // Save image to file
        out.println("bufferedImage: " + bufferedImage);
        File outputfile = new File("image.jpg");
        ImageIO.write(bufferedImage, "jpg", outputfile);
    } catch (FlickrException | IOException ex) {
        ex.printStackTrace();
    }
}