Java Code Examples for org.androidannotations.api.BackgroundExecutor#execute()

The following examples show how to use org.androidannotations.api.BackgroundExecutor#execute() . 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: Utils.java    From flickr-uploader with GNU General Public License v2.0 6 votes vote down vote up
static void validatePaypalPayment(final String paypal_result_confirmation) {
	BackgroundExecutor.execute(new Runnable() {
		@Override
		public void run() {
			if (ToolString.isNotBlank(paypal_result_confirmation) && paypalActivity != null && paypalCallback != null) {
				toast("Processing payment");
				Boolean valid = RPC.getRpcService().confirmPaypalPayment(paypal_result_confirmation);
				if (valid != null && valid) {
					onPaymentAccepted("Paypal", paypalActivity, paypalCallback);
				} else {
					paypalCallback.onResult(false);
				}
			}
			paypalCallback = null;
			paypalActivity = null;
		}
	});
}
 
Example 2
Source File: Utils.java    From flickr-uploader with GNU General Public License v2.0 6 votes vote down vote up
public static void setPremium(final boolean notifyServer, final boolean premium, final boolean purchased) {
	LOG.debug("premium : " + premium);
	setBooleanProperty(STR.premium, premium);
	if (notifyServer) {
		BackgroundExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					RPC.getRpcService().setPremium(premium, purchased, getAccountEmails());
				} catch (Throwable e) {
					LOG.error(ToolString.stack2string(e));
				}
			}
		});
	}
}
 
Example 3
Source File: UploadService.java    From flickr-uploader with GNU General Public License v2.0 6 votes vote down vote up
public static void wake(final boolean force) {
	BackgroundExecutor.execute(new Runnable() {
		@Override
		public void run() {
			if ((instance == null || instance.destroyed) && (force || Utils.canAutoUploadBool() || checkQueue() != null)) {
				Context context = FlickrUploader.getAppContext();
				context.startService(new Intent(context, UploadService.class));
				AlarmBroadcastReceiver.initAlarm();
			}
			checkForFilesToDelete();
			synchronized (mPauseLock) {
				mPauseLock.notifyAll();
			}
		}
	});
}
 
Example 4
Source File: DrawerContentView.java    From flickr-uploader with GNU General Public License v2.0 6 votes vote down vote up
public void updateLists() {
	if (activity != null && !activity.destroyed && !activity.isPaused() && activity.getSlidingDrawer() != null && activity.getSlidingDrawer().isOpened()) {
		BackgroundExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					List<Media> currentlyQueued = new ArrayList<Media>(UploadService.getCurrentlyQueued());
					Collections.sort(currentlyQueued, Utils.MEDIA_COMPARATOR);
					Collections.reverse(currentlyQueued);
					notifyDataSetChanged(queuedAdapter, currentlyQueued);
					List<Media> recentlyUploaded = new ArrayList<Media>(UploadService.getRecentlyUploaded());
					Collections.sort(recentlyUploaded, Utils.MEDIA_COMPARATOR_UPLOAD);
					notifyDataSetChanged(uploadedAdapter, recentlyUploaded);
					List<Media> failed = new ArrayList<Media>(UploadService.getFailed());
					Collections.sort(failed, Utils.MEDIA_COMPARATOR);
					notifyDataSetChanged(failedAdapter, failed);
				} catch (Throwable e) {
					LOG.error(ToolString.stack2string(e));
				}
			}
		});
	}
}
 
Example 5
Source File: PreferencesActivity.java    From flickr-uploader with GNU General Public License v2.0 6 votes vote down vote up
void loadNbSynced() {
	BackgroundExecutor.execute(new Runnable() {
		@Override
		public void run() {
			try {
				nbSynced = Utils.getFoldersMonitoredNb();
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						render();
					}
				});
			} catch (Throwable e) {
				LOG.error(ToolString.stack2string(e));
			}
		}

	});
}
 
