1. Juan Carlos Picado Herrera
  2. encuestame

Commits

Juan Carlos Picado Herrera  committed ed95116

Added social abstract layer

  • Participants
  • Parent commits 815e877
  • Branches master

Comments (0)

Files changed (19)

File encuestame-business/src/main/java/org/encuestame/business/service/AbstractBaseService.java

View file
  • Ignore whitespace
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.encuestame.business.mail.MailServiceImpl;
+import org.encuestame.business.service.imp.ITwitterService;
 import org.encuestame.core.files.PathUtil;
 import org.encuestame.core.util.ConvertDomainBean;
 import org.encuestame.core.util.MD5Utils;
  * @author Picado, Juan juan@encuestame.org
  * @since 22/05/2009 1:02:45
  */
-public abstract class AbstractBaseService extends AbstractConfigurationService {
+public abstract class AbstractBaseService extends AbstractSocialService {
 
     private Log log = LogFactory.getLog(this.getClass());
 
     private MailServiceImpl serviceMail;
 
     /**
-     *
-     */
-    private static int TWITTER_AUTH_ERROR = 401;
-
-    /**
      * Constructor.
      */
     public AbstractBaseService() {}
      }
 
     /**
-     * Verify OAuth Credentials
-     * @param token token stored
-     * @param secretToken secret Token
-     * @param pin pin
-     * @return
-     * @throws TwitterException
-     */
-    public Boolean verifyCredentials(final String token,
-                                     final String tokenSecret,
-                                     final String consumerKey,
-                                     final String consumerSecret,
-                final String pin){
-        Boolean verified = false;
-        log.debug("verifyCredentials OAuth");
-        log.debug("Token {"+token);
-        log.debug("secretToken {"+tokenSecret);
-        log.debug("pin {"+pin);
-        log.debug("consumerKey {"+consumerKey);
-        log.debug("consumerSecret {"+consumerSecret);
-        Twitter twitter = null;
-        try {
-             twitter = new TwitterFactory().getInstance();
-            if(token == null || token.isEmpty()){
-                verified = false;
-            } else {
-                log.debug("Exist Previous Token.");
-                final AccessToken accessToken = new AccessToken(token, tokenSecret);
-                log.debug("Created Token "+accessToken);
-                twitter = new TwitterFactory().getOAuthAuthorizedInstance(consumerKey, consumerSecret, accessToken);
-                log.debug("Verifying Credentials");
-                final User user = twitter.verifyCredentials();
-                log.debug("Verifying Credentials User "+user);
-                if (user != null) {
-                    log.debug("Verify OAuth User " + user.getId());
-                    verified = true;
-                }
-            }
-        } catch (TwitterException te) {
-            log.error("Twitter Error "+te.getMessage());
-            if (AbstractBaseService.TWITTER_AUTH_ERROR == te.getStatusCode()) {
-                log.error("Twitter Error "+te.getStatusCode());
-                verified = false;
-            } else {
-                log.error(te);
-            }
-            log.error("Verify OAuth Error " + te.getLocalizedMessage());
-        }
-        log.debug("verified "+verified);
-        return verified;
-    }
-
-    /**
      * Get Access Token.
      * @param token
      * @param tokenSecret
             throw new EnMeExpcetion("error on create directory");
         }
     }
-
 }

File encuestame-business/src/main/java/org/encuestame/business/service/AbstractSocialService.java

View file
  • Ignore whitespace
+
+package org.encuestame.business.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.encuestame.business.service.imp.ITwitterService;
+import org.encuestame.core.util.ConvertDomainBean;
+import org.encuestame.persistence.domain.security.SocialAccount;
+import org.encuestame.persistence.domain.security.UserAccount;
+import org.encuestame.persistence.domain.security.SocialAccount.TypeAuth;
+import org.encuestame.persistence.domain.social.SocialProvider;
+import org.encuestame.persistence.exception.EnMeExpcetion;
+import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
+import org.encuestame.utils.security.SocialAccountBean;
+
+import twitter4j.Twitter;
+import twitter4j.TwitterException;
+import twitter4j.TwitterFactory;
+import twitter4j.User;
+import twitter4j.http.AccessToken;
+
+/**
+ *
+ * @author Picado, Juan juanATencuestame.org
+ * @since Mar 7, 2011
+ */
+public class AbstractSocialService extends AbstractConfigurationService {
+
+    private Logger log = Logger.getLogger(this.getClass());
+
+    /** Twitter Service. **/
+    private ITwitterService twitterService;
+
+   /**
+    *
+    */
+   private static int TWITTER_AUTH_ERROR = 401;
+
+
+    /**
+     * Update OAuth Secret Twitter Credentials.
+     * @param accountBean {@link SocialAccountBean}
+     * @param username username logged
+     * @throws EnMeExpcetion exception
+     */
+    public void updateSecretTwitterCredentials(final SocialAccountBean accountBean,
+            final String username) throws EnMeExpcetion{
+         //TODO: we should search twitter account filter by username
+         final SocialAccount twitterAccount = this.getSocialAccount(accountBean.getAccountId()); //TODO: filter by Username Too
+         //twitterAccount.setConsumerKey(accountBean.getKey());
+         //twitterAccount.setConsumerSecret(accountBean.getSecret());
+         twitterAccount.setType(ConvertDomainBean.convertStringToEnum(accountBean.getType()));
+         if(accountBean.getPin() != null && !accountBean.getPin().isEmpty()){
+             log.debug("PIN Exists {"+accountBean.getPin());
+             //twitterAccount.setTwitterPin(Integer.valueOf(accountBean.getPin()));
+            //If exist pin, we can verify credentials
+            log.debug("Verify OAuth Credentials");
+                if(verifyCredentials(
+                        //Token and Secret token should be always from database
+                        twitterAccount.getToken(),
+                        twitterAccount.getSecretToken(),
+                        //consumer key's
+                        accountBean.getKey(),
+                        accountBean.getSecret(),
+                        //pin, update by the user.
+                        accountBean.getPin())){
+                    twitterAccount.setVerfied(Boolean.TRUE);
+                } else {
+                    twitterAccount.setVerfied(Boolean.FALSE);
+                }
+         } else {
+             log.info("Account not verified, pin not found");
+             //twitterAccount.setTwitterPin(null);
+             twitterAccount.setVerfied(Boolean.FALSE);
+         }
+        log.debug("Update Secret Twitter Credentials");
+        getAccountDao().saveOrUpdate(twitterAccount);
+        log.info("update Twitter Account");
+    }
+
+    /**
+     * Verify OAuth Credentials
+     * @param token token stored
+     * @param secretToken secret Token
+     * @param pin pin
+     * @return
+     * @throws TwitterException
+     */
+    public Boolean verifyCredentials(final String token,
+                                     final String tokenSecret,
+                                     final String consumerKey,
+                                     final String consumerSecret,
+                final String pin){
+        Boolean verified = false;
+        log.debug("verifyCredentials OAuth");
+        log.debug("Token {"+token);
+        log.debug("secretToken {"+tokenSecret);
+        log.debug("pin {"+pin);
+        log.debug("consumerKey {"+consumerKey);
+        log.debug("consumerSecret {"+consumerSecret);
+        Twitter twitter = null;
+        try {
+             twitter = new TwitterFactory().getInstance();
+            if(token == null || token.isEmpty()){
+                verified = false;
+            } else {
+                log.debug("Exist Previous Token.");
+                final AccessToken accessToken = new AccessToken(token, tokenSecret);
+                log.debug("Created Token "+accessToken);
+                twitter = new TwitterFactory().getOAuthAuthorizedInstance(consumerKey, consumerSecret, accessToken);
+                log.debug("Verifying Credentials");
+                final User user = twitter.verifyCredentials();
+                log.debug("Verifying Credentials User "+user);
+                if (user != null) {
+                    log.debug("Verify OAuth User " + user.getId());
+                    verified = true;
+                }
+            }
+        } catch (TwitterException te) {
+            log.error("Twitter Error "+te.getMessage());
+            if (AbstractSocialService.TWITTER_AUTH_ERROR == te.getStatusCode()) {
+                log.error("Twitter Error "+te.getStatusCode());
+                verified = false;
+            } else {
+                log.error(te);
+            }
+            log.error("Verify OAuth Error " + te.getLocalizedMessage());
+        }
+        log.debug("verified "+verified);
+        return verified;
+    }
+
+
+    /**
+     * Update OAuth Token/Secret Social Account.
+     * @param socialAccountId
+     * @param token
+     * @param tokenSecret
+     * @param username
+     * @param account
+     * @throws EnMeExpcetion
+     */
+    public void addOrUpdateOAuthTokenSocialAccount(
+            final Long socialAccountId,
+            final String token,
+            final String tokenSecret,
+            final String username,
+            final UserAccount account,
+            final SocialProvider socialProvider) throws EnMeExpcetion{
+            SocialAccount socialAccount = getAccountDao().getSocialAccount(socialProvider, socialAccountId);
+            if (socialAccount == null) {
+                log.info("adding new social account");
+                socialAccount = new SocialAccount();
+            }
+            log.debug("Updating  Token to {"+token);
+            log.debug("Updating Secret Token to {"+tokenSecret);
+            socialAccount.setToken(token);
+            socialAccount.setVerfied(Boolean.TRUE);
+            socialAccount.setAccounType(socialProvider);
+            socialAccount.setSecUsers(account.getAccount());
+            socialAccount.setSocialAccountName(username);
+            socialAccount.setType(TypeAuth.OAUTH);
+            socialAccount.setSecretToken(tokenSecret);
+            socialAccount.setSocialUserId(socialAccountId);
+            getAccountDao().saveOrUpdate(socialAccount);
+            log.debug("Updated Token");
+    }
+
+
+    /**
+     * Get Twitter Account.
+     * @param twitterAccountId
+     * @return
+     */
+    public SocialAccountBean getTwitterAccount(final Long twitterAccountId){
+        return ConvertDomainBean.convertSocialAccountToBean(getAccountDao().getTwitterAccount(twitterAccountId));
+    }
+
+
+    /**
+     * Get User Logged Scocial Accounts.
+     * @param username
+     * @param provider
+     * @return
+     * @throws EnMeNoResultsFoundException
+     */
+    public List<SocialAccountBean> getUserLoggedSocialAccount(final String username, final SocialProvider provider)
+           throws EnMeNoResultsFoundException{
+         return ConvertDomainBean.convertListSocialAccountsToBean(getAccountDao()
+                                 .getTwitterAccountByUser(getUserAccount(username).getAccount(), provider));
+    }
+
+    /**
+     * Get User Logged Verified Social Accounts.
+     * @param username username
+     * @return list of social accounts.
+     * @throws EnMeNoResultsFoundException exception
+     */
+    public List<SocialAccountBean> getUserLoggedVerifiedTwitterAccount(final String username, final SocialProvider provider)
+             throws EnMeNoResultsFoundException{
+        final List<SocialAccountBean> comfirmedSocialAccounts = new ArrayList<SocialAccountBean>();
+        final List<SocialAccount> socialAccounts = getAccountDao()
+                .getTwitterVerifiedAccountByUser(getUserAccount(username).getAccount(), provider);
+        for (SocialAccount socialAccount : socialAccounts) {
+            if(getTwitterService().verifyCredentials(socialAccount)){
+                log.debug("Confirmed Account  -- "+socialAccount.getSocialAccountName());
+                comfirmedSocialAccounts.add(ConvertDomainBean.convertSocialAccountToBean(socialAccount));
+            }
+        }
+        log.debug("social provider verified "+comfirmedSocialAccounts.size());
+        return comfirmedSocialAccounts;
+   }
+
+
+    /**
+    *
+    * @param accountId
+    * @return
+    */
+   protected SocialAccount getSocialAccount(final Long accountId){
+        return  getAccountDao().getTwitterAccount(accountId); //TODO: filter by Username Too
+   }
+
+   /**
+    * Update Twitter Account.
+    * @param accountBean account
+    * @param password password
+    * TODO: this method is close to be deprecated, twitter don't allow password login.
+    */
+   @Deprecated
+   public void updateTwitterAccount(
+           final SocialAccountBean accountBean,
+           final String password,
+           final Boolean verify){
+       if(accountBean.getAccountId() != null){
+           final SocialAccount twitterAccount = getAccountDao().getTwitterAccount(accountBean.getAccountId());
+           if(twitterAccount != null){
+               //twitterAccount.setTwitterPassword(password);
+               twitterAccount.setVerfied(verify);
+               log.debug("Updating twitter password account");
+               getAccountDao().saveOrUpdate(twitterAccount);
+           }
+       }
+       log.info("update Twitter Account");
+   }
+
+
+   /**
+    * @return the twitterService
+    */
+   public ITwitterService getTwitterService() {
+       return twitterService;
+   }
+
+   /**
+    * @param twitterService the twitterService to set
+    */
+   public void setTwitterService(final ITwitterService twitterService) {
+       this.twitterService = twitterService;
+   }
+}

File encuestame-business/src/main/java/org/encuestame/business/service/AbstractSurveyService.java

View file
  • Ignore whitespace
 @Service
 public class AbstractSurveyService extends AbstractChartService {
 
-    /** Twitter Service. **/
-    private ITwitterService twitterService;
-
     /** AnswerPoll Path. **/
     private String answerPollPath;
 
      }
 
     /**
-     * @return the twitterService
-     */
-    public ITwitterService getTwitterService() {
-        return twitterService;
-    }
-
-    /**
-     * @param twitterService the twitterService to set
-     */
-    public void setTwitterService(final ITwitterService twitterService) {
-        this.twitterService = twitterService;
-    }
-
-    /**
      * @return the answerPollPath
      */
     public String getAnswerPollPath() {

File encuestame-business/src/main/java/org/encuestame/business/service/SecurityService.java

View file
  • Ignore whitespace
 import org.encuestame.persistence.domain.security.Account;
 import org.encuestame.persistence.domain.security.Group;
 import org.encuestame.persistence.domain.security.Permission;
-import org.encuestame.persistence.domain.security.SocialAccount;
-import org.encuestame.persistence.domain.security.SocialAccount.TypeAuth;
 import org.encuestame.persistence.domain.security.UserAccount;
-import org.encuestame.persistence.domain.social.SocialProvider;
-import org.encuestame.persistence.exception.EnMeIllegalProviderException;
-import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
 import org.encuestame.persistence.exception.EnMeExpcetion;
+import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
 import org.encuestame.persistence.exception.EnmeFailOperation;
 import org.encuestame.utils.security.SignUpBean;
-import org.encuestame.utils.security.SocialAccountBean;
 import org.encuestame.utils.web.UnitGroupBean;
 import org.encuestame.utils.web.UnitLists;
 import org.encuestame.utils.web.UnitPermission;
     private Logger log = Logger.getLogger(this.getClass());
 
     /** Default User Permission **/
-    private static final String DEFAULT = EnMePermission.ENCUESTAME_USER.name();
+    private static final EnMePermission DEFAULT = EnMePermission.ENCUESTAME_USER;
 
     /** Default User Permission **/
-    private static final String ADMIN = EnMePermission.ENCUESTAME_ADMIN.name();
+    private static final EnMePermission ADMIN = EnMePermission.ENCUESTAME_ADMIN;
 
     /** Default User Permission **/
-    private static final String EDITOR = EnMePermission.ENCUESTAME_EDITOR.name();
+    private static final EnMePermission EDITOR = EnMePermission.ENCUESTAME_EDITOR;
 
     /** Default User Permission **/
-    private static final String OWNER = EnMePermission.ENCUESTAME_OWNER.name();
+    private static final EnMePermission OWNER = EnMePermission.ENCUESTAME_OWNER;
 
     /** Default User Permission **/
-    private static final String PUBLISHER = EnMePermission.ENCUESTAME_PUBLISHER.name();
+    private static final EnMePermission PUBLISHER = EnMePermission.ENCUESTAME_PUBLISHER;
 
 
     private final Integer DEFAULT_LENGTH_PASSWORD = 8;
     }
 
     /**
-     * Update Twitter Account.
-     * @param accountBean account
-     * @param password password
-     * TODO: this method is close to be deprecated, twitter don't allow password login.
-     */
-    @Deprecated
-    public void updateTwitterAccount(
-            final SocialAccountBean accountBean,
-            final String password,
-            final Boolean verify){
-        if(accountBean.getAccountId() != null){
-            final SocialAccount twitterAccount = getAccountDao().getTwitterAccount(accountBean.getAccountId());
-            if(twitterAccount != null){
-                //twitterAccount.setTwitterPassword(password);
-                twitterAccount.setVerfied(verify);
-                log.debug("Updating twitter password account");
-                getAccountDao().saveOrUpdate(twitterAccount);
-            }
-        }
-        log.info("update Twitter Account");
-    }
-
-    /**
-     *
-     * @param accountId
-     * @return
-     */
-    private SocialAccount getSocialAccount(final Long accountId){
-         return  getAccountDao().getTwitterAccount(accountId); //TODO: filter by Username Too
-    }
-
-    /**
-     * Update OAuth Secret Twitter Credentials.
-     * @param accountBean {@link SocialAccountBean}
-     * @param username username logged
-     * @throws EnMeExpcetion exception
-     */
-    public void updateSecretTwitterCredentials(final SocialAccountBean accountBean,
-            final String username) throws EnMeExpcetion{
-         //TODO: we should search twitter account filter by username
-         final SocialAccount twitterAccount = this.getSocialAccount(accountBean.getAccountId()); //TODO: filter by Username Too
-         //twitterAccount.setConsumerKey(accountBean.getKey());
-         //twitterAccount.setConsumerSecret(accountBean.getSecret());
-         twitterAccount.setType(ConvertDomainBean.convertStringToEnum(accountBean.getType()));
-         if(accountBean.getPin() != null && !accountBean.getPin().isEmpty()){
-             log.debug("PIN Exists {"+accountBean.getPin());
-             //twitterAccount.setTwitterPin(Integer.valueOf(accountBean.getPin()));
-            //If exist pin, we can verify credentials
-            log.debug("Verify OAuth Credentials");
-                if(verifyCredentials(
-                        //Token and Secret token should be always from database
-                        twitterAccount.getToken(),
-                        twitterAccount.getSecretToken(),
-                        //consumer key's
-                        accountBean.getKey(),
-                        accountBean.getSecret(),
-                        //pin, update by the user.
-                        accountBean.getPin())){
-                    twitterAccount.setVerfied(Boolean.TRUE);
-                } else {
-                    twitterAccount.setVerfied(Boolean.FALSE);
-                }
-         } else {
-             log.info("Account not verified, pin not found");
-             //twitterAccount.setTwitterPin(null);
-             twitterAccount.setVerfied(Boolean.FALSE);
-         }
-        log.debug("Update Secret Twitter Credentials");
-        getAccountDao().saveOrUpdate(twitterAccount);
-        log.info("update Twitter Account");
-    }
-
-
-    /**
-     * Update OAuth Token/Secret Social Account.
-     * @param socialAccountId
-     * @param token
-     * @param tokenSecret
-     * @param username
-     * @param account
-     * @throws EnMeExpcetion
-     */
-    public void addOrUpdateOAuthTokenSocialAccount(
-            final Long socialAccountId,
-            final String token,
-            final String tokenSecret,
-            final String username,
-            final UserAccount account,
-            final SocialProvider socialProvider) throws EnMeExpcetion{
-            SocialAccount socialAccount = getAccountDao().getSocialAccount(socialProvider, socialAccountId);
-            if (socialAccount == null) {
-                log.info("adding new social account");
-                socialAccount = new SocialAccount();
-            }
-            log.debug("Updating  Token to {"+token);
-            log.debug("Updating Secret Token to {"+tokenSecret);
-            socialAccount.setToken(token);
-            socialAccount.setVerfied(Boolean.TRUE);
-            socialAccount.setAccounType(socialProvider);
-            socialAccount.setSecUsers(account.getAccount());
-            socialAccount.setSocialAccountName(username);
-            socialAccount.setType(TypeAuth.OAUTH);
-            socialAccount.setSecretToken(tokenSecret);
-            socialAccount.setSocialUserId(socialAccountId);
-            getAccountDao().saveOrUpdate(socialAccount);
-            log.debug("Updated Token");
-    }
-
-
-    /**
-     * Get Twitter Account.
-     * @param twitterAccountId
-     * @return
-     */
-    public SocialAccountBean getTwitterAccount(final Long twitterAccountId){
-        return ConvertDomainBean.convertSocialAccountToBean(getAccountDao().getTwitterAccount(twitterAccountId));
-    }
-
-    /**
      * Assing Group to User.
      * @param user user
      * @param group group
     }
 
     /**
-     * Get Permission By Name
-     * @param permission permission
-     * @return {@link Permission}
-     */
-    public Permission getPermissionByName(final String permission){
-        final Permission permission2 = getPermissionDao().loadPermission(
-              EnMePermission.getPermissionString(permission));
-        return permission2;
-    }
-
-    /**
      * Get Permission by {@link EnMePermission}.
      * @param permission permission.
      * @return
     }
 
     /**
-     * Get User Logged Scocial Accounts.
-     * @return
-     * @throws EnMeNoResultsFoundException
-     */
-    public List<SocialAccountBean> getUserLoggedSocialAccount(final String username) throws EnMeNoResultsFoundException{
-         return ConvertDomainBean.convertListSocialAccountsToBean(getAccountDao()
-                                 .getTwitterAccountByUser(getUserAccount(username).getAccount()));
-    }
-
-    /**
-     * Get User Logged Verified Social Accounts.
-     * @param username username
-     * @return list of social accounts.
-     * @throws EnMeNoResultsFoundException exception
-     */
-    public List<SocialAccountBean> getUserLoggedVerifiedTwitterAccount(final String username, final SocialProvider provider)
-             throws EnMeNoResultsFoundException{
-        final List<SocialAccountBean> socialAccounts = ConvertDomainBean.convertListSocialAccountsToBean(getAccountDao()
-                .getTwitterVerifiedAccountByUser(getUserAccount(username).getAccount(), provider));
-        log.debug("social provider verified "+socialAccounts.size());
-        return socialAccounts;
-   }
-
-    /**
      * Invite some users to register in the system.
      * @param email list of users
      * @param code code
      * @return default user permission.
      */
     public String getDefaultUserPermission() {
-        return  DEFAULT;
+        return  DEFAULT.name();
     }
 
     /**

File encuestame-business/src/main/java/org/encuestame/business/service/imp/ISecurityService.java

View file
  • Ignore whitespace
 
     /**
      * Get User Logged Twitter Accounts.
+     * @param username
+     * @param provider
      * @return
      * @throws EnMeNoResultsFoundException
      */
-    List<SocialAccountBean> getUserLoggedSocialAccount(final String username) throws EnMeNoResultsFoundException;
+    List<SocialAccountBean> getUserLoggedSocialAccount(
+            final String username
+            , final SocialProvider provider) throws EnMeNoResultsFoundException;
 
     /**
      * Get User Logged Verified Twitter Accounts.

File encuestame-business/src/main/java/org/encuestame/business/service/imp/ITwitterService.java

View file
  • Ignore whitespace
     User verifyCredentials(final String username, final String password) throws TwitterException;
 
     /**
+     * Verify Credentials.
+     * @param socialAccount
+     * @return
+     */
+    Boolean verifyCredentials(final SocialAccount socialAccount);
+
+    /**
      * Get OAuthorized Token.
      * @param socialAccount {@link SocialAccount}.
      * @return {@link Twitter}.

File encuestame-business/src/main/java/org/encuestame/business/service/social/provider/TwitterService.java

View file
  • Ignore whitespace
         //Twitter twitter = new TwitterFactory().getInstance();
         log.debug("publicTweet Before  Token  {"+socialTwitterAccount.getToken());
         log.debug("publicTweet Before Secret Token  {"+socialTwitterAccount.getSecretToken());
-        final AccessToken accessToken = this.createNewOAuthAccessToken(socialTwitterAccount);
-        log.debug("Access Token "+accessToken);
-        final Twitter twitter = this.getOAuthAuthorizedInstance(socialTwitterAccount, accessToken);
+        final Twitter twitter = this.getTwitterInsstance(socialTwitterAccount);
         log.debug("Verify  "+twitter.verifyCredentials());
         log.debug("Update Status "+tweet);
         return twitter.updateStatus(tweet);
     }
 
     /**
+     *
+     * @param socialTwitterAccount
+     * @return
+     */
+    public Twitter getTwitterInsstance(final SocialAccount socialTwitterAccount){
+        final AccessToken accessToken = this.createNewOAuthAccessToken(socialTwitterAccount);
+        log.debug("Access Token "+accessToken);
+        return this.getOAuthAuthorizedInstance(socialTwitterAccount, accessToken);
+    }
+
+    /**
+     * Verify Credentials.
+     * @param socialAccount
+     * @return
+     */
+    public Boolean verifyCredentials(final SocialAccount socialAccount){
+        final Twitter twitter = this.getTwitterInsstance(socialAccount);
+        final Boolean confirmed = twitter.isOAuthEnabled();
+        log.debug("Twitter Account "+socialAccount.getSocialAccountName()+ " is confirmed? "+confirmed);
+        return confirmed;
+    }
+
+    /**
      * Create New OAuth Access Token.
      * @param socialTwitterAccount {@link SocialAccount}.
      * @return {@link AccessToken}.

File encuestame-business/src/test/java/org/encuestame/test/business/service/TestSecurityService.java

View file
  • Ignore whitespace
 import org.encuestame.persistence.domain.security.Account;
 import org.encuestame.persistence.domain.security.UserAccount;
 import org.encuestame.persistence.domain.security.SocialAccount;
+import org.encuestame.persistence.domain.social.SocialProvider;
 import org.encuestame.persistence.domain.EnMePermission;
 import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
 import org.encuestame.persistence.exception.EnMeExpcetion;
     @Ignore
     public void testaddNewTwitterAccount() throws EnMeNoResultsFoundException{
         //this.securityService.addNewTwitterAccount("encuestameTest", this.secUserSecondary.getUsername());
-        assertEquals(getAccountDao().getTwitterAccountByUser(this.userPrimary).size(), 1);
+        assertEquals(getAccountDao().getTwitterAccountByUser(this.userPrimary, SocialProvider.SocialProvider.TWITTER).size(), 1);
     }
 
     /**

File encuestame-business/src/test/java/org/encuestame/test/business/service/TestTweetPollService.java

View file
  • Ignore whitespace
 import org.apache.commons.lang.RandomStringUtils;
 import org.encuestame.business.service.imp.ITweetPollService;
 import org.encuestame.persistence.domain.Question;
+import org.encuestame.persistence.domain.social.SocialProvider;
 import org.encuestame.persistence.domain.survey.QuestionPattern;
 import org.encuestame.persistence.domain.security.Account;
 import org.encuestame.persistence.domain.security.UserAccount;
     @Test
     public void testPublicMultiplesTweetAccounts(){
             createDefaultSettedTwitterAccount(this.userAccount.getAccount());
-            final List<SocialAccount> list = getAccountDao().getTwitterAccountByUser(this.userAccount.getAccount());
+            final List<SocialAccount> list = getAccountDao().getTwitterAccountByUser(this.userAccount.getAccount(), SocialProvider.TWITTER);
             final List<SocialAccountBean> listUnitTwitterAccount = ConvertDomainBean.convertListSocialAccountsToBean(list);
              final String tweetText = RandomStringUtils.randomAlphabetic(5);
             final TweetPoll tweetPoll = createTweetPollPublicated(true, true, new Date(), this.user, question);

File encuestame-mvc/src/main/java/org/encuestame/mvc/controller/social/json/SocialAccountsJsonController.java

View file
  • Ignore whitespace
-
 package org.encuestame.mvc.controller.social.json;
 
 import java.io.IOException;
     @RequestMapping(value = "/api/social/twitter/account/{type}.json", method = RequestMethod.GET)
     public ModelMap actionTwitterAccount(
             @PathVariable String type,
-            @RequestParam(value = "consumerKey", required = true) String consumerKey,
-            @RequestParam(value = "consumerSecret", required = true) String consumerSecret,
-            @RequestParam(value = "username", required = true) String usernameAccount,
-            @RequestParam(value = "socialAccountId", required = false) String socialAccountId,
+            @RequestParam(value = "socialAccountId", required = true) String socialAccountId,
             HttpServletRequest request,
             HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
-         log.debug("consumerKey "+consumerKey);
-         log.debug("consumerSecret "+ (consumerSecret));
          try {
            final UserAccount userAccount = getUserAccount();
-           if("create".equals(type)){
-               //getSecurityService().addNewTwitterAccount(userAccount, usernameAccount, consumerKey, consumerSecret);
-               setSuccesResponse();
-           } else if("update".equals(type)){
+           if("default".equals(type)){
               log.info("update social twitter account");
+           } else if("remove".equals(type)){
+
+           } else if("valid".equals(type)){
+
            } else {
                setError("type not valid", response);
            }
      * @throws IOException
      */
     @PreAuthorize("hasRole('ENCUESTAME_USER')")
-    @RequestMapping(value = "/api/common/social/valid-accounts.json", method = RequestMethod.GET)
+    @RequestMapping(value = "/api/common/social/confirmed-accounts.json", method = RequestMethod.GET)
     public ModelMap get(
             HttpServletRequest request,
             HttpServletResponse response,
     }
 
     /**
+     * Return Social Valid Accounts.
+     * @param request
+     * @param response
+     * @param provider
+     * @return
+     * @throws JsonGenerationException
+     * @throws JsonMappingException
+     * @throws IOException
+     */
+    @PreAuthorize("hasRole('ENCUESTAME_USER')")
+    @RequestMapping(value = "/api/common/social/accounts.json", method = RequestMethod.GET)
+    public ModelMap getSocialAccountByType(
+            HttpServletRequest request,
+            HttpServletResponse response,
+            @RequestParam(value = "provider", required = false) String provider)
+            throws JsonGenerationException, JsonMappingException, IOException {
+        try {
+             final List<SocialAccountBean> accounts = getSecurityService()
+                   .getUserLoggedSocialAccount(getUserPrincipalUsername(), SocialProvider.getProvider(provider));
+             setItemReadStoreResponse("socialAccounts", "id", accounts);
+             log.debug("Twitter Accounts Loaded");
+        } catch (Exception e) {
+            log.error(e);
+            e.printStackTrace();
+            setError(e.getMessage(), response);
+        }
+        return returnData();
+    }
+
+    /**
      * Get Twitter Pin Url.
      * @param ping
      * @param consumerKey

File encuestame-persistence/src/main/java/org/encuestame/persistence/dao/IAccountDao.java

View file
  • Ignore whitespace
     /**
      * Get Twitter Accounts.
      * @param secUsers {@link Account}.
+     * @param provider
      * @return List {@link SocialAccount}.
      *
      */
-    List<SocialAccount> getTwitterAccountByUser(final Account secUsers);
+    List<SocialAccount> getTwitterAccountByUser(final Account secUsers,
+            final SocialProvider provider);
 
     /**
      * Get Twitter Account.

File encuestame-persistence/src/main/java/org/encuestame/persistence/dao/imp/AccountDaoImp.java

View file
  • Ignore whitespace
     /**
      * Get Twitter Accounts.
      * @param secUsers {@link Account}.
+     * @param provider
      * @return List {@link SocialAccount}.
      *
      */
-    public List<SocialAccount> getTwitterAccountByUser(final Account secUsers){
+    public List<SocialAccount> getTwitterAccountByUser(
+            final Account secUsers,
+            final SocialProvider provider){
         final DetachedCriteria criteria = DetachedCriteria.forClass(SocialAccount.class);
         criteria.add(Restrictions.eq("secUsers", secUsers) );
+        if (provider != null) { //if provider is null, we fetch everything
+            criteria.add(Restrictions.eq("accounType", provider));
+        }
         return   getHibernateTemplate().findByCriteria(criteria);
     }
 

File encuestame-persistence/src/main/java/org/encuestame/persistence/domain/EnMePermission.java

View file
  • Ignore whitespace
     ENCUESTAME_PUBLISHER,
     ENCUESTAME_EDITOR,
     ENCUESTAME_ANONYMOUS,
+    ENCUESTAME_API,
+    ENCUESTAME_READ,
+    ENCUESTAME_WRITE,
 
-    EnMePermission(){
-        //Constructor.
-    };
+    EnMePermission(){};
 
     /**
      * To String.

File encuestame-war/src/main/webapp/resource/css/social.css

View file
  • Ignore whitespace
 }
 
 div.socialAccounts div.socialWrapper div.listSocialCommunities{
-    float: left;
     min-width: 200px;
 }
 
 }
 
 div.socialAccounts div.socialWrapper  div.socialAccountListDetail{
-    margin-left: 220px;
-    padding: 10px;
+    float: right;
+    width: 1050px;
 }
 
 
 /** Row Account */
 
 div.socialWrapperRow{
-    padding: 7px;
-    font-size: 110%;
-    margin: 2px;
+     padding: 7px;
+     font-size: 110%;
+     margin: 2px;
     -moz-box-shadow: 0px 2px 2px #888;
     -webkit-box-shadow: 0px 2px 2px #888;
-    box-shadow: 10px 10px 5px #888;
+     box-shadow: 10px 10px 5px #888;
     -webkit-border-radius: 0px 0px 5px 5px;
     -moz-border-radius: 0px 0px 5px 5px;
      border-radius: 0px 0px 5px 5px;
      cursor: pointer;
      margin: 10px 0px 10px 0px;
-     min-height: 50px;
+}
+
+div.socialWrapperRow div.socialNewForm{
+    clear: both;
+    position: fixed;
 }
 
 div.socialWrapperRow div.tokensWrapper{
-    float: left;
+    padding: 5px;
+}
+
+div.socialWrapperRow div.tokensWrapper div.tokenHideOptions{
+    min-height: 45px;
 }
 
 div.socialWrapperRow  div.optionToken{
+    text-align: right;
     float: right;
 }
 
 }
 
 /** Twitter Account **/
+
+div.twitterListAccount{
+
+}
+
 div.twitterWrapperRow{
     background-color: #9AE4E8;
 }
 div.twitterWrapperRow div.tokensWrapper label{
     color: #2C4762;
 }
+
+div.twitterListAccount div.newTwitterAccount{
+    padding: 10px;
+}

File encuestame-war/src/main/webapp/resource/js/encuestame/org/core/commons.js

View file
  • Ignore whitespace
 encuestame.service.list.removePermission = encuestame.contextWidget()+"/api/admon/remove-permission.json";
 encuestame.service.list.hashtags = encuestame.contextWidget()+"/api/common/hashtags.json";
 //TODO: replace twitter
-encuestame.service.list.twitterAccount = encuestame.contextWidget()+"/api/common/social/valid-accounts.json";
+encuestame.service.list.twitterAccount = encuestame.contextWidget()+"/api/common/social/confirmed-accounts.json";
+encuestame.service.list.allSocialAccount = encuestame.contextWidget()+"/api/common/social/accounts.json";
 
 //tweetpoll service
 encuestame.service.list.publishTweetPoll = encuestame.contextWidget()+"/api/survey/tweetpoll/publish.json";

File encuestame-war/src/main/webapp/resource/js/encuestame/org/core/commons/social/SocialAccounts.js

View file
  • Ignore whitespace
 dojo.require("dijit.form.Button");
 dojo.require("dijit.form.Form");
 
+dojo.require("dojo.hash");
+
 dojo.declare(
     "encuestame.org.core.commons.social.SocialAccounts",
     [dijit._Widget, dijit._Templated],{
 
             label : "define label",
 
+            widgetsInTemplate: true,
+
             templatePath: dojo.moduleUrl("encuestame.org.core.commons.social", "templates/socialButton.inc"),
 
             postCreate : function(){
+                var hash = dojo.queryToObject(dojo.hash());
+                if (hash.provider && hash.provider == this.id) {
+                    this._loadAccountInterface(hash.provider);
+                }
 
             },
 
-            _click : function(event){
-                console.debug("click button");
-                var widget = dijit.byId(this.id.toLowerCase()+"Detail");
+            _loadAccountInterface : function(id){
+                console.debug("_loadAccountInterface ", id.toLowerCase()+"Detail");
+                var widget = dijit.byId(id.toLowerCase()+"Detail");
                 console.debug("widget ", widget);
                 dojo.publish("/encuestame/social/change", [widget]);
-                dojo.publish("/encuestame/social/"+this.id+"/loadAccounts");
+                dojo.publish("/encuestame/social/"+id+"/loadAccounts");
+            },
+
+            _click : function(event){
+                var hash = dojo.queryToObject(dojo.hash());
+                console.debug("click button");
+                this._loadAccountInterface(this.id);
+                params = {
+                   provider : this.id
+                };
+                dojo.hash(dojo.objectToQuery(params));
             }
  });
 
                     console.debug("error", error);
                 };
                 encuestame.service.xhrGet(
-                        encuestame.service.list.twitterAccount, {}, load, error);
+                        encuestame.service.list.allSocialAccount, {}, load, error);
             },
 
 
 
             widgetsInTemplate: true,
 
