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
This commit is contained in:
Costantino Perciante 2016-05-25 13:05:07 +00:00
parent a45f629068
commit c7668dda93
8 changed files with 175 additions and 319 deletions

View File

@ -31,5 +31,6 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/social-util-library"/>
<classpathentry kind="output" path="target/share-updates-2.0.0-SNAPSHOT/WEB-INF/classes"/>
</classpath>

View File

@ -5,6 +5,9 @@
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/target/generated-sources/gwt"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<dependent-module archiveName="social-util-library-1.0.0-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/social-util-library/social-util-library">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="/${module}/target/www/WEB-INF/classes"/>
<property name="context-root" value="share-updates"/>
</wb-module>

View File

@ -112,6 +112,12 @@
<artifactId>pickitem-widget</artifactId>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.socialnetworking</groupId>
<artifactId>social-util-library</artifactId>
<version>1.0.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.portlets.widgets</groupId>
<artifactId>fileupload-progress-bar</artifactId>

View File

@ -29,7 +29,7 @@ public interface ShareUpdateService extends RemoteService {
LinkPreview checkUploadedFile(String fileName, String fileabsolutePathOnServer);
ArrayList<ItemBean> getPortalUsers();
ArrayList<ItemBean> getPortalItemBeans();
ArrayList<ItemBean> getHashtags();
}

View File

@ -21,7 +21,7 @@ public interface ShareUpdateServiceAsync {
void getUserSettings(AsyncCallback<UserSettings> callback);
void getPortalUsers(AsyncCallback<ArrayList<ItemBean>> callback);
void getPortalItemBeans(AsyncCallback<ArrayList<ItemBean>> callback);
void checkUploadedFile(String fileName, String fileabsolutePathOnServer,
AsyncCallback<LinkPreview> callback);

View File

@ -52,10 +52,10 @@ public class SuperPosedTextArea extends TextArea {
sinkEvents(Event.ONKEYDOWN);
sinkEvents(Event.ONKEYUP);
//get the users
shareupdateService.getPortalUsers(new AsyncCallback<ArrayList<ItemBean>>() {
shareupdateService.getPortalItemBeans(new AsyncCallback<ArrayList<ItemBean>>() {
@Override
public void onSuccess(ArrayList<ItemBean> users) {
pickUserDlg = new PickItemsDialog('@', users, eventBus, 525);
public void onSuccess(ArrayList<ItemBean> beans) {
pickUserDlg = new PickItemsDialog('@', beans, eventBus, 525);
pickUserDlg.withPhoto();
}
@Override

View File

@ -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<String> mentionedUserFullNames, boolean notifyGroup) {
// escape text
String escapedFeedText = TextTransfromUtils.escapeHtmlAndTransformUrl(postText);
String escapedFeedText = Utils.escapeHtmlAndTransformUrl(postText);
// get hashtags
List<String> hashtags = TextTransfromUtils.getHashTags(postText);
List<String> hashtags = Utils.getHashTags(postText);
if (hashtags != null && !hashtags.isEmpty())
escapedFeedText = TextTransfromUtils.convertHashtagsAnchorHTML(escapedFeedText, hashtags);
escapedFeedText = Utils.convertHashtagsAnchorHTML(escapedFeedText, hashtags);
// retrieve mentioned users
ArrayList<ItemBean> 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<GenericItemBean> toPass = new ArrayList<GenericItemBean>();
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<String> mentionedUserFullNames, boolean notifyGroup, boolean saveCopyWokspace) {
// escape text
String escapedFeedText = TextTransfromUtils.escapeHtmlAndTransformUrl(feedText);
String escapedFeedText = Utils.escapeHtmlAndTransformUrl(feedText);
// get the list of hashtags
List<String> hashtags = TextTransfromUtils.getHashTags(feedText);
List<String> 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<ItemBean> 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<String> 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<GenericItemBean> toPass = new ArrayList<GenericItemBean>();
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<UploadedFile> 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<ItemBean> 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<GenericItemBean> toPass = new ArrayList<GenericItemBean>();
// among the mentionedUsers there could be groups of people
Map<String, ItemBean> uniqueUsersToNotify = new HashMap<>();
UserManager um = new LiferayUserManager();
for (ItemBean bean : mentionedUsers) {
if(bean.isItemGroup()){
// retrieve the users of this group
try {
List<GCubeUser> 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<Entry<String, ItemBean>> userMapIterator = uniqueUsersToNotify.entrySet().iterator();
while (userMapIterator.hasNext()) {
Map.Entry<String, ItemBean> user = (Map.Entry<String, ItemBean>) 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<ItemBean>();
else {
ArrayList<ItemBean> allUsers = getPortalUsers();
ArrayList<ItemBean> allbeans = getPortalItemBeans();
ArrayList<ItemBean> toReturn = new ArrayList<ItemBean>();
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<ItemBean> getPortalUsers() {
public ArrayList<ItemBean> 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<ItemBean> getOrganizationUsers(String scope, String currUser, boolean withinPortal) {
ArrayList<ItemBean> portalUsers = new ArrayList<ItemBean>();
try {
if (withinPortal) {
UserManager um = new LiferayUserManager();
GroupManager gm = new LiferayGroupManager();
ScopeBean sb = new ScopeBean(scope);
List<GCubeUser> 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;
}
}

View File

@ -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("<span style=\"color:gray; font-size:12px;\">shared </span><a class=\"link\" href=\"").append(url).append("\" target=\"_blank\">").append("a file.").append("</a> ").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<ItemBean> taggedPeople, HttpServletRequest request) {
String userProfilePageURL = "";
userProfilePageURL = PortalContext.getConfiguration().getSiteLandingPagePath(request)+GCubePortalConstants.USER_PROFILE_FRIENDLY_URL;
for (ItemBean tagged : taggedPeople) {
String taggedHTML = "<a class=\"link\" href=\""+userProfilePageURL
+"?"+
new String(Base64.encodeBase64(GCubeSocialNetworking.USER_PROFILE_OID.getBytes()))+"="+
new String(Base64.encodeBase64(tagged.getName().getBytes()))+"\">"+tagged.getAlternativeName()+"</a> ";
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<String> getHashTags(String postText) {
List<String> 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<String> hashtags) {
for (String hashtag : hashtags) {
String taggedHTML = "<a class=\"link\" style=\"font-size:14px;\" href=\"?"+
new String(Base64.encodeBase64(GCubeSocialNetworking.HASHTAG_OID.getBytes()))+"="+
new String(Base64.encodeBase64(hashtag.getBytes()))+"\">"+hashtag+"</a>";
//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("&", "&amp;").replaceAll("<", "&lt;")
.replaceAll(">", "&gt;");
// replace all the line breaks by <br/>
toReturn = toReturn.replaceAll("(\r\n|\n)"," <br/> ");
//transfrom the URL in a clickable URL
toReturn = transformUrls(toReturn);
// then replace all the double spaces by the html version &nbsp;
toReturn = toReturn.replaceAll("\\s\\s","&nbsp;&nbsp;");
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)"," <br/> ");
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("&amp;", "&");
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("<span style=\"color:gray; font-size:12px;\">shared </span><a class=\"link\" href=\"").append(url).append("\" target=\"_blank\">").append("a link.").append("</a> ").toString();
// If possible then replace with anchor...
sb.append("<a class=\"link\" style=\"font-size:14px;\" href=\"").append(url).append("\" target=\"_blank\">").append(url).append("</a> ");
} 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
*/