ru.develgame.jflickrorganizer.Threads.BackupRunnable.java Source code

Java tutorial

Introduction

Here is the source code for ru.develgame.jflickrorganizer.Threads.BackupRunnable.java

Source

/* This Source Code Form is subject to the terms of the Mozilla
 * Public License, v. 2.0. If a copy of the MPL was not distributed
 * with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 * 
 * Copyright 2017 Ilya Zemskov */

package ru.develgame.jflickrorganizer.Threads;

import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.RequestContext;
import com.flickr4java.flickr.photos.Photo;
import com.flickr4java.flickr.photos.PhotosInterface;
import com.flickr4java.flickr.photos.Size;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import ru.develgame.jflickrorganizer.Common.Authorizer;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import ru.develgame.jflickrorganizer.Common.Status;
import ru.develgame.jflickrorganizer.Common.LocaleMessages;
import ru.develgame.jflickrorganizer.DataModel.VisibilityFilter;
import ru.develgame.jflickrorganizer.repositories.PhotoRepository;

/**
 *
 * @author Ilya Zemskov
 */
@Component
@Scope("prototype")
public class BackupRunnable extends ProgressBarRunnableImpl {
    @Autowired
    private Authorizer authorizer;

    @Autowired
    private PhotoRepository photoRepository;

    private final List<Photo> photos;
    private final File backupFolder;

    // check Pro account
    private boolean isCheckedProAccount = false;
    private boolean isProAccount = false;

    public static String THUMBS_FOLDER = "thumbs";

    public BackupRunnable(List<Photo> photos, File backupFolder) {
        this.photos = photos;
        this.backupFolder = backupFolder;
    }

    int sizesForBackup[] = { Size.LARGE_2048, Size.LARGE_1600, Size.LARGE, Size.MEDIUM_800, Size.MEDIUM_640,
            Size.MEDIUM, Size.SMALL };

    private void downloadPhoto(File newFile, Size size, PhotosInterface photoInt)
            throws FileNotFoundException, IOException, FlickrException {
        if (!newFile.exists()) {
            BufferedInputStream inStream = new BufferedInputStream(photoInt.getImageAsStream(size));

            FileOutputStream fos = new FileOutputStream(newFile);

            byte buffer[] = IOUtils.toByteArray(inStream);
            fos.write(buffer);

            fos.flush();
            fos.close();
            inStream.close();
        }
    }