+            _secrets : false,
+
             type : "twitter",
 
             postCreate : function(){
               console.debug("account", this.account);
+              dojo.subscribe("/encuestame/social/account/row/show", this, function(widget){
+                  console.debug(this.id, widget.id);
+                  if (this.id != widget.id) {
+                      console.debug("hiding ...", widget.id);
+                      this._secrets = true;
+                      this._showHideAction();
+                  } else {
+
+                  }
+              });
             },
 
             _disableSocialAccount : function(){
 
             _remove : function(event){
                 dojo.stopEvent(event);
+
             },
 
             _changeStatusAccount : function(){
                 dojo.stopEvent(event);
+            },
+
+            _showHideAction : function(){
+                console.debug("_showHideAction ", this);
+                if(this._secrets){
+                    dojo.addClass(this._secretView, "defaultDisplayHide");
+                } else {
+                    dojo.removeClass(this._secretView, "defaultDisplayHide");
+                }
+                this._secrets = !this._secrets;
+            },
+
+            _showHideSecrets : function(event){
+                dojo.stopEvent(event);
+                this._showHideAction();
+                dojo.publish("/encuestame/social/account/row/show", [this]);
             }
 });
 

File encuestame-war/src/main/webapp/resource/js/encuestame/org/core/commons/social/templates/socialAccountRow.inc