Example 6
Source File: PreferencesAdvancedActivity.java    From flickr-uploader with GNU General Public License v2.0 6 votes vote down vote up
private void render() {
    BackgroundExecutor.execute(new Runnable() {
        @Override
        public void run() {
            final long size = FlickrUploader.getLogSize();
            final List<String> autoupload_delay_values = Arrays.asList(getResources().getStringArray(R.array.autoupload_delay_values));
            final String[] autoupload_delay_entries = getResources().getStringArray(R.array.autoupload_delay_entries);
            final String autoupload_delay_value = Utils.getStringProperty("autoupload_delay", autoupload_delay_values.get(0));
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    findPreference("clear_logs").setSummary("Files size: " + Utils.formatFileSize(size));
                    String autoupload_delay = autoupload_delay_entries[autoupload_delay_values.indexOf(autoupload_delay_value)];
                    if (autoupload_delay.equalsIgnoreCase("custom")) {
                        findPreference("autoupload_delay").setSummary(autoupload_delay);
                    } else {
                        findPreference("autoupload_delay").setSummary(autoupload_delay);
                    }
                    findPreference("upload_description").setSummary(Html.fromHtml(Utils.getUploadDescription()));
                    findPreference("custom_tags").setSummary(Utils.getStringProperty("custom_tags"));
                }
            });
        }
    });
}
 
Example 7
Source File: AccountPropertiesManagerCore.java    From moVirt with Apache License 2.0 5 votes vote down vote up
private void notifyBackgroundListeners(Set<WrappedPropertyChangedListener> backgroundListeners, Object o) {
    BackgroundExecutor.execute(new BackgroundExecutor.Task("", 0L, "") {
        @Override
        public void execute() {
            try {
                notifyListeners(backgroundListeners, o);
            } catch (final Throwable e) {
                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);
            }
        }
    });
}
 
Example 8
Source File: Utils.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
public static final void sendMail(final String subject, final String bodyHtml) {
	BackgroundExecutor.execute(new Runnable() {
		@Override
		public void run() {
			try {
				String admin = FlickrUploader.getAppContext().getString(R.string.admin_email);
				RPC.getRpcService().sendEmail(admin, subject, bodyHtml, admin);
			} catch (Throwable e) {
				LOG.error(ToolString.stack2string(e));

			}
		}
	});
}
 
Example 9
Source File: UploadService.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
public static void clear(final int status, final Callback<Void> callback) {
	if (status == STATUS.FAILED || status == STATUS.QUEUED) {
		BackgroundExecutor.execute(new Runnable() {
			@Override
			public void run() {
				int nbModified = 0;
				List<Media> medias = Utils.loadMedia(false);
				Transaction t = new Transaction();
				try {
					for (final Media media : medias) {
						if (media.getStatus() == status) {
							if (media.isQueued() && media.equals(mediaCurrentlyUploading)) {
								REST.kill(media);
							}
							media.setStatus(STATUS.PAUSED, t);
							nbModified++;
						}
					}
					t.setSuccessful(true);
				} finally {
					t.finish();
				}
				if (nbModified > 0) {
					checkQueue();
				}
				if (callback != null)
					callback.onResult(null);
			}
		});
	} else {
		LOG.error("status " + status + " is not supported");
	}
}
 
Example 10
Source File: UploadService.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
static void checkForFilesToDelete() {
	if (Utils.isAutoDelete() && System.currentTimeMillis() - lastDeleteCheck > 3600 * 1000L) {
		lastDeleteCheck = System.currentTimeMillis();
		Utils.setLongProperty("lastDeleteCheck", lastDeleteCheck);
		BackgroundExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					long firstInstallTime = FlickrUploader.getAppContext().getPackageManager().getPackageInfo(FlickrUploader.getAppContext().getPackageName(), 0).firstInstallTime;
					long yesterday = System.currentTimeMillis() - 24 * 3600 * 1000L;
					List<Media> loadMedia = Utils.loadMedia(false);
					int nbFileDeleted = 0;
					for (Media media : loadMedia) {
						if (media.isUploaded() && media.getTimestampUploaded() > firstInstallTime && media.getTimestampUploaded() < yesterday) {
							boolean stillOnFlickr = FlickrApi.isStillOnFlickr(media);
							LOG.info("poundering deletion of : " + media + " : stillOnFlickr=" + stillOnFlickr);
							if (stillOnFlickr) {
								boolean deleted = new File(media.getPath()).delete();
								LOG.warn("Deleting " + media + " " + ToolString.formatDuration(System.currentTimeMillis() - media.getTimestampUploaded()) + " after upload : deleted=" + deleted);
								media.delete();
								nbFileDeleted++;
							} else if (FlickrApi.isNetworkOk()) {
								media.setFlickrId(null);
								media.save2(null);
							}
						}
					}
					if (nbFileDeleted > 0) {
						LOG.warn(nbFileDeleted + " files deleted");
						Utils.loadMedia(true);
					}
				} catch (Throwable e) {
					LOG.error(ToolString.stack2string(e));
				}
			}
		});
	}
}
 
