com.appspot.socialinquirer.server.service.impl.UserServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.appspot.socialinquirer.server.service.impl.UserServiceImpl.java

Source

/*
 * Copyright 2012 Nabeel Mukhtar 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 */
package com.appspot.socialinquirer.server.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import javax.persistence.EntityManager;

import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.http.AccessToken;
import twitter4j.http.Authorization;
import twitter4j.http.OAuthAuthorization;

import com.appspot.socialinquirer.server.constant.ApplicationConstants;
import com.appspot.socialinquirer.server.dao.DataAccessObject;
import com.appspot.socialinquirer.server.dao.NamedQueries;
import com.appspot.socialinquirer.server.model.Quote;
import com.appspot.socialinquirer.server.model.User;
import com.appspot.socialinquirer.server.model.Version;
import com.appspot.socialinquirer.server.model.XmppSettings;
import com.appspot.socialinquirer.server.service.ServiceException;
import com.appspot.socialinquirer.server.service.ServiceFactory;
import com.appspot.socialinquirer.server.service.StackExchangeService;
import com.appspot.socialinquirer.server.service.UserService;
import com.appspot.socialinquirer.server.service.mapper.Mapper;
import com.appspot.socialinquirer.shared.dto.Message;
import com.appspot.socialinquirer.shared.dto.Page;
import com.appspot.socialinquirer.shared.dto.Poll;
import com.appspot.socialinquirer.shared.dto.Question;
import com.appspot.socialinquirer.shared.dto.Quiz;
import com.appspot.socialinquirer.shared.dto.Tag;
import com.appspot.socialinquirer.shared.dto.Task;
import com.google.appengine.api.datastore.Text;

/**
 * The Class UserServiceImpl.
 */
public class UserServiceImpl extends BaseService implements UserService {