View file
  • Ignore whitespace
 <div class="${type}WrapperRow socialWrapperRow">
-    <div dojoType="dijit.form.Form">
-        <div class="optionToken">
-                <a href="#"  dojoAttachEvent="onclick:_remove">Remove</a><br/>
-                <a href="#"  dojoAttachEvent="onclick:_changeStatusAccount">Enable/Disable Account</a><br/>
-        </div>
-        <div class="title">${account.account}</div>
-        <div class="tokensWrapper">
-            <label for="consumer">Secret Token</label>
-            <input type="text" name="${id}_secretToken" id="${id}_secretToken"
-                                dojoType="dijit.form.ValidationTextBox"
-                                required="true"
-                                invalidMessage="Consumer Secret is Required"
-                                value="${account.secretToken}"
-                                selectOnClick="true">
-             <label for="consumer">Token</label>
-             <input type="text" name="${id}_token" id="${id}_token"
-                                dojoType="dijit.form.ValidationTextBox"
-                                required="true"
-                                invalidMessage="Token is Required"
-                                value="${account.token}"
-                                selectOnClick="true">
+    <div dojoType="dijit.form.Form" class="socialNewForm">
+        <table  dojoAttachEvent="onclick:_showHideSecrets">
+            <tr>
+                <td>
+                    <div class="title">${account.account}</div>
+                </td>
+                <td>
+                    <a href="#"  dojoAttachEvent="onclick:_showHideSecrets">Show Details</a><br/>
+                </td>
+            </tr>
+        </table>
+        <div class="tokensWrapper defaultDisplayHide" dojoAttachPoint="_secretView">
+            <div class="tokenHideOptions">
+                <div class="optionToken">
+                      <button id="${id}_remove" dojoType="dijit.form.Button" type="button" dojoAttachEvent="onClick:_remove">
+                               Remove
+                      </button>
+                      <button id="${id}_statusAccount" dojoType="dijit.form.Button" type="button" dojoAttachEvent="onClick:_changeStatusAccount">
+                               Disable
+                      </button>
+                      <button id="${id}_default" dojoType="dijit.form.Button" type="button" dojoAttachEvent="onClick:_changeStatusAccount">
+                               Set as Default
+                      </button>
+                </div>
+                <table>
+                    <tr>
+                        <td>
+                            <label>Secret Token</label>
+                        </td>
+                         <td>
+                            <input type="text" name="${id}_secretToken" id="${id}_secretToken"
+                                        dojoType="dijit.form.ValidationTextBox"
+                                        required="true"
+                                        style="width:400px;"
+                                        invalidMessage="Consumer Secret is Required"
+                                        value="${account.secretToken}"
+                                        selectOnClick="true">
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>
+                           <label> Token</label>
+                        </td>
+                         <td>
+                             <input type="text" name="${id}_token" id="${id}_token"
+                                        dojoType="dijit.form.ValidationTextBox"
+                                        required="true"
+                                        style="width:400px;"
+                                        invalidMessage="Token is Required"
+                                        value="${account.token}"
+                                        selectOnClick="true">
+                        </td>
+                    </tr>
+                     <tr>
+                        <td>
+                            <label>Profile Url</label>
+                        </td>
+                        <td>
+                            <a href="#" target="_blank">http://twitter.com/xxxxx</a>
+                        </td>
+                     </tr>
+               </table>
+            </div>
          </div>
     </div>
 </div>