Example 11
Source File: DrawerHandleView.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
public void onActivityResume() {
	BackgroundExecutor.execute(new Runnable() {
		@Override
		public void run() {
			nbMonitored = Utils.getFoldersMonitoredNb();
			render();
		}
	});
}
 
Example 12
Source File: RPC.java    From flickr-uploader with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // LOG.trace("method : " + method);
    if (args == null) {
        args = new Object[0];
    }
    final String key = method.getName() + "-" + getKey(args);

    Object lock = locks.get(key);
    long start = System.currentTimeMillis();
    if (method.getReturnType() != void.class && lock != null && !responses.containsKey(key)) {
        synchronized (lock) {
            do {
                try {
                    LOG.info("###### concurrent RPC call " + method.getReturnType().getSimpleName() + " " + method.getName() + "(" + Arrays.toString(args) + ")");
                    lock.wait(2 * HTTP_CACHE_TIMEOUT);
                } catch (InterruptedException e) {
                }
            }
            while (!responses.containsKey(key) && System.currentTimeMillis() - start < HTTP_CACHE_TIMEOUT);
        }
    } else {
        lock = new Object();
        locks.put(key, lock);
    }
    try {
        Object object = null;
        String response;
        if (responses.containsKey(key)) {
            LOG.info("###### response still in cache : " + key + ", after " + ToolString.formatDuration(System.currentTimeMillis() - start));
            object = responses.get(key);
        } else {
            int retry = 0;
            while (retry < DEFAULT_MAX_RETRIES) {
                retry++;
                response = postRpc(method, args);
                if (ToolString.isBlank(response)) {
                    break;
                } else {
                    object = Streams.decode(response);
                    if (object instanceof Throwable) {
                        LOG.warn("retry:" + retry + ", server exception :" + object.getClass().getName() + "," + ((Throwable) object).getMessage());
                    } else {
                        break;
                    }
                }
            }

            if (object != null) {
                responses.put(key, object);
                BackgroundExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        responses.remove(key);
                    }
                }, HTTP_CACHE_TIMEOUT);
            }
        }
        if (object instanceof Throwable) {
            if (object instanceof StreamCorruptedException || object instanceof IOException) {
                LOG.warn(object.getClass().getSimpleName() + " on " + method.getName());
            } else {
                LOG.error("Server error calling " + method.getName(), (Throwable) object);
            }
            return null;
            // throw new Exception(throwable.getClass().getSimpleName() + " : " + throwable.getMessage());
        }
        return object;
    } finally {
        synchronized (lock) {
            lock.notifyAll();
            locks.remove(key);
        }
    }
}
 