    /**
     * Instantiates a new user service impl.
     */
    public UserServiceImpl() {
        super("user-service");
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.bitlyminous.service.UserService#getUserByScreenName(java.
     * lang.String)
     */
    public com.appspot.socialinquirer.shared.dto.User getUserByStackExchangeId(String stackExchangeId) {
        Mapper<com.appspot.socialinquirer.shared.dto.User, User> mapper = MAPPER_FACTORY
                .createMapper(com.appspot.socialinquirer.shared.dto.User.class, User.class);
        EntityManager entityManager = createEntityManager();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                populateUser(user);
            }
            return mapper.from(user);
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.bitlyminous.service.UserService#getSimilarUsers(com.appspot
     * .bitlyminous.entity.User, int)
     */
    public List<com.appspot.socialinquirer.shared.dto.User> getSimilarUsers(
            com.appspot.socialinquirer.shared.dto.User user, int count) {
        EntityManager entityManager = createEntityManager();
        Mapper<com.appspot.socialinquirer.shared.dto.User, User> mapper = MAPPER_FACTORY
                .createMapper(com.appspot.socialinquirer.shared.dto.User.class, User.class);
        try {
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("user", mapper.to(user));
            return mapList(getDao(entityManager).getResultList(User.class, NamedQueries.FIND_SIMILAR_USERS,
                    parameters, count));
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.bitlyminous.service.UserService#getSimilarUsers(com.appspot
     * .bitlyminous.entity.User, int)
     */
    public List<com.appspot.socialinquirer.shared.dto.User> getAllAuthenticatedUsers() {
        EntityManager entityManager = createEntityManager();
        try {
            return mapList(getDao(entityManager).getResultList(User.class, NamedQueries.FIND_AUTHENTICATED_USERS));
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.appspot.bitlyminous.service.UserService#updateUser(com.appspot.
     * bitlyminous.entity.User)
     */
    public void updateUser(com.appspot.socialinquirer.shared.dto.User user) {
        EntityManager entityManager = createEntityManager();
        try {
            if (user.getKey() == null) {
                getDao(entityManager).saveOrUpdate(user);
            } else {
                getDao(entityManager).merge(user);
            }
            // memcache.delete(user.getEvernoteId());
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.appspot.everscribe.server.service.UserService#aggregateQuotes()
     */
    @Override
    public void aggregateQuotes() {
        EntityManager entityManager = createEntityManager();
        try {
            DataAccessObject dao = getDao(entityManager);
            Version version = getCurrentVersion();
            Twitter twitter = getTwitterClient();
            List<Status> homeTimeline = twitter.getUserTimeline(ApplicationConstants.TWITTER_SCREEN_NAME,
                    new Paging(version.getLastHomeTweetId()));
            long lastTweetId = 0L;
            for (Status status : homeTimeline) {
                if (status.getId() > lastTweetId) {
                    lastTweetId = status.getId();
                }
                if (!status.isRetweet() && status.getInReplyToStatusId() == -1) {
                    Quote quote = new Quote();
                    quote.setPublishedDate(status.getCreatedAt());
                    quote.setText(new Text(status.getText()));
                    quote.setTweetId(status.getId());
                    dao.saveOrUpdate(quote);
                }
            }
            if (lastTweetId > version.getLastHomeTweetId()) {
                version.setLastHomeTweetId(lastTweetId);
                dao.saveOrUpdate(version);
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /**
     * Gets the twitter client.
     *
     * @return the twitter client
     */
    protected Twitter getTwitterClient() {
        return new TwitterFactory().getInstance(getAuthorization());
    }

    /**
     * Gets the authorization.
     *
     * @return the authorization
     */
    protected Authorization getAuthorization() {
        return getAuthorization(ApplicationConstants.TWITTER_ACCESS_TOKEN,
                ApplicationConstants.TWITTER_ACCESS_TOKEN_SECRET);
    }

    /**
     * Gets the authorization.
     *
     * @param token the token
     * @param tokenSecret the token secret
     * @return the authorization
     */
    protected Authorization getAuthorization(String token, String tokenSecret) {
        Configuration configuration = new ConfigurationBuilder().build();
        return new OAuthAuthorization(configuration, ApplicationConstants.TWITTER_CONSUMER_KEY,
                ApplicationConstants.TWITTER_CONSUMER_SECRET, new AccessToken(token, tokenSecret));
    }

    /**
     * Populate user.
     *
     * @param user the user
     */
    private void populateUser(User user) {
        // if (user.getTags() != null) {
        // user.getTags().getTag().size();
        // }
        // if (user.getUrls() != null) {
        // for (Url url : user.getUrls()) {
        // url.getDescription();
        // }
        // }
    }

    /**
     * Map list.
     *
     * @param source the source
     * @return the list
     */
    private List<com.appspot.socialinquirer.shared.dto.User> mapList(List<User> source) {
        List<com.appspot.socialinquirer.shared.dto.User> target = new ArrayList<com.appspot.socialinquirer.shared.dto.User>();
        for (User user : source) {
            target.add(mapUser(user));
        }
        return target;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.appspot.everscribe.server.service.UserService#getRandomQuote()
     */
    @Override
    public String getRandomQuote() {
        EntityManager entityManager = createEntityManager();
        try {
            Map<String, Object> parameters = new HashMap<String, Object>();
            Quote quote = getDao(entityManager).getSingleResult(Quote.class, NamedQueries.FIND_RANDOM_QUOTE,
                    parameters);
            if (quote != null) {
                return quote.getText().getValue();
            }
        } finally {
            closeEntityManager(entityManager);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#authenticate(java.lang
     * .String)
     */
    @Override
    public com.appspot.socialinquirer.shared.dto.User authenticate(String accessToken) {
        EntityManager entityManager = createEntityManager();
        try {
            com.appspot.socialinquirer.shared.dto.User sUser = ServiceFactory.newInstance()
                    .createStackExchangeService(accessToken).getCurrentUser();
            User user = getUserByStackExchangeId(sUser.getStackExchangeId(), entityManager);

            if (user == null) {
                user = new User();
            }
            user.setDisplayName(sUser.getDisplayName());
            user.setAge(sUser.getAge());
            user.setReputation(sUser.getReputation());
            user.setStackExchangeId(sUser.getStackExchangeId());
            user.setAccessToken(new Text(accessToken));
            user.setAcceptRate(sUser.getAcceptRate());

            if (user.getId() == null) {
                getDao(entityManager).saveOrUpdate(user);
            } else {
                getDao(entityManager).merge(user);
            }

            return mapUser(user);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "An error occurred while fetching user from Evernote", e);
            throw new ServiceException(e);
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /**
     * Map user.
     *
     * @param user the user
     * @return the com.appspot.socialinquirer.shared.dto. user
     */
    private com.appspot.socialinquirer.shared.dto.User mapUser(User user) {
        Mapper<com.appspot.socialinquirer.shared.dto.User, User> mapper = MAPPER_FACTORY
                .createMapper(com.appspot.socialinquirer.shared.dto.User.class, User.class);
        com.appspot.socialinquirer.shared.dto.User retValue = mapper.from(user);
        retValue.setXmppSettings(MAPPER_FACTORY
                .createMapper(com.appspot.socialinquirer.shared.dto.XmppSettings.class, XmppSettings.class)
                .from(user.getXmppSettings()));

        return retValue;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#updatePaperSettings
     * (java.lang.String, com.appspot.everscribe.shared.dto.PaperSettings)
     */
    @Override
    public void updateXmppSettings(String stackExchangeId,
            com.appspot.socialinquirer.shared.dto.XmppSettings settings) {
        EntityManager entityManager = createEntityManager();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                MAPPER_FACTORY
                        .createMapper(com.appspot.socialinquirer.shared.dto.XmppSettings.class, XmppSettings.class)
                        .copyProperties(settings, user.getXmppSettings());
                getDao(entityManager).merge(user.getXmppSettings());
                // memcache.put(user.getEvernoteId(), user);
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#getUsersPendingSync
     * (int, long)
     */
    @Override
    public List<com.appspot.socialinquirer.shared.dto.User> getUsersPendingSync(int bucketId, long lastSyncTime) {
        EntityManager entityManager = createEntityManager();
        try {
            Map<String, Object> parameters = new HashMap<String, Object>();
            // parameters.put("bucketSize", 10);
            // parameters.put("bucketId", bucketId);
            // parameters.put("lastSyncTime", lastSyncTime);
            return mapList(getDao(entityManager).getResultList(User.class, NamedQueries.FIND_USERS_PENDING_SYNC,
                    parameters));
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#getUserTemplates(java
     * .lang.String)
     */
    @Override
    public List<Message> getUserMessages(String stackExchangeId) {
        EntityManager entityManager = createEntityManager();
        List<Message> templates = new ArrayList<Message>();
        Mapper<Message, com.appspot.socialinquirer.server.model.Message> mapper = MAPPER_FACTORY
                .createMapper(Message.class, com.appspot.socialinquirer.server.model.Message.class);
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("user", user);
                List<com.appspot.socialinquirer.server.model.Message> resultList = getDao(entityManager)
                        .getResultList(com.appspot.socialinquirer.server.model.Message.class,
                                NamedQueries.FIND_USER_MESSAGES, parameters);
                for (com.appspot.socialinquirer.server.model.Message template : resultList) {
                    templates.add(mapper.from(template));
                }
            }
        } finally {
            closeEntityManager(entityManager);
        }
        return templates;
    }

    /**
     * Gets the user by stack exchange id.
     *
     * @param stackExchangeId the stack exchange id
     * @param entityManager the entity manager
     * @return the user by stack exchange id
     */
    private User getUserByStackExchangeId(String stackExchangeId, EntityManager entityManager) {
        // Caching is broken. Lets see if its needed
        User user = null; // (User) memcache.get(stackExchangeId);
        if (user == null) {
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("stackExchangeId", stackExchangeId);
            user = getDao(entityManager).getSingleResult(User.class, NamedQueries.FIND_USER_BY_STACK_EXCHANGE_ID,
                    parameters);
            if (user != null) {
                // memcache.put(user.getEvernoteId(), user);
            }
        }
        return user;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#addUserTemplates(java
     * .lang.String, java.util.List)
     */
    @Override
    public void addUserMessages(String stackExchangeId, List<Message> templates) {
        EntityManager entityManager = createEntityManager();
        Mapper<Message, com.appspot.socialinquirer.server.model.Message> mapper = MAPPER_FACTORY
                .createMapper(Message.class, com.appspot.socialinquirer.server.model.Message.class);
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                List<com.appspot.socialinquirer.server.model.Message> userTemplates = new ArrayList<com.appspot.socialinquirer.server.model.Message>();
                // Map<String, com.appspot.everscribe.server.model.Template>
                // savedTemplates = getSavedTemplates(templates, entityManager);
                for (Message template : templates) {
                    com.appspot.socialinquirer.server.model.Message userTemplate = mapper.to(template);
                    userTemplate.setUser(user);
                    userTemplates.add(userTemplate);
                }
                getDao(entityManager).saveOrUpdateAll(userTemplates);
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#addUserTags(java.lang
     * .String, java.util.List)
     */
    @Override
    public void addUserTags(String stackExchangeId, List<Tag> tags) {
        EntityManager entityManager = createEntityManager();
        Mapper<Tag, com.appspot.socialinquirer.server.model.Tag> mapper = MAPPER_FACTORY.createMapper(Tag.class,
                com.appspot.socialinquirer.server.model.Tag.class);
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                List<com.appspot.socialinquirer.server.model.Tag> userTags = new ArrayList<com.appspot.socialinquirer.server.model.Tag>();
                for (Tag template : tags) {
                    com.appspot.socialinquirer.server.model.Tag userTag = mapper.to(template);
                    userTag.setUser(user);
                    userTags.add(userTag);
                }
                getDao(entityManager).saveOrUpdateAll(userTags);
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#manageConnection(java
     * .lang.String, boolean)
     */
    @Override
    public void manageConnection(String stackExchangeId, boolean connect) {
        EntityManager entityManager = createEntityManager();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                user.setConnected(connect);
                getDao(entityManager).merge(user);
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#removeUserTemplates
     * (java.lang.String, java.util.List)
     */
    @Override
    public void removeUserMessages(String stackExchangeId, List<Message> templates) {
        EntityManager entityManager = createEntityManager();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("user", user);
                List<com.appspot.socialinquirer.server.model.Message> resultList = getDao(entityManager)
                        .getResultList(com.appspot.socialinquirer.server.model.Message.class,
                                NamedQueries.FIND_USER_MESSAGES, parameters);
                for (Message template : templates) {
                    for (com.appspot.socialinquirer.server.model.Message entity : resultList) {
                        if (entity.getId().getId() == Long.valueOf(template.getKey())) {
                            getDao(entityManager).delete(entity);
                        }
                    }
                }
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.appspot.everscribe.server.service.UserService#getUserTags(java.lang
     * .String)
     */
    @Override
    public List<Tag> getUserTags(String stackExchangeId, int numberOfTags) {
        List<Tag> tags = new ArrayList<Tag>();
        EntityManager entityManager = createEntityManager();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                List<com.appspot.socialinquirer.server.model.Tag> tagList = user.getTags();
                Collections.sort(tagList, new Comparator<com.appspot.socialinquirer.server.model.Tag>() {
                    @Override
                    public int compare(com.appspot.socialinquirer.server.model.Tag o1,
                            com.appspot.socialinquirer.server.model.Tag o2) {
                        return o2.getFreqency() - o1.getFreqency();
                    }
                });
                for (int i = 0; i < tagList.size() && i < numberOfTags; i++) {
                    com.appspot.socialinquirer.server.model.Tag tag = tagList.get(i);
                    tags.add(new Tag(tag.getTag(), tag.getDescription().getValue(), tag.getFreqency()));
                }
            }
        } finally {
            closeEntityManager(entityManager);
        }
        return tags;
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getUserTasks(java.lang.String)
     */
    @Override
    public List<Task> getUserTasks(String stackExchangeId) {
        EntityManager entityManager = createEntityManager();
        List<Task> templates = new ArrayList<Task>();
        Mapper<Task, com.appspot.socialinquirer.server.model.Task> mapper = MAPPER_FACTORY.createMapper(Task.class,
                com.appspot.socialinquirer.server.model.Task.class);
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("user", user);
                List<com.appspot.socialinquirer.server.model.Task> resultList = getDao(entityManager).getResultList(
                        com.appspot.socialinquirer.server.model.Task.class, NamedQueries.FIND_USER_TASKS,
                        parameters);
                for (com.appspot.socialinquirer.server.model.Task template : resultList) {
                    templates.add(mapper.from(template));
                }
            }
        } finally {
            closeEntityManager(entityManager);
        }
        return templates;
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getUserFriends(java.lang.String)
     */
    @Override
    public List<com.appspot.socialinquirer.shared.dto.User> getUserFriends(String stackExchangeId) {
        EntityManager entityManager = createEntityManager();
        List<com.appspot.socialinquirer.shared.dto.User> templates = new ArrayList<com.appspot.socialinquirer.shared.dto.User>();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null && user.getAccessToken() != null) {
                StackExchangeService service = ServiceFactory.newInstance()
                        .createStackExchangeService(user.getAccessToken().getValue());
                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("user", user);
                List<com.appspot.socialinquirer.server.model.Friend> resultList = getDao(entityManager)
                        .getResultList(com.appspot.socialinquirer.server.model.Friend.class,
                                NamedQueries.FIND_USER_FRIENDS, parameters);
                List<Long> userIds = new ArrayList<Long>();
                for (com.appspot.socialinquirer.server.model.Friend friend : resultList) {
                    userIds.add(friend.getFriendId());
                }
                templates.addAll(service.getUsers(userIds));
            }
        } finally {
            closeEntityManager(entityManager);
        }
        return templates;
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getUserFollowers(java.lang.String)
     */
    @Override
    public List<com.appspot.socialinquirer.shared.dto.User> getUserFollowers(String stackExchangeId) {
        EntityManager entityManager = createEntityManager();
        List<com.appspot.socialinquirer.shared.dto.User> templates = new ArrayList<com.appspot.socialinquirer.shared.dto.User>();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null && user.getAccessToken() != null) {
                StackExchangeService service = ServiceFactory.newInstance()
                        .createStackExchangeService(user.getAccessToken().getValue());
                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("friendId", user.getStackExchangeId());
                List<com.appspot.socialinquirer.server.model.Friend> resultList = getDao(entityManager)
                        .getResultList(com.appspot.socialinquirer.server.model.Friend.class,
                                NamedQueries.FIND_USER_FOLLOWERS, parameters);
                List<Long> userIds = new ArrayList<Long>();
                for (com.appspot.socialinquirer.server.model.Friend friend : resultList) {
                    userIds.add(friend.getFriendId());
                }
                templates.addAll(service.getUsers(userIds));
            }
        } finally {
            closeEntityManager(entityManager);
        }
        return templates;
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#addUserTasks(java.lang.String, java.util.List)
     */
    @Override
    public void addUserTasks(String stackExchangeId, List<Task> tasks) {
        EntityManager entityManager = createEntityManager();
        Mapper<Task, com.appspot.socialinquirer.server.model.Task> mapper = MAPPER_FACTORY.createMapper(Task.class,
                com.appspot.socialinquirer.server.model.Task.class);
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                List<com.appspot.socialinquirer.server.model.Task> userTemplates = new ArrayList<com.appspot.socialinquirer.server.model.Task>();
                for (Task template : tasks) {
                    com.appspot.socialinquirer.server.model.Task userTemplate = mapper.to(template);
                    userTemplate.setUser(user);
                    userTemplates.add(userTemplate);
                }
                getDao(entityManager).saveOrUpdateAll(userTemplates);
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#addUserFriends(java.lang.String, java.util.List)
     */
    @Override
    public void addUserFriends(String stackExchangeId, List<com.appspot.socialinquirer.shared.dto.User> friends) {
        EntityManager entityManager = createEntityManager();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                List<com.appspot.socialinquirer.server.model.Friend> userTemplates = new ArrayList<com.appspot.socialinquirer.server.model.Friend>();
                for (com.appspot.socialinquirer.shared.dto.User template : friends) {
                    com.appspot.socialinquirer.server.model.Friend friend = new com.appspot.socialinquirer.server.model.Friend();
                    friend.setDescription(new Text(template.getDescription()));
                    friend.setFriendId(Long.valueOf(template.getStackExchangeId()));
                    friend.setUser(user);
                    userTemplates.add(friend);
                }
                getDao(entityManager).saveOrUpdateAll(userTemplates);
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#removeUserTasks(java.lang.String, java.util.List)
     */
    @Override
    public void removeUserTasks(String stackExchangeId, List<Task> tasks) {
        EntityManager entityManager = createEntityManager();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("user", user);
                List<com.appspot.socialinquirer.server.model.Task> resultList = getDao(entityManager).getResultList(
                        com.appspot.socialinquirer.server.model.Task.class, NamedQueries.FIND_USER_TASKS,
                        parameters);
                for (Task template : tasks) {
                    for (com.appspot.socialinquirer.server.model.Task entity : resultList) {
                        if (entity.getId().getId() == Long.valueOf(template.getKey())) {
                            getDao(entityManager).delete(entity);
                        }
                    }
                }
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#removeUserFriends(java.lang.String, java.util.List)
     */
    @Override
    public void removeUserFriends(String stackExchangeId,
            List<com.appspot.socialinquirer.shared.dto.User> friends) {
        EntityManager entityManager = createEntityManager();
        try {
            User user = getUserByStackExchangeId(stackExchangeId, entityManager);
            if (user != null) {
                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("user", user);
                List<com.appspot.socialinquirer.server.model.Friend> resultList = getDao(entityManager)
                        .getResultList(com.appspot.socialinquirer.server.model.Friend.class,
                                NamedQueries.FIND_USER_FRIENDS, parameters);
                for (com.appspot.socialinquirer.shared.dto.User template : friends) {
                    for (com.appspot.socialinquirer.server.model.Friend entity : resultList) {
                        if (entity.getId().getId() == Long.valueOf(template.getKey())) {
                            getDao(entityManager).delete(entity);
                        }
                    }
                }
            }
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getQuizzes()
     */
    @Override
    public List<Quiz> getQuizzes() {
        List<Quiz> retValue = new ArrayList<Quiz>();
        Mapper<Quiz, com.appspot.socialinquirer.server.model.Quiz> mapper = MAPPER_FACTORY.createMapper(Quiz.class,
                com.appspot.socialinquirer.server.model.Quiz.class);

        EntityManager entityManager = createEntityManager();
        try {
            List<com.appspot.socialinquirer.server.model.Quiz> result = getDao(entityManager)
                    .loadAll(com.appspot.socialinquirer.server.model.Quiz.class);
            for (com.appspot.socialinquirer.server.model.Quiz quiz : result) {
                retValue.add(mapper.from(quiz));
            }
        } finally {
            closeEntityManager(entityManager);
        }

        return retValue;
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getQuiz(java.lang.String)
     */
    @Override
    public Quiz getQuiz(String quizId) {
        Mapper<Quiz, com.appspot.socialinquirer.server.model.Quiz> mapper = MAPPER_FACTORY.createMapper(Quiz.class,
                com.appspot.socialinquirer.server.model.Quiz.class);

        EntityManager entityManager = createEntityManager();
        try {
            StackExchangeService service = ServiceFactory.newInstance()
                    .createStackExchangeService(ApplicationConstants.STACK_EXCHANGE_ACCESS_TOKEN);

            com.appspot.socialinquirer.server.model.Quiz result = getDao(entityManager)
                    .load(com.appspot.socialinquirer.server.model.Quiz.class, quizId);
            Quiz quiz = mapper.from(result);
            if (result.getQuestionIds() != null && !result.getQuestionIds().isEmpty()) {
                quiz.setQuestions(service.getQuestions(result.getQuestionIds()));
            }
            return quiz;
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getPolls()
     */
    @Override
    public List<Poll> getPolls() {
        List<Poll> retValue = new ArrayList<Poll>();
        Mapper<Poll, com.appspot.socialinquirer.server.model.Poll> mapper = MAPPER_FACTORY.createMapper(Poll.class,
                com.appspot.socialinquirer.server.model.Poll.class);

        EntityManager entityManager = createEntityManager();
        try {
            List<com.appspot.socialinquirer.server.model.Poll> result = getDao(entityManager)
                    .loadAll(com.appspot.socialinquirer.server.model.Poll.class);
            for (com.appspot.socialinquirer.server.model.Poll quiz : result) {
                retValue.add(mapper.from(quiz));
            }
        } finally {
            closeEntityManager(entityManager);
        }

        return retValue;
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getPoll(java.lang.String)
     */
    @Override
    public Poll getPoll(String pollId) {
        Mapper<Poll, com.appspot.socialinquirer.server.model.Poll> mapper = MAPPER_FACTORY.createMapper(Poll.class,
                com.appspot.socialinquirer.server.model.Poll.class);

        EntityManager entityManager = createEntityManager();
        try {
            com.appspot.socialinquirer.server.model.Poll result = getDao(entityManager)
                    .load(com.appspot.socialinquirer.server.model.Poll.class, pollId);
            return mapper.from(result);
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getPages()
     */
    @Override
    public List<Page> getPages() {
        List<Page> retValue = new ArrayList<Page>();
        Mapper<Page, com.appspot.socialinquirer.server.model.Page> mapper = MAPPER_FACTORY.createMapper(Page.class,
                com.appspot.socialinquirer.server.model.Page.class);

        EntityManager entityManager = createEntityManager();
        try {
            List<com.appspot.socialinquirer.server.model.Page> result = getDao(entityManager)
                    .loadAll(com.appspot.socialinquirer.server.model.Page.class);
            for (com.appspot.socialinquirer.server.model.Page quiz : result) {
                retValue.add(mapper.from(quiz));
            }
        } finally {
            closeEntityManager(entityManager);
        }

        return retValue;
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#getPage(java.lang.String)
     */
    @Override
    public Page getPage(String pageId) {
        Mapper<Page, com.appspot.socialinquirer.server.model.Page> mapper = MAPPER_FACTORY.createMapper(Page.class,
                com.appspot.socialinquirer.server.model.Page.class);

        EntityManager entityManager = createEntityManager();
        try {
            com.appspot.socialinquirer.server.model.Page result = getDao(entityManager)
                    .load(com.appspot.socialinquirer.server.model.Page.class, pageId);
            return mapper.from(result);
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#addQuiz(com.appspot.socialinquirer.shared.dto.Quiz)
     */
    @Override
    public void addQuiz(Quiz quiz) {
        Mapper<Quiz, com.appspot.socialinquirer.server.model.Quiz> mapper = MAPPER_FACTORY.createMapper(Quiz.class,
                com.appspot.socialinquirer.server.model.Quiz.class);
        EntityManager entityManager = createEntityManager();
        try {
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("name", quiz.getName());
            com.appspot.socialinquirer.server.model.Quiz existing = getDao(entityManager).getSingleResult(
                    com.appspot.socialinquirer.server.model.Quiz.class, NamedQueries.FIND_QUIZ_BY_NAME);
            if (existing != null) {
                throw new ServiceException("A quiz with this name already exists.");
            }
            getDao(entityManager).saveOrUpdate(mapper.to(quiz));
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#addPoll(com.appspot.socialinquirer.shared.dto.Poll)
     */
    @Override
    public void addPoll(Poll poll) {
        Mapper<Poll, com.appspot.socialinquirer.server.model.Poll> mapper = MAPPER_FACTORY.createMapper(Poll.class,
                com.appspot.socialinquirer.server.model.Poll.class);
        EntityManager entityManager = createEntityManager();
        try {
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("name", poll.getName());
            com.appspot.socialinquirer.server.model.Poll existing = getDao(entityManager).getSingleResult(
                    com.appspot.socialinquirer.server.model.Poll.class, NamedQueries.FIND_POLL_BY_NAME);
            if (existing != null) {
                throw new ServiceException("A poll with this name already exists.");
            }
            getDao(entityManager).saveOrUpdate(mapper.to(poll));
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#addPage(com.appspot.socialinquirer.shared.dto.Page)
     */
    @Override
    public void addPage(Page page) {
        Mapper<Page, com.appspot.socialinquirer.server.model.Page> mapper = MAPPER_FACTORY.createMapper(Page.class,
                com.appspot.socialinquirer.server.model.Page.class);
        EntityManager entityManager = createEntityManager();
        try {
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("name", page.getName());
            com.appspot.socialinquirer.server.model.Page existing = getDao(entityManager).getSingleResult(
                    com.appspot.socialinquirer.server.model.Page.class, NamedQueries.FIND_PAGE_BY_NAME);
            if (existing != null) {
                throw new ServiceException("A page with this name already exists.");
            }
            getDao(entityManager).saveOrUpdate(mapper.to(page));
        } finally {
            closeEntityManager(entityManager);
        }
    }

    /* (non-Javadoc)
     * @see com.appspot.socialinquirer.server.service.UserService#addQuestionToQuiz(com.appspot.socialinquirer.shared.dto.Question, com.appspot.socialinquirer.shared.dto.Quiz)
     */
    @Override
    public void addQuestionToQuiz(Question question, Quiz quiz) {
        EntityManager entityManager = createEntityManager();
        try {
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("name", quiz.getName());
            com.appspot.socialinquirer.server.model.Quiz existing = getDao(entityManager).getSingleResult(
                    com.appspot.socialinquirer.server.model.Quiz.class, NamedQueries.FIND_QUIZ_BY_NAME);
            if (existing == null) {
                throw new ServiceException("No quiz exists with the name." + quiz.getName());
            }
            existing.getQuestionIds().add(Long.valueOf(question.getKey()));
            getDao(entityManager).merge(existing);
        } finally {
            closeEntityManager(entityManager);
        }
    }
}