File encuestame-war/src/main/webapp/resource/js/encuestame/org/core/commons/social/templates/socialAccounts.inc

View file
  • Ignore whitespace
 <div class="socialAccounts">
 
     <div class="socialWrapper">
-        <div class="listSocialCommunities">
-             <div id="twitter" dojoType="encuestame.org.core.commons.social.SocialButton" label="Twitter"></div>
-             <div id="facebook" dojoType="encuestame.org.core.commons.social.SocialButton" label="Facebook"></div>
-             <div id="linkedin" dojoType="encuestame.org.core.commons.social.SocialButton" label="Linked In"></div>
-             <div id="google" dojoType="encuestame.org.core.commons.social.SocialButton" label="Google Buzz"></div>
-        </div>
         <div class="socialAccountListDetail" dojoAttachPoint="_detail">
-                <div>
-                    INFO ACCOUNTS
-                </div>
                 <div id="twitterDetail" dojoType="encuestame.org.core.commons.social.SocialAccountTwitterDetail" class="defaultDisplayHide"></div>
                 <div id="facebookDetail" dojoType="encuestame.org.core.commons.social.SocialAccountFacebookDetail" class="defaultDisplayHide"></div>
                 <div id="linkedinDetail" dojoType="encuestame.org.core.commons.social.SocialAccountLinkedInDetail" class="defaultDisplayHide"></div>
                 <div id="googleDetail" dojoType="encuestame.org.core.commons.social.SocialAccountGoogleBuzzDetail" class="defaultDisplayHide"></div>
         </div>