Example 13
Source File: Notifications.java    From flickr-uploader with GNU General Public License v2.0 4 votes vote down vote up
public static void notifyProgress(final Media media) {
	try {
		if (!Utils.getBooleanProperty("notification_progress", true)) {
			return;
		}

		if (System.currentTimeMillis() - lastUpdate < 1000) {
			return;
		}

		lastUpdate = System.currentTimeMillis();

		int currentPosition = UploadService.getRecentlyUploaded().size();
		int total = UploadService.getNbTotal();
		int progress = media.getProgress();

		ensureBuilders();

		Notification.Builder builder = builderUploading;
		builder.setProgress(1000, progress, false);
		builder.setContentText(media.getName());
		builder.setContentInfo(currentPosition + " / " + total);

		CacheableBitmapDrawable bitmapDrawable = Utils.getCache().getFromMemoryCache(media.getPath() + "_" + VIEW_SIZE.small);
		if (bitmapDrawable == null || bitmapDrawable.getBitmap().isRecycled()) {
			BackgroundExecutor.execute(new Runnable() {
				@Override
				public void run() {
					final Bitmap bitmap = Utils.getBitmap(media, VIEW_SIZE.small);
					if (bitmap != null) {
						Utils.getCache().put(media.getPath() + "_" + VIEW_SIZE.small, bitmap);
					}
				}
			});
		} else {
			builder.setLargeIcon(bitmapDrawable.getBitmap());
		}

		Notification notification = builder.build();
		notification.icon = android.R.drawable.stat_sys_upload_done;
		// notification.iconLevel = progress / 10;
		manager.notify(0, notification);
	} catch (Throwable e) {
		LOG.error(ToolString.stack2string(e));
	}

}
 
Example 14
Source File: UploadService.java    From flickr-uploader with GNU General Public License v2.0 4 votes vote down vote up
public static void checkNewFiles() {
	BackgroundExecutor.execute(new Runnable() {
		@Override
		public void run() {
			try {

				final List<Media> medias;
				if (System.currentTimeMillis() - lastLoad > 5000) {
					medias = Utils.loadMedia(true);
					lastLoad = System.currentTimeMillis();
				} else {
					medias = Utils.loadMedia(false);
				}

				if (medias == null || medias.isEmpty()) {
					LOG.info("no media found");
					return;
				}

				Map<String, Folder> pathFolders = Utils.getFolders(false);
				if (pathFolders.isEmpty()) {
					LOG.info("no folder monitored");
					return;
				}

				String canAutoUpload = Utils.canAutoUpload();
				boolean autoUpload = "true".equals(canAutoUpload);

				final long uploadDelayMs = Utils.getUploadDelayMs();
				long newestFileAge = 0;
				for (Media media : medias) {
					if (media.isImported()) {
						if (!autoUpload) {
							LOG.debug("not uploading " + media + " because " + canAutoUpload);
							media.setStatus(STATUS.PAUSED);
							continue;
						} else if (media.getMediaType() == MEDIA_TYPE.PHOTO && !Utils.isAutoUpload(MEDIA_TYPE.PHOTO)) {
							LOG.debug("not uploading " + media + " because photo upload disabled");
							media.setStatus(STATUS.PAUSED);
							continue;
						} else if (media.getMediaType() == MEDIA_TYPE.VIDEO && !Utils.isAutoUpload(MEDIA_TYPE.VIDEO)) {
							LOG.debug("not uploading " + media + " because video upload disabled");
							media.setStatus(STATUS.PAUSED);
							continue;
						} else {
							File file = new File(media.getPath());
							if (file.exists()) {
								boolean uploaded = media.isUploaded();
								LOG.debug("uploaded : " + uploaded + ", " + media);
								if (!uploaded) {
									Folder folder = pathFolders.get(media.getFolderPath());
									if (folder == null || !folder.isAutoUploaded()) {
										media.setStatus(STATUS.PAUSED);
										LOG.debug("not uploading " + media + " because " + media.getFolderPath() + " is not monitored");
									} else {
										int sleep = 0;
										while (file.length() < 100 && sleep < 5) {
											LOG.debug("sleeping a bit");
											sleep++;
											Thread.sleep(1000);
										}
										long fileAge = System.currentTimeMillis() - file.lastModified();
										LOG.debug("uploadDelayMs:" + uploadDelayMs + ", fileAge:" + fileAge + ", newestFileAge:" + newestFileAge);
										if (uploadDelayMs > 0) {
											media.setTimestampRetry(System.currentTimeMillis() + uploadDelayMs);
										}
										enqueue(true, Arrays.asList(media), folder.getFlickrSetTitle());
									}
								}
							} else {
								LOG.debug("Deleted : " + file);
								media.deleteAsync();
							}
						}
					}
				}
			} catch (Throwable e) {
				LOG.error(ToolString.stack2string(e));
			}
		}
	}, "checkNewFiles", "checkNewFiles");

}