    @Override
    public void run() {
        if (photos == null) {
            status = Status.STATUS_FAIL;
            errors.append(LocaleMessages.getMessage("BackupRunnable.Error.PhotoListNull"));
            completed();
            return;
        }

        if (backupFolder == null) {
            status = Status.STATUS_FAIL;
            errors.append(LocaleMessages.getMessage("BackupRunnable.Error.BackupFolderNull"));
            completed();
            return;
        }

        if (!backupFolder.exists()) {
            status = Status.STATUS_FAIL;
            errors.append(LocaleMessages.getMessage("BackupRunnable.Error.BackupFolderNotExists"));
            completed();
            return;
        }

        synchronized (authorizer) {
            RequestContext rc = RequestContext.getRequestContext();
            rc.setAuth(authorizer.getAuth());

            PhotosInterface photoInt = authorizer.getFlickr().getPhotosInterface();

            File thumbs = new File(backupFolder, THUMBS_FOLDER);
            if (!thumbs.exists()) {
                if (!thumbs.mkdirs()) {
                    status = Status.STATUS_FAIL;
                    errors.append(LocaleMessages.getMessage("BackupRunnable.Error.BackupFolderNotExists"));
                    completed();
                    return;
                }
            }

            int i = 0;
            for (Photo e : photos) {
                if (isCancel()) {
                    status = Status.STATUS_CANCELED;
                    break;
                }

                try {
                    String photoName = e.getId() + "." + e.getOriginalFormat();

                    ru.develgame.jflickrorganizer.entities.Photo dbPhoto = photoRepository.findByFid(e.getId());
                    if (dbPhoto == null) {
                        dbPhoto = new ru.develgame.jflickrorganizer.entities.Photo(e.getId(), authorizer.getUser());
                    }

                    savePhotoDataToDB(e, dbPhoto, photoName);

                    if (!isCheckedProAccount)
                        checkProAccount(e, photoInt);

                    Collection<Size> sizes = photoInt.getSizes(e.getId());
                    if (sizes.isEmpty()) {
                        errors.append(LocaleMessages.getMessage("BackupRunnable.Error.GetPhotoSize", e.getId()));
                        status = Status.STATUS_FAIL;
                        break;
                    }

                    Size selectedPrefSize = getSelectedPrefSize(sizes);
                    if (selectedPrefSize == null) {
                        errors.append(
                                LocaleMessages.getMessage("BackupRunnable.Error.GetPreferredSize", e.getId()));
                        status = Status.STATUS_FAIL;
                        break;
                    }

                    File newFile = new File(backupFolder, photoName);
                    downloadPhoto(newFile, selectedPrefSize, photoInt);

                    selectedPrefSize = null;
                    for (Size size : sizes) {
                        if (size.getLabel() == Size.SQUARE_LARGE) {
                            selectedPrefSize = size;
                            break;
                        }
                    }

                    if (selectedPrefSize != null) {
                        newFile = new File(thumbs, photoName);
                        downloadPhoto(newFile, selectedPrefSize, photoInt);
                    }

                    photoRepository.save(dbPhoto);
                } catch (FlickrException ex) {
                    errors.append(ex.getMessage());
                    status = Status.STATUS_FAIL;
                    break;
                } catch (IOException ex) {
                    errors.append(ex.getMessage());
                    status = Status.STATUS_FAIL;
                    break;
                }

                i++;

                setProgress(i * 100 / photos.size());
            }

            completed();
        }
    }

    private void savePhotoDataToDB(Photo e, ru.develgame.jflickrorganizer.entities.Photo dbPhoto,
            String photoName) {
        if (e.getDescription() != null)
            dbPhoto.setDescription(e.getDescription());
        else
            dbPhoto.setDescription("");

        if (e.getTitle() != null)
            dbPhoto.setTitle(e.getTitle());
        else
            dbPhoto.setTitle("");

        dbPhoto.setViews(e.getViews());

        if (e.isPublicFlag())
            dbPhoto.setVisibility(VisibilityFilter.VISIBILITY_PUBLIC);
        else
            dbPhoto.setVisibility(VisibilityFilter.VISIBILITY_PRIVATE);

        dbPhoto.setFileName(photoName);

        if (e.getDateTaken() != null)
            dbPhoto.setDateTaken(e.getDateTaken());
        else
            dbPhoto.setDateTaken(new Date());

        if (e.getDatePosted() != null)
            dbPhoto.setDateUploaded(e.getDatePosted());
        else
            dbPhoto.setDateUploaded(new Date());
    }

    private Size getSelectedPrefSize(Collection<Size> sizes) {
        Size selectedPrefSize = null;

        if (isProAccount) {
            for (Size size : sizes) {
                if (size.getLabel() == Size.ORIGINAL)
                    return size;
            }
        }

        for (int sizeForBackup : sizesForBackup) {
            for (Size size : sizes) {
                if (size.getLabel() == sizeForBackup) {
                    selectedPrefSize = size;
                    break;
                }
            }

            if (selectedPrefSize != null)
                break;
        }

        return selectedPrefSize;
    }

    private void checkProAccount(Photo e, PhotosInterface photoInt) throws FlickrException {
        Collection<Size> sizes = photoInt.getSizes(e.getId());
        if (sizes.isEmpty()) {
            return;
        }

        Size selectedPrefSize = null;
        for (Size size : sizes) {
            if (size.getLabel() == Size.ORIGINAL) {
                selectedPrefSize = size;
                break;
            }
        }

        if (selectedPrefSize == null)
            return;

        try {
            BufferedInputStream inStream = new BufferedInputStream(photoInt.getImageAsStream(selectedPrefSize));
            isProAccount = true;
        } catch (FlickrException ex) {
            isCheckedProAccount = false;
        }

        isCheckedProAccount = true;
    }
}