+        <div class="listSocialCommunities">
+             <div id="twitter" dojoType="encuestame.org.core.commons.social.SocialButton" label="Twitter"></div>
+             <div id="facebook" dojoType="encuestame.org.core.commons.social.SocialButton" label="Facebook"></div>
+             <div id="linkedin" dojoType="encuestame.org.core.commons.social.SocialButton" label="Linked In"></div>
+             <div id="google" dojoType="encuestame.org.core.commons.social.SocialButton" label="Google Buzz"></div>
+        </div>
     </div>
 
 <div>

File encuestame-war/src/main/webapp/resource/js/encuestame/org/core/commons/social/templates/twitterAccounts.inc

View file
  • Ignore whitespace
-<div>
-        <div>
-             <a href="#" dojoAttachEvent="onclick:_autorize"  dojoAttachPoint="_addTitle">Add new Twitter Account</a>
-             <div class="newTwitterAccount ">
-                    <div id="twitterNewAccountForm" dojoType="dijit.form.Form" class="defaultDisplayHide" dojoAttachPoint="_form">
-                         <label for="_newTwitterAccount">Pin</label>
-                         <input type="text" name="_pin" id="_pin"
-                                dojoType="dijit.form.ValidationTextBox"
-                                required="true"
-                                invalidMessage="Pin is Required"
-                                class="defaultDisplayHide"
-                                selectOnClick="true">
-                        <button id="_authorize" dojoType="dijit.form.Button" type="button" dojoAttachEvent="onClick:_autorizeOpen">
-                            Click to Open Authorize Window
-                        </button>
-                        <button id="_validate" dojoType="dijit.form.Button" type="button" class="defaultDisplayHide" dojoAttachEvent="onClick:_validatePin">
-                            Validate
-                        </button>
-                    </div>
-             </div>
-        </div>
-        <div class="twitterAccounts" dojoAttachPoint="_list">
-
-        </div>
+<div class="twitterListAccount">
+     <a href="#" dojoAttachEvent="onclick:_autorize" dojoAttachPoint="_addTitle">Add new Twitter Account</a>
+     <div class="newTwitterAccount">
+            <div id="twitterNewAccountForm" dojoType="dijit.form.Form" class="defaultDisplayHide" dojoAttachPoint="_form">
+                 <label for="_newTwitterAccount">Pin</label>
+                 <input type="text" name="_pin" id="_pin"
+                        dojoType="dijit.form.ValidationTextBox"
+                        required="true"
+                        invalidMessage="Pin is Required"
+                        class="defaultDisplayHide"
+                        selectOnClick="true">
+                <button id="_authorize" dojoType="dijit.form.Button" type="button" dojoAttachEvent="onClick:_autorizeOpen">
+                    Click to Open Authorize Window
+                </button>
+                <button id="_validate" dojoType="dijit.form.Button" type="button" class="defaultDisplayHide" dojoAttachEvent="onClick:_validatePin">
+                    Validate
+                </button>
+            </div>
+     </div>
+    <div class="twitterAccounts" dojoAttachPoint="_list"></div>
 </div>