From c7668dda938d2fadfca9f7968b5052e8b7b2af27 Mon Sep 17 00:00:00 2001 From: Costantino Perciante Date: Wed, 25 May 2016 13:05:07 +0000 Subject: [PATCH] Servlet code optimized. Mention of group of people is now available using "@" annotation. Common utilities have been put into the social-util-library (added into the pom xml) git-svn-id: https://svn.research-infrastructures.eu/d4science/gcube/trunk/portlets/user/share-updates@128825 82a268e6-3cf1-43bd-a215-b396298e98cf --- .classpath | 1 + .settings/org.eclipse.wst.common.component | 3 + pom.xml | 6 + .../client/ShareUpdateService.java | 2 +- .../client/ShareUpdateServiceAsync.java | 2 +- .../client/view/SuperPosedTextArea.java | 6 +- .../server/ShareUpdateServiceImpl.java | 298 ++++++++++-------- .../server/TextTransfromUtils.java | 176 ----------- 8 files changed, 175 insertions(+), 319 deletions(-) diff --git a/.classpath b/.classpath index 6e74f86..74b4a5c 100644 --- a/.classpath +++ b/.classpath @@ -31,5 +31,6 @@ + diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index bbf0648..7dc47c7 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -5,6 +5,9 @@ + + uses + diff --git a/pom.xml b/pom.xml index 4f28914..e2ca945 100644 --- a/pom.xml +++ b/pom.xml @@ -112,6 +112,12 @@ pickitem-widget [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) + + org.gcube.socialnetworking + social-util-library + 1.0.0-SNAPSHOT + compile + org.gcube.portlets.widgets fileupload-progress-bar diff --git a/src/main/java/org/gcube/portlets/user/shareupdates/client/ShareUpdateService.java b/src/main/java/org/gcube/portlets/user/shareupdates/client/ShareUpdateService.java index 945b6ba..d76ccc6 100644 --- a/src/main/java/org/gcube/portlets/user/shareupdates/client/ShareUpdateService.java +++ b/src/main/java/org/gcube/portlets/user/shareupdates/client/ShareUpdateService.java @@ -29,7 +29,7 @@ public interface ShareUpdateService extends RemoteService { LinkPreview checkUploadedFile(String fileName, String fileabsolutePathOnServer); - ArrayList getPortalUsers(); + ArrayList getPortalItemBeans(); ArrayList getHashtags(); } diff --git a/src/main/java/org/gcube/portlets/user/shareupdates/client/ShareUpdateServiceAsync.java b/src/main/java/org/gcube/portlets/user/shareupdates/client/ShareUpdateServiceAsync.java index f1c5cd9..e9f9191 100644 --- a/src/main/java/org/gcube/portlets/user/shareupdates/client/ShareUpdateServiceAsync.java +++ b/src/main/java/org/gcube/portlets/user/shareupdates/client/ShareUpdateServiceAsync.java @@ -21,7 +21,7 @@ public interface ShareUpdateServiceAsync { void getUserSettings(AsyncCallback callback); - void getPortalUsers(AsyncCallback> callback); + void getPortalItemBeans(AsyncCallback> callback); void checkUploadedFile(String fileName, String fileabsolutePathOnServer, AsyncCallback callback); diff --git a/src/main/java/org/gcube/portlets/user/shareupdates/client/view/SuperPosedTextArea.java b/src/main/java/org/gcube/portlets/user/shareupdates/client/view/SuperPosedTextArea.java index d49b36e..5383b22 100644 --- a/src/main/java/org/gcube/portlets/user/shareupdates/client/view/SuperPosedTextArea.java +++ b/src/main/java/org/gcube/portlets/user/shareupdates/client/view/SuperPosedTextArea.java @@ -52,10 +52,10 @@ public class SuperPosedTextArea extends TextArea { sinkEvents(Event.ONKEYDOWN); sinkEvents(Event.ONKEYUP); //get the users - shareupdateService.getPortalUsers(new AsyncCallback>() { + shareupdateService.getPortalItemBeans(new AsyncCallback>() { @Override - public void onSuccess(ArrayList users) { - pickUserDlg = new PickItemsDialog('@', users, eventBus, 525); + public void onSuccess(ArrayList beans) { + pickUserDlg = new PickItemsDialog('@', beans, eventBus, 525); pickUserDlg.withPhoto(); } @Override diff --git a/src/main/java/org/gcube/portlets/user/shareupdates/server/ShareUpdateServiceImpl.java b/src/main/java/org/gcube/portlets/user/shareupdates/server/ShareUpdateServiceImpl.java index 037c9fc..68a8b8c 100644 --- a/src/main/java/org/gcube/portlets/user/shareupdates/server/ShareUpdateServiceImpl.java +++ b/src/main/java/org/gcube/portlets/user/shareupdates/server/ShareUpdateServiceImpl.java @@ -10,8 +10,10 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.UUID; import javax.net.ssl.HttpsURLConnection; @@ -53,10 +55,13 @@ import org.gcube.portlets.user.shareupdates.shared.LinkPreview; import org.gcube.portlets.user.shareupdates.shared.UploadedFile; import org.gcube.portlets.user.shareupdates.shared.UserSettings; import org.gcube.portlets.widgets.pickitem.shared.ItemBean; +import org.gcube.social_networking.socialutillibrary.Utils; import org.gcube.vomanagement.usermanagement.GroupManager; import org.gcube.vomanagement.usermanagement.UserManager; import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault; +import org.gcube.vomanagement.usermanagement.exception.TeamRetrievalFault; import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException; +import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault; import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; @@ -117,7 +122,7 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar } public String getDevelopmentUser() { String user = TEST_USER; -// user = "costantino.perciante"; + // user = "costantino.perciante"; return user; } /** @@ -143,18 +148,18 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar Long vreOrgId, LinkPreview preview, String urlThumbnail, ArrayList mentionedUserFullNames, boolean notifyGroup) { // escape text - String escapedFeedText = TextTransfromUtils.escapeHtmlAndTransformUrl(postText); + String escapedFeedText = Utils.escapeHtmlAndTransformUrl(postText); // get hashtags - List hashtags = TextTransfromUtils.getHashTags(postText); + List hashtags = Utils.getHashTags(postText); if (hashtags != null && !hashtags.isEmpty()) - escapedFeedText = TextTransfromUtils.convertHashtagsAnchorHTML(escapedFeedText, hashtags); + escapedFeedText = Utils.convertHashtagsAnchorHTML(escapedFeedText, hashtags); // retrieve mentioned users ArrayList mentionedUsers = null; if (mentionedUserFullNames != null && ! mentionedUserFullNames.isEmpty()) { mentionedUsers = getSelectedUserIds(mentionedUserFullNames); - escapedFeedText = TextTransfromUtils.convertMentionPeopleAnchorHTML(escapedFeedText, mentionedUsers, getThreadLocalRequest()); + escapedFeedText = Utils.convertMentionPeopleAnchorHTML(escapedFeedText, mentionedUsers, getThreadLocalRequest()); } // get session @@ -234,7 +239,8 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar } //save the feed _log.trace("Success writing onto " + vreScope2Set); } - if (!result) return null; + if (!result) + return null; //everything went fine ClientFeed cf = new ClientFeed(toShare.getKey(), toShare.getType().toString(), username, feedDate, toShare.getUri(), @@ -242,35 +248,18 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar toShare.getUriThumbnail(), toShare.getLinkHost(), null); - //send the notification about this posts to everyone in the group if notifyGroup is true - if (pLevel == PrivacyLevel.SINGLE_VRE && vreOrgId != null && notifyGroup) { - NotificationsManager nm = new ApplicationNotificationsManager( - new SocialNetworkingSite(getThreadLocalRequest()), - vreScope2Set, - new SocialNetworkingUser(username, email, fullName, thumbnailAvatarURL), - NEWS_FEED_PORTLET_CLASSNAME); - Thread thread = new Thread(new PostNotificationsThread(toShare.getKey(), escapedFeedText, ""+vreOrgId, nm, hashtags)); - thread.start(); + // check if is needed to notify people in the vre + notifyPeopleGroup(pLevel, vreOrgId, notifyGroup, username, email, fullName, thumbnailAvatarURL, toShare, hashtags, vreScope2Set, escapedFeedText); - } //send the notification to the mentioned users - if (mentionedUsers != null && mentionedUsers.size() > 0) { - NotificationsManager nm = new ApplicationNotificationsManager( - new SocialNetworkingSite(getThreadLocalRequest()), - vreScope2Set, - new SocialNetworkingUser(username, email, fullName, thumbnailAvatarURL), - NEWS_FEED_PORTLET_CLASSNAME); - ArrayList toPass = new ArrayList(); - for (ItemBean u : mentionedUsers) { - toPass.add(new GenericItemBean(u.getId(), u.getName(), u.getAlternativeName(), u.getThumbnailURL())); - } - Thread thread = new Thread(new MentionNotificationsThread(toShare.getKey(), escapedFeedText, nm, null, toPass)); - thread.start(); - } + if (mentionedUsers != null && mentionedUsers.size() > 0) + notifyMentionedUsers(vreScope2Set, mentionedUsers, username, email, fullName, thumbnailAvatarURL, toShare, escapedFeedText); + return cf; } + /** * Share a post with at least one attachment. */ @@ -280,18 +269,18 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar ArrayList mentionedUserFullNames, boolean notifyGroup, boolean saveCopyWokspace) { // escape text - String escapedFeedText = TextTransfromUtils.escapeHtmlAndTransformUrl(feedText); + String escapedFeedText = Utils.escapeHtmlAndTransformUrl(feedText); // get the list of hashtags - List hashtags = TextTransfromUtils.getHashTags(feedText); + List hashtags = Utils.getHashTags(feedText); if (hashtags != null && !hashtags.isEmpty()) - escapedFeedText = TextTransfromUtils.convertHashtagsAnchorHTML(escapedFeedText, hashtags); + escapedFeedText = Utils.convertHashtagsAnchorHTML(escapedFeedText, hashtags); // get the list of mentioned users ArrayList mentionedUsers = null; if (mentionedUserFullNames != null && ! mentionedUserFullNames.isEmpty()) { mentionedUsers = getSelectedUserIds(mentionedUserFullNames); - escapedFeedText = TextTransfromUtils.convertMentionPeopleAnchorHTML(escapedFeedText, mentionedUsers, getThreadLocalRequest()); + escapedFeedText = Utils.convertMentionPeopleAnchorHTML(escapedFeedText, mentionedUsers, getThreadLocalRequest()); } ASLSession session = getASLSession(); @@ -333,29 +322,27 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar firstAttachmentDescription = firstAttachment.getDescription(); firstAttachmentFormat = firstAttachment.getFormat(); firstAttachmentDownloadUrl = firstAttachment.getDownloadUrl(); - firstAttachmenturlThumbnail = - firstAttachment.getThumbnailUrl() != null ? - firstAttachment.getThumbnailUrl() : firstAttachmenturlThumbnail; + firstAttachmenturlThumbnail = firstAttachment.getThumbnailUrl() != null ? firstAttachment.getThumbnailUrl() : firstAttachmenturlThumbnail; - // check if there are more files - if(uploadedFiles.size() > 1){ + // check if there are more files + if(uploadedFiles.size() > 1){ - attachments = new ArrayList<>(); + attachments = new ArrayList<>(); - // starting from 1 - for (int i = 1; i < uploadedFiles.size(); i++){ - UploadedFile file = uploadedFiles.get(i); + // starting from 1 + for (int i = 1; i < uploadedFiles.size(); i++){ + UploadedFile file = uploadedFiles.get(i); - attachments.add(new Attachment( - UUID.randomUUID().toString(), - file.getDownloadUrl(), - file.getFileName(), - file.getDescription(), - file.getThumbnailUrl(), - file.getFormat()) - ); - } - } + attachments.add(new Attachment( + UUID.randomUUID().toString(), + file.getDownloadUrl(), + file.getFileName(), + file.getDescription(), + file.getThumbnailUrl(), + file.getFormat()) + ); + } + } } @@ -364,11 +351,9 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar String textToPost = ""; //this means the user has shared a file without text in it. - - _log.debug("Url vale " + firstAttachmentDownloadUrl); if (escapedFeedText.trim().compareTo(ShareUpdateForm.NO_TEXT_FILE_SHARE) == 0) { if(uploadedFiles.size() <= 1){ - textToPost = TextTransfromUtils.convertFileNameAnchorHTML(firstAttachmentDownloadUrl); + textToPost = Utils.convertFileNameAnchorHTML(firstAttachmentDownloadUrl); } else{ StringBuilder sb = new StringBuilder(); @@ -449,6 +434,41 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar toShare.getUriThumbnail(), toShare.getLinkHost(), attachments); + // check if is needed to notify people in the vre + notifyPeopleGroup(pLevel, vreOrgId, notifyGroup, username, email, fullName, thumbnailAvatarURL, toShare, hashtags, vreScope2Set, textToPost); + + //send the notification to the mentioned users + if (mentionedUsers != null && mentionedUsers.size() > 0) + notifyMentionedUsers(vreScope2Set, mentionedUsers, username, email, fullName, thumbnailAvatarURL, toShare, textToPost); + + //it means I also should upload a copy of the files on the user's Workspace root folder + if (saveCopyWokspace) + saveCopyIntoWorkSpace(fullName, username, uploadedFiles); + + + return cf; + + } + + /** + * Check if vre notification must be performed and does it. + * @param pLevel + * @param vreOrgId + * @param notifyGroup + * @param username + * @param email + * @param fullName + * @param thumbnailAvatarURL + * @param toShare + * @param hashtags + * @param vreScope2Set + * @param postText + */ + private void notifyPeopleGroup(PrivacyLevel pLevel, Long vreOrgId, + boolean notifyGroup, String username, String email, + String fullName, String thumbnailAvatarURL, Feed toShare, + List hashtags, String vreScope2Set, String postText) { + //send the notification about this posts to everyone in the group if notifyGroup is true if (pLevel == PrivacyLevel.SINGLE_VRE && vreOrgId != null && notifyGroup) { NotificationsManager nm = new ApplicationNotificationsManager( @@ -456,41 +476,92 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar vreScope2Set, new SocialNetworkingUser(username, email, fullName, thumbnailAvatarURL), NEWS_FEED_PORTLET_CLASSNAME); - Thread thread = new Thread(new PostNotificationsThread(toShare.getKey(), textToPost, ""+vreOrgId, nm, hashtags)); + Thread thread = new Thread(new PostNotificationsThread(toShare.getKey(), postText, ""+vreOrgId, nm, hashtags)); thread.start(); } - //send the notification to the mentioned users - if (mentionedUsers != null && mentionedUsers.size() > 0) { - NotificationsManager nm = new ApplicationNotificationsManager( - new SocialNetworkingSite(getThreadLocalRequest()), - vreScope2Set, - new SocialNetworkingUser(username, email, fullName, thumbnailAvatarURL), - NEWS_FEED_PORTLET_CLASSNAME); - ArrayList toPass = new ArrayList(); - for (ItemBean u : mentionedUsers) { - toPass.add(new GenericItemBean(u.getId(), u.getName(), u.getAlternativeName(), u.getThumbnailURL())); - } - Thread thread = new Thread(new MentionNotificationsThread(toShare.getKey(), textToPost, nm, null, toPass)); - thread.start(); + } + + /** + * Save copy of the file(s) into the workspace + * @param fullName + * @param username + * @param uploadedFiles + */ + private void saveCopyIntoWorkSpace(String fullName, String username, ArrayList uploadedFiles){ + + for(UploadedFile file: uploadedFiles){ + new Thread( + new UploadToWorkspaceThread( + fullName, + username, + file.getFileName(), + file.getFileAbsolutePathOnServer())) + .start(); } + } - //it means I also should upload a copy of the files on the user's Workspace root folder - if (saveCopyWokspace) { + /** + * Common method to notify users. + * @param vreScope2Set + * @param mentionedUsers + * @param username + * @param email + * @param fullName + * @param thumbnailAvatarURL + */ + private void notifyMentionedUsers(String vreScope2Set, ArrayList mentionedUsers, String username, String email, String fullName, String thumbnailAvatarURL, + Feed toShare, String escapedFeedText){ + + NotificationsManager nm = new ApplicationNotificationsManager( + new SocialNetworkingSite(getThreadLocalRequest()), + vreScope2Set, + new SocialNetworkingUser(username, email, fullName, thumbnailAvatarURL), + NEWS_FEED_PORTLET_CLASSNAME); + ArrayList toPass = new ArrayList(); + // among the mentionedUsers there could be groups of people + Map uniqueUsersToNotify = new HashMap<>(); + UserManager um = new LiferayUserManager(); + + for (ItemBean bean : mentionedUsers) { + + if(bean.isItemGroup()){ + + // retrieve the users of this group + try { + List teamUsers = um.listUsersByTeam(Long.parseLong(bean.getId())); + + for (GCubeUser userTeam : teamUsers) { + if(!uniqueUsersToNotify.containsKey(userTeam.getUsername())) + uniqueUsersToNotify.put(userTeam.getUsername(), new ItemBean(userTeam.getUserId()+"", + userTeam.getUsername(), userTeam.getFullname(), userTeam.getUserAvatarURL())); + } + + } catch (NumberFormatException + | UserManagementSystemException + | TeamRetrievalFault | UserRetrievalFault e) { + _log.error("Unable to retrieve team information", e); + } + + }else{ + // it is a user, just add to the hashmap + if(!uniqueUsersToNotify.containsKey(bean.getName())) + uniqueUsersToNotify.put(bean.getName(), bean); - for(UploadedFile file: uploadedFiles){ - new Thread( - new UploadToWorkspaceThread( - fullName, - username, - file.getFileName(), - file.getFileAbsolutePathOnServer())) - .start(); } } - return cf; + // iterate over the hashmap + Iterator> userMapIterator = uniqueUsersToNotify.entrySet().iterator(); + while (userMapIterator.hasNext()) { + Map.Entry user = (Map.Entry) userMapIterator + .next(); + ItemBean userBean = user.getValue(); + toPass.add(new GenericItemBean(userBean.getId(), userBean.getName(), userBean.getAlternativeName(), userBean.getThumbnailURL())); + } + Thread thread = new Thread(new MentionNotificationsThread(toShare.getKey(), escapedFeedText, nm, null, toPass)); + thread.start(); } @@ -500,7 +571,7 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar ASLSession session = getASLSession(); String username = session.getUsername(); _log.debug("getUserSettings() for " + username); - + String email = username+"@isti.cnr.it"; String fullName = username+" FULL"; String thumbnailURL = "images/Avatar_default.png"; @@ -508,7 +579,7 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar if (isWithinPortal() && username.compareTo(TEST_USER) != 0) { UserManager um = new LiferayUserManager(); GCubeUser user = um.getUserByUsername(username); - + thumbnailURL = user.getUserAvatarURL(); fullName = user.getFullname(); email = user.getEmail(); @@ -652,12 +723,13 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar * Meta "title" and "description" tags * Best guess from page content (not recommended) */ + @SuppressWarnings("restriction") @Override public LinkPreview checkLink(String linkToCheck) { LinkPreview toReturn = null; _log.info("to check " + linkToCheck); //look for a url in text - linkToCheck = TextTransfromUtils.extractURL(linkToCheck); + linkToCheck = Utils.extractURL(linkToCheck); if (linkToCheck == null) return null; //no url @@ -799,10 +871,10 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar if (fullNames == null) return new ArrayList(); else { - ArrayList allUsers = getPortalUsers(); + ArrayList allbeans = getPortalItemBeans(); ArrayList toReturn = new ArrayList(); for (String fullName : fullNames) - for (ItemBean puser : allUsers) { + for (ItemBean puser : allbeans) { if (puser.getAlternativeName().compareTo(fullName) == 0) { toReturn.add(puser); break; @@ -813,13 +885,14 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar } @Override - public ArrayList getPortalUsers() { + public ArrayList getPortalItemBeans() { ASLSession session = getASLSession(); boolean withinPortal = false; if (isWithinPortal() && session.getUsername().compareTo(TEST_USER) != 0) { withinPortal = true; } - return getOrganizationUsers(session.getScope(), session.getUsername(), withinPortal); + // retrieve user and group beans + return Utils.getDisplayableItemBeans(session.getScope(), session.getUsername(), withinPortal); } @Override @@ -841,55 +914,4 @@ public class ShareUpdateServiceImpl extends RemoteServiceServlet implements Shar } return toReturn; } - - /** - * - * @param session the Asl Session - * @param withinPortal true when is on Liferay portal - * @return the users belonging to the current organization (scope) - */ - public static ArrayList getOrganizationUsers(String scope, String currUser, boolean withinPortal) { - ArrayList portalUsers = new ArrayList(); - try { - if (withinPortal) { - UserManager um = new LiferayUserManager(); - GroupManager gm = new LiferayGroupManager(); - ScopeBean sb = new ScopeBean(scope); - List users = null; - - if (sb.is(Type.INFRASTRUCTURE)) - users = um.listUsersByGroup(gm.getRootVO().getGroupId()); - else if (sb.is(Type.VRE)) { //must be in VRE - //get the name from the scope - String orgName = scope.substring(scope.lastIndexOf("/")+1, scope.length()); - //ask the users - users = um.listUsersByGroup(gm.getGroupId(orgName)); - } - else { - _log.error("Error, you must be in SCOPE VRE OR INFRASTURCTURE, you are in VO SCOPE returning no users"); - return portalUsers; - } - for (GCubeUser user : users) { - if (user.getUsername().compareTo(TEST_USER) != 0 && user.getUsername().compareTo(currUser) != 0) { //skip test.user & current user - portalUsers.add(new ItemBean(user.getUserId()+"", user.getUsername(), user.getFullname(), user.getUserAvatarURL())); - } - } - } - else { //test users - portalUsers.add(new ItemBean("12111", "massimiliano.assante", "Test User #1", "")); - portalUsers.add(new ItemBean("14111", "massimiliano.assante", "Test Second User #2", "")); - portalUsers.add(new ItemBean("11511", "massimiliano.assante", "Test Third User", "")); - portalUsers.add(new ItemBean("11611", "massimiliano.assante", "Test Fourth User", "")); - portalUsers.add(new ItemBean("11711", "massimiliano.assante", "Test Fifth User", "")); - portalUsers.add(new ItemBean("11811", "massimiliano.assante", "Test Sixth User", "")); - portalUsers.add(new ItemBean("15811", "massimiliano.assante", "Ninth Testing User", "")); - portalUsers.add(new ItemBean("15811", "massimiliano.assante", "Eighth Testing User", "")); - portalUsers.add(new ItemBean("11211", "giogio.giorgi", "Seventh Test User", "")); - portalUsers.add(new ItemBean("2222", "pino.pinetti", "Tenth Testing User", "")); - } - } catch (Exception e) { - _log.error("Error in server get all contacts ", e); - } - return portalUsers; - } } diff --git a/src/main/java/org/gcube/portlets/user/shareupdates/server/TextTransfromUtils.java b/src/main/java/org/gcube/portlets/user/shareupdates/server/TextTransfromUtils.java index d3e64f5..caa1535 100644 --- a/src/main/java/org/gcube/portlets/user/shareupdates/server/TextTransfromUtils.java +++ b/src/main/java/org/gcube/portlets/user/shareupdates/server/TextTransfromUtils.java @@ -3,36 +3,24 @@ package org.gcube.portlets.user.shareupdates.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; -import javax.servlet.http.HttpServletRequest; -import org.apache.commons.codec.binary.Base64; -import org.gcube.common.portal.GCubePortalConstants; -import org.gcube.common.portal.PortalContext; -import org.gcube.portal.databook.client.GCubeSocialNetworking; import org.gcube.portlets.user.shareupdates.server.metaseeker.MetaSeeker; import org.gcube.portlets.user.shareupdates.server.opengraph.OpenGraph; import org.gcube.portlets.user.shareupdates.shared.LinkPreview; -import org.gcube.portlets.widgets.pickitem.shared.ItemBean; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.TagNode; import org.htmlparser.beans.StringBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; import com.sun.net.ssl.HttpsURLConnection; /** * this class contains utility method for parsing and trasforming users pasted text containing URLs and other utility methods @@ -46,72 +34,6 @@ public class TextTransfromUtils { */ private static Logger _log = LoggerFactory.getLogger(ShareUpdateServiceImpl.class); - /** - * - * @param preview - * @return - */ - protected static String convertFileNameAnchorHTML(String url) { - StringBuilder sb = new StringBuilder(); - sb.append("shared ").append("a file.").append(" ").toString(); - return sb.toString(); - } - - /** - * convert the mentioned people in HTML anchor and also Encode the params Base64 - * @param escapedFeedText - * @param taggedPeople - * @return - */ - protected static String convertMentionPeopleAnchorHTML(String escapedFeedText, ArrayList taggedPeople, HttpServletRequest request) { - String userProfilePageURL = ""; - userProfilePageURL = PortalContext.getConfiguration().getSiteLandingPagePath(request)+GCubePortalConstants.USER_PROFILE_FRIENDLY_URL; - - for (ItemBean tagged : taggedPeople) { - String taggedHTML = ""+tagged.getAlternativeName()+" "; - escapedFeedText = escapedFeedText.replace(tagged.getAlternativeName(), taggedHTML); - } - return escapedFeedText; - } - /** - * utility method that extract the hashtags from a text - * @param postText - * @return the list of hashtags present in the text - */ - protected static List getHashTags(String postText) { - List hashtags = new ArrayList<>(); - Pattern MY_PATTERN = Pattern.compile("^#\\w+|\\s#\\w+"); - Matcher matcher = MY_PATTERN.matcher(postText); - while (matcher.find()) { - hashtags.add("#"+matcher.group().replace(" ", "").replace("#", "")); - } - return hashtags; - } - /** - * convert the hashtag in HTML anchor and also Encode the params Base64 - * @param escapedFeedText - * @param hashtags - * @return - */ - protected static String convertHashtagsAnchorHTML(String escapedFeedText, List hashtags) { - for (String hashtag : hashtags) { - String taggedHTML = ""+hashtag+""; - //TODO: does not work if the word is no preceeded by # - //dirty trick: double replace because \\boundaries do not accept # char - final String placeholder = "ñöñö-ñöñö"; - String first = escapedFeedText.replaceAll("(?i)\\b"+hashtag.substring(1)+"\\b", placeholder); - escapedFeedText = first.replaceAll("#"+placeholder, taggedHTML); - //this is needed if there is a word equal to an hashtagged one without '#' e.g. #job and job - escapedFeedText = escapedFeedText.replaceAll(placeholder, hashtag.substring(1)); - } - return escapedFeedText; - } - /** * generate the description parsing the content (Best Guess) * @param link the link to check @@ -125,72 +47,6 @@ public class TextTransfromUtils { description = ((description.length() > 256) ? description.substring(0, 256)+"..." : description); return description; } - /** - * Escape an html string. Escaping data received from the client helps to - * prevent cross-site script vulnerabilities. - * - * @param html the html string to escape - * @return the escaped string - */ - protected static String escapeHtmlAndTransformUrl(String html) { - if (html == null) { - return null; - } - String toReturn = html.replaceAll("&", "&").replaceAll("<", "<") - .replaceAll(">", ">"); - - // replace all the line breaks by
- toReturn = toReturn.replaceAll("(\r\n|\n)","
"); - //transfrom the URL in a clickable URL - toReturn = transformUrls(toReturn); - // then replace all the double spaces by the html version   - toReturn = toReturn.replaceAll("\\s\\s","  "); - return toReturn; - } - - /** - * utility method that extract an url ina text when you paste a link - * @param feedText - * @return the text with the clickable url in it - */ - protected static String extractURL(String feedText) { - // separate input by spaces ( URLs have no spaces ) - feedText = feedText.replaceAll("(\r\n|\n)","
"); - String [] parts = feedText.split("\\s"); - // Attempt to convert each item into an URL. - for( String item : parts ) { - String toCheck = getHttpToken(item); - if (toCheck != null) { - try { - new URL(toCheck); - return toCheck; - } catch (MalformedURLException e) { - // If there was an URL then it's not valid - _log.error("MalformedURLException returning... "); - return null; - } - } - } - return null; - } - /** - * check the tokens of a pasted text and see if there's any http link in it - * @param item a text token - * @return the actual http link - */ - private static String getHttpToken(String item) { - if (item.startsWith("http") || item.startsWith("www") || item.startsWith("(www") || item.startsWith("(http")) { - if (item.startsWith("(")) - item = item.substring(1, item.length()); - if (item.endsWith(".") || item.endsWith(")")) { //sometimes people write the url and close the phrase with a . - item = item.substring(0, item.length()-1); - } - item = item.startsWith("www") ? "http://"+item : item; - System.out.println("getHttpToken returns -> " + item); - return item; - } - return null; - } /** * try with HtmlCleaner API to read the images * @param pageURL @@ -359,38 +215,6 @@ public class TextTransfromUtils { String toReturn = toReplace.replaceAll("&", "&"); return toReturn; } - /** - * utility method that convert a url ina text in a clickable url by the browser - * and if the user has just pasted a link, converts the link in: shared a link - * @param feedText - * @return the text with the clickable url in it - */ - protected static String transformUrls(String feedText) { - StringBuilder sb = new StringBuilder(); - // separate input by spaces ( URLs have no spaces ) - String [] parts = feedText.split("\\s"); - // Attempt to convert each item into an URL. - for (int i = 0; i < parts.length; i++) { - String toCheck = getHttpToken(parts[i]); - if (toCheck != null) { - try { - URL url = new URL(toCheck); - if (i == 0 && parts.length == 1) //then he shared just a link - return sb.append("shared ").append("a link.").append(" ").toString(); - // If possible then replace with anchor... - sb.append("").append(url).append(" "); - } catch (MalformedURLException e) { - // If there was an URL then it's not valid - _log.error("MalformedURLException returning... "); - return feedText; - } - } else { - sb.append(parts[i]); - sb.append(" "); - } - } - return sb.toString(); - } /** * this method handles the non trusted https connections */