@SuppressWarnings("rawtypes")
public SwingWorker getFavoriteThoughts(final ThoughtLoadable thoughtLoadable) {
SwingWorker<ThoughtList, Void> swingWorker = new SwingWorker<ThoughtList, Void>() {
@Override
public ThoughtList doInBackground() throws NotRegisteredException, IOException{
ThoughtList thoughtList = new ThoughtList();
if (webServiceREST.isUserRegistered()){
// get list of favorite thought IDs for current registered user
ListLong favoriteIDs = webServiceREST.getUserFavoriteIDs();
// compare cached thoughts with received thought ids
Set<Long> notFavoriteThoughtsLeft = new HashSet<Long>(cachedFavoriteThought.getMap().keySet());
List<Long> favoriteThoughtsLeft = new ArrayList<Long>();
for(Long id : favoriteIDs.getList()){
if(!cachedFavoriteThought.getMap().containsKey(id)){
favoriteThoughtsLeft.add(id);
}
notFavoriteThoughtsLeft.remove(id);
}
//remove thoughts, that are not favorite
for (Long id:notFavoriteThoughtsLeft){
cachedFavoriteThought.getMap().remove(id);
}
//request from server favorite thoughts, that are left in saved favorite thoughts
if (favoriteThoughtsLeft.size()!=0){
ThoughtList fetchedThoughts = webServiceREST.getThoughtsByIDs(favoriteThoughtsLeft);
for (Thought thought:fetchedThoughts.getThoughtsList()){
cachedFavoriteThought.getMap().put(thought.getID(), thought);
}
}
cachedFavoriteThought.saveToFile();
//now favorite thoughts is synchronized with server
//copy them to list, that will be returned
for (Thought thought:cachedFavoriteThought.getMap().values()){
thoughtList.getThoughtsList().add(thought);
}
} else {
throw new NotRegisteredException();
}
return thoughtList;
}
@Override
public void done() {
try {
ThoughtList favoriteThoughts = get();
thoughtLoadable.completeLoadingThoughts(Status.OK, favoriteThoughts.getThoughtsList(), null);
} catch (InterruptedException ignore) {
} catch (CancellationException ignore){
} catch (ExecutionException e) {
if (e.getCause() != null){
if (e.getCause().getClass() == UniformInterfaceException.class){