diff --git a/.classpath b/.classpath index 3db4410..ba34ce9 100644 --- a/.classpath +++ b/.classpath @@ -1,6 +1,6 @@ - + @@ -29,10 +29,10 @@ - + - + diff --git a/distro/changelog.xml b/distro/changelog.xml index e52f964..d071005 100644 --- a/distro/changelog.xml +++ b/distro/changelog.xml @@ -1,4 +1,9 @@ + + Feeds related to some statistics can be now retrievable on the + demand + Ported to Liferay 6.2 diff --git a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/StatisticsPanel.java b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/StatisticsPanel.java index 38dab29..2471c7f 100644 --- a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/StatisticsPanel.java +++ b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/StatisticsPanel.java @@ -7,6 +7,10 @@ import net.eliasbalasis.tibcopagebus4gwt.client.PageBusListener; import org.gcube.portal.databook.client.GCubeSocialNetworking; import org.gcube.portal.databook.client.util.Encoder; +import org.gcube.portal.databook.shared.ShowUserStatisticAction; +import org.gcube.portlet.user.userstatisticsportlet.client.events.PageBusEvents; +import org.gcube.portlet.user.userstatisticsportlet.client.events.ShowFeedsRelatedToUserStatisticsEvent; +import org.gcube.portlet.user.userstatisticsportlet.client.events.ShowFeedsRelatedToUserStatisticsEventHandler; import org.gcube.portlet.user.userstatisticsportlet.client.resources.Images; import org.gcube.portlet.user.userstatisticsportlet.client.ui.CommentsAndLikesWidget; import org.gcube.portlet.user.userstatisticsportlet.client.ui.StatisticWidget; @@ -19,10 +23,12 @@ import com.github.gwtbootstrap.client.ui.CheckBox; import com.github.gwtbootstrap.client.ui.constants.AlertType; import com.github.gwtbootstrap.client.ui.constants.ButtonType; import com.google.gwt.core.client.GWT; +import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; +import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; @@ -67,8 +73,9 @@ public class StatisticsPanel extends Composite { * Labels */ private final static String POSTS_LABEL = "Posts"; + private final static String LIKES_COMMENTS_MADE_LABEL = "Likes & Replies"; + private final static String LIKES_COMMENTS_GOT_LABEL = "Got"; private final static String STORAGE_LABEL = "Space Used"; - private final static String LIKES_COMMENTS_LABEL = "Got"; private final static String PROFILE_STRENGTH_LABEL = "Profile Strength"; /** @@ -76,14 +83,14 @@ public class StatisticsPanel extends Composite { */ public static String IMPROVE_PROFILE_HINT_MESSAGE_ROOT = "You can improve your profile strength by: "; + + "
  • adding your contact information (facebook, linkedin, skype, google mail and so on)"; /** * improve profile hints */ public static final String IMPROVE_PROFILE_HINT_MESSAGE_PROFILE = "You can improve your profile strength by:
      " + "
    • adding a job title, your current position or your professional summary;" - + "
    • adding your contact information (facebook, linkedin, skype, google mail and so on).
    "; + + "
  • adding your contact information (facebook, linkedin, skype, google mail and so on)"; /** * profile button label @@ -140,13 +147,18 @@ public class StatisticsPanel extends Composite { */ final public static PageBusAdapter pageBusAdapter = new PageBusAdapter(); + /** + * Handler Manager for internal events + */ + private final HandlerManager eventBus = new HandlerManager(null); + public StatisticsPanel() { //init this object super(); initWidget(mainPanel); - // bind pagebus events + // bind pagebus events/ internal events bind(); // set style of the main panel @@ -184,7 +196,7 @@ public class StatisticsPanel extends Composite { // first of all check if the statistics can be shown to other people if(userid != null && !userid.equals(information.getAslSessionUsername()) && !information.isProfileShowable()){ - mainPanel.add(new HTML("Sorry but the user set his Statistics to private.")); + mainPanel.add(new HTML("Sorry but the user set his Statistics to private")); return; } @@ -241,9 +253,9 @@ public class StatisticsPanel extends Composite { feeds.setHeader(POSTS_LABEL); if(isRoot || isProfilePage) - feeds.setToolTip("Posts during the last year."); + feeds.setToolTip("Posts during the last year"); else - feeds.setToolTip("Posts during the last year in this VRE."); + feeds.setToolTip("Posts during the last year in this VRE"); // add loading image that will be replaced by the incoming values @@ -254,22 +266,39 @@ public class StatisticsPanel extends Composite { // append widget mainPanel.add(feeds); - // likes & comments - final StatisticWidget likesAndComments = new StatisticWidget(isRoot); - likesAndComments.setHeader(LIKES_COMMENTS_LABEL); + // likes & comments made + final StatisticWidget likesAndCommentsMade = new StatisticWidget(isRoot); + likesAndCommentsMade.setHeader(LIKES_COMMENTS_MADE_LABEL); if(isRoot || isProfilePage) - likesAndComments.setToolTip("Likes and post replies got during the last year."); + likesAndCommentsMade.setToolTip("Likes and post replies made during the last year"); else - likesAndComments.setToolTip("Likes and post replies got during the last year in this VRE."); + likesAndCommentsMade.setToolTip("Likes and post replies made during the last year in this VRE"); + + // add loading image that will be replaced by the incoming values + Image commentsLikesMadeLoader = new Image(imagePath); + commentsLikesMadeLoader.setStyleName("loading-image-center-small"); + likesAndCommentsMade.appendToPanel(commentsLikesMadeLoader); + + // append widget + mainPanel.add(likesAndCommentsMade); + + // likes & comments got + final StatisticWidget likesAndCommentsGot = new StatisticWidget(isRoot); + likesAndCommentsGot.setHeader(LIKES_COMMENTS_GOT_LABEL); + + if(isRoot || isProfilePage) + likesAndCommentsGot.setToolTip("Likes and post replies got during the last year"); + else + likesAndCommentsGot.setToolTip("Likes and post replies got during the last year in this VRE"); // add loading image that will be replaced by the incoming values Image commentsLikesLoader = new Image(imagePath); commentsLikesLoader.setStyleName("loading-image-center-small"); - likesAndComments.appendToPanel(commentsLikesLoader); + likesAndCommentsGot.appendToPanel(commentsLikesLoader); // append widget - mainPanel.add(likesAndComments); + mainPanel.add(likesAndCommentsGot); // the storage and the profile strength(only in root) final StatisticWidget storage = new StatisticWidget(isRoot); @@ -278,7 +307,7 @@ public class StatisticsPanel extends Composite { if(isRoot || isProfilePage){ storage.setHeader(STORAGE_LABEL); - storage.setToolTip("Total amount of space used in the infrastructure."); + storage.setToolTip("Total amount of space used in the infrastructure"); // add loading image that will be replaced by the incoming values Image totalSpaceLoader = new Image(imagePath); @@ -360,7 +389,7 @@ public class StatisticsPanel extends Composite { final Button improveProfileButton = new Button(IMPROVE_BUTTON_LABEL); improveProfileButton.setType(ButtonType.INFO); - improveProfileButton.setTitle("Improve your profile."); + improveProfileButton.setTitle("Improve your profile"); improveProfileButton.addClickHandler(new ClickHandler() { @@ -394,7 +423,7 @@ public class StatisticsPanel extends Composite { public void onFailure(Throwable arg0) { appendAlertIcon(feeds); - appendAlertIcon(likesAndComments); + appendAlertIcon(likesAndCommentsGot); } @@ -404,7 +433,7 @@ public class StatisticsPanel extends Composite { if(postsBean == null){ appendAlertIcon(feeds); - appendAlertIcon(likesAndComments); + appendAlertIcon(likesAndCommentsGot); return; } @@ -413,50 +442,110 @@ public class StatisticsPanel extends Composite { feeds.clearPanelValues(); numberOfFeedsLabel = new Label(formattedNumbers(postsBean.getFeedsNumber())); if(isRoot || isProfilePage) - numberOfFeedsLabel.setTitle("Posts during the last year (" + postsBean.getFeedsNumber() + ")."); + numberOfFeedsLabel.setTitle("Posts during the last year (" + postsBean.getFeedsNumber() + ")"); else - numberOfFeedsLabel.setTitle("Posts during the last year in this VRE (" + postsBean.getFeedsNumber() + ")."); + numberOfFeedsLabel.setTitle("Posts during the last year in this VRE (" + postsBean.getFeedsNumber() + ")"); + + // add handler for user that clicks on the numberOfFeedsLabel + if(!isProfilePage){ + numberOfFeedsLabel.getElement().getStyle().setCursor(Cursor.POINTER); + numberOfFeedsLabel.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + eventBus.fireEvent(new ShowFeedsRelatedToUserStatisticsEvent(ShowUserStatisticAction.POSTS_MADE_BY_USER)); + + } + }); + } numberOfWrittenFeeds = postsBean.getFeedsNumber(); numberOfFeedsLabel.setStyleName("statistic-value"); feeds.appendToPanel(numberOfFeedsLabel); - // updates comments and likes - likesAndComments.clearPanelValues(); - content = new CommentsAndLikesWidget(); + // updates comments and likes made + likesAndCommentsMade.clearPanelValues(); + CommentsAndLikesWidget contentLikesAndCommentsMade = new CommentsAndLikesWidget(); + + if(!isProfilePage) + contentLikesAndCommentsMade.setEventBus(eventBus); String urlLikesIcon = GWT.getModuleBaseURL() + "../images/star_blue.png"; + if(isRoot || isProfilePage) + contentLikesAndCommentsMade.setLikes( + urlLikesIcon, + formattedNumbers(postsBean.getLikesMade()), + "Likes made during the last year", + "Likes made during the last year (" + postsBean.getLikesMade() + ")", + ShowUserStatisticAction.LIKES_MADE_BY_USER); + else + contentLikesAndCommentsMade.setLikes( + urlLikesIcon, + formattedNumbers(postsBean.getLikesMade()), + "Likes made during the last year in this VRE", + "Likes made during the last year in this VRE (" + postsBean.getLikesMade() + ")", + ShowUserStatisticAction.LIKES_MADE_BY_USER); + + String urlCommentsIcon = GWT.getModuleBaseURL() + "../images/comment_edit.png"; + if(isRoot || isProfilePage) + contentLikesAndCommentsMade.setComments( + urlCommentsIcon, + formattedNumbers(postsBean.getCommentsMade()), + "Post replies made during the last year", + "Post replies made during the last year (" + postsBean.getCommentsMade() + ")", + ShowUserStatisticAction.COMMENTS_MADE_BY_USER); + else + contentLikesAndCommentsMade.setComments( + urlCommentsIcon, + formattedNumbers(postsBean.getCommentsMade()), + "Post replies made during the last year in this VRE", + "Post replies made during the last year in this VRE (" + postsBean.getCommentsMade() + ")", + ShowUserStatisticAction.COMMENTS_MADE_BY_USER); + + likesAndCommentsMade.appendToPanel(contentLikesAndCommentsMade); + + // updates comments and likes got + likesAndCommentsGot.clearPanelValues(); + content = new CommentsAndLikesWidget(); + + if(!isProfilePage) + content.setEventBus(eventBus); + if(isRoot || isProfilePage) content.setLikes( urlLikesIcon, formattedNumbers(postsBean.getLikesReceived()), - "Likes got during the last year.", - "Likes got during the last year (" + postsBean.getLikesReceived() + ")."); + "Likes got during the last year", + "Likes got during the last year (" + postsBean.getLikesReceived() + ")", + ShowUserStatisticAction.LIKES_GOT_BY_USER); else content.setLikes( urlLikesIcon, formattedNumbers(postsBean.getLikesReceived()), "Likes got during the last year in this VRE", - "Likes got during the last year in this VRE (" + postsBean.getLikesReceived() + ")."); + "Likes got during the last year in this VRE (" + postsBean.getLikesReceived() + ")", + ShowUserStatisticAction.LIKES_GOT_BY_USER); numberOfLikesGot = postsBean.getLikesReceived(); - String urlCommentsIcon = GWT.getModuleBaseURL() + "../images/comment_edit.png"; if(isRoot || isProfilePage) content.setComments( urlCommentsIcon, formattedNumbers(postsBean.getCommentsReceived()), - "Post replies got during the last year.", - "Post replies got during the last year (" + postsBean.getCommentsReceived() + ")."); + "Post replies got during the last year", + "Post replies got during the last year (" + postsBean.getCommentsReceived() + ")", + ShowUserStatisticAction.COMMENTS_GOT_BY_USER); else content.setComments( urlCommentsIcon, formattedNumbers(postsBean.getCommentsReceived()), "Post replies got during the last year in this VRE.", - "Post replies got during the last year in this VRE (" + postsBean.getCommentsReceived() + ")."); + "Post replies got during the last year in this VRE (" + postsBean.getCommentsReceived() + ")", + ShowUserStatisticAction.COMMENTS_GOT_BY_USER); numberOfCommentsGot = postsBean.getCommentsReceived(); - likesAndComments.appendToPanel(content); + likesAndCommentsGot.appendToPanel(content); } }); @@ -504,6 +593,25 @@ public class StatisticsPanel extends Composite { private void bind() { try { + + // on statistic value click handler + eventBus.addHandler(ShowFeedsRelatedToUserStatisticsEvent.TYPE, new ShowFeedsRelatedToUserStatisticsEventHandler() { + + @Override + public void onShowRelatedFeeds( + ShowFeedsRelatedToUserStatisticsEvent event) { + + ShowUserStatisticAction actionToTake = event.getAction(); + + // get current url + String currentUrl = Window.Location.getHref(); + String[] splittedUrl = currentUrl.split("\\?"); + + Window.Location.assign(splittedUrl[0] + "?" + Encoder.encode(GCubeSocialNetworking.SHOW_STATISTICS_ACTION_OID) + "=" + Encoder.encode(actionToTake.toString())); + + } + }); + // increment post number pageBusAdapter.PageBusSubscribe(PageBusEvents.postIncrement, null, null, null, null); @@ -524,9 +632,9 @@ public class StatisticsPanel extends Composite { numberOfWrittenFeeds ++; numberOfFeedsLabel.setText(formattedNumbers(numberOfWrittenFeeds)); if(isRoot) - numberOfFeedsLabel.setTitle("Your posts during the last year (" + numberOfWrittenFeeds + ")."); + numberOfFeedsLabel.setTitle("Your posts during the last year (" + numberOfWrittenFeeds + ")"); else - numberOfFeedsLabel.setTitle("Your posts during the last year in this VRE (" + numberOfWrittenFeeds + ")."); + numberOfFeedsLabel.setTitle("Your posts during the last year in this VRE (" + numberOfWrittenFeeds + ")"); GWT.log("Number of written posts changed to " + numberOfWrittenFeeds); } } @@ -553,9 +661,9 @@ public class StatisticsPanel extends Composite { numberOfWrittenFeeds = numberOfWrittenFeeds < 0 ? 0: numberOfWrittenFeeds; numberOfFeedsLabel.setText(formattedNumbers(numberOfWrittenFeeds)); if(isRoot) - numberOfFeedsLabel.setTitle("Your posts during the last year (" + numberOfWrittenFeeds + ")."); + numberOfFeedsLabel.setTitle("Your posts during the last year (" + numberOfWrittenFeeds + ")"); else - numberOfFeedsLabel.setTitle("Your posts during the last year in this VRE (" + numberOfWrittenFeeds + ")."); + numberOfFeedsLabel.setTitle("Your posts during the last year in this VRE (" + numberOfWrittenFeeds + ")"); GWT.log("Number of written posts changed to " + numberOfWrittenFeeds); } }}); @@ -585,15 +693,15 @@ public class StatisticsPanel extends Composite { urlLikesIcon, formattedNumbers(numberOfLikesGot), "Likes you got during the last year.", - "Likes you got during the last year (" + numberOfLikesGot + ")."); + "Likes you got during the last year (" + numberOfLikesGot + ")", + ShowUserStatisticAction.LIKES_GOT_BY_USER); else content.setLikes( urlLikesIcon, formattedNumbers(numberOfLikesGot), "Likes you got during the last year in this VRE", - "Likes you got during the last year in this VRE (" + numberOfLikesGot + ")."); - - + "Likes you got during the last year in this VRE (" + numberOfLikesGot + ")", + ShowUserStatisticAction.LIKES_GOT_BY_USER); GWT.log("Number of likes got changed to " + numberOfLikesGot); } @@ -627,13 +735,15 @@ public class StatisticsPanel extends Composite { urlLikesIcon, formattedNumbers(numberOfLikesGot), "Likes you got during the last year.", - "Likes you got during the last year (" + numberOfLikesGot + ")."); + "Likes you got during the last year (" + numberOfLikesGot + ")", + ShowUserStatisticAction.LIKES_GOT_BY_USER); else content.setLikes( urlLikesIcon, formattedNumbers(numberOfLikesGot), "Likes you got during the last year in this VRE", - "Likes you got during the last year in this VRE (" + numberOfLikesGot + ")."); + "Likes you got during the last year in this VRE (" + numberOfLikesGot + ")", + ShowUserStatisticAction.LIKES_GOT_BY_USER); GWT.log("Number of likes got changed to " + numberOfLikesGot); } @@ -666,13 +776,15 @@ public class StatisticsPanel extends Composite { urlCommentsIcon, formattedNumbers(numberOfCommentsGot), "Post replies you got during the last year.", - "Post replies you got during the last year (" + numberOfCommentsGot + ")."); + "Post replies you got during the last year (" + numberOfCommentsGot + ")", + ShowUserStatisticAction.COMMENTS_GOT_BY_USER); else content.setComments( urlCommentsIcon, formattedNumbers(numberOfCommentsGot), "Post replies you got during the last year in this VRE.", - "Post replies you got during the last year in this VRE (" + numberOfCommentsGot + ")."); + "Post replies you got during the last year in this VRE (" + numberOfCommentsGot + ")", + ShowUserStatisticAction.COMMENTS_GOT_BY_USER); GWT.log("Number of comments got changed to " + numberOfCommentsGot); } @@ -705,13 +817,15 @@ public class StatisticsPanel extends Composite { urlCommentsIcon, formattedNumbers(numberOfCommentsGot), "Post replies you got during the last year.", - "Post replies you got during the last year (" + numberOfCommentsGot + ")."); + "Post replies you got during the last year (" + numberOfCommentsGot + ")", + ShowUserStatisticAction.COMMENTS_GOT_BY_USER); else content.setComments( urlCommentsIcon, formattedNumbers(numberOfCommentsGot), "Post replies you got during the last year in this VRE.", - "Post replies you got during the last year in this VRE (" + numberOfCommentsGot + ")."); + "Post replies you got during the last year in this VRE (" + numberOfCommentsGot + ")", + ShowUserStatisticAction.COMMENTS_GOT_BY_USER); GWT.log("Number of comments got changed to " + numberOfCommentsGot); } @@ -800,7 +914,7 @@ public class StatisticsPanel extends Composite { String encodedUserId = Window.Location.getParameter(encodedOid); return Encoder.decode(encodedUserId); } - + /** * The user-statistics can be deployed in a vre, within the home or in a profile page * @return true if the current page is a profile page, false otherwise diff --git a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/PageBusEvents.java b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/PageBusEvents.java similarity index 91% rename from src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/PageBusEvents.java rename to src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/PageBusEvents.java index 08d542f..59c3c5c 100644 --- a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/PageBusEvents.java +++ b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/PageBusEvents.java @@ -1,4 +1,4 @@ -package org.gcube.portlet.user.userstatisticsportlet.client; +package org.gcube.portlet.user.userstatisticsportlet.client.events; /** * This class contains the events (in a package like format) to which this portlet listens at. diff --git a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/ShowFeedsRelatedToUserStatisticsEvent.java b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/ShowFeedsRelatedToUserStatisticsEvent.java new file mode 100644 index 0000000..7b062da --- /dev/null +++ b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/ShowFeedsRelatedToUserStatisticsEvent.java @@ -0,0 +1,32 @@ +package org.gcube.portlet.user.userstatisticsportlet.client.events; + +import org.gcube.portal.databook.shared.ShowUserStatisticAction; + +import com.google.gwt.event.shared.GwtEvent; + +/** + * Event fired when the user wants to see feeds related to certain statistics. + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class ShowFeedsRelatedToUserStatisticsEvent extends GwtEvent { + public static Type TYPE = new Type(); + + private ShowUserStatisticAction action; + public ShowFeedsRelatedToUserStatisticsEvent(ShowUserStatisticAction actionToTake) { + this.action = actionToTake; + } + + public ShowUserStatisticAction getAction() { + return action; + } + + @Override + public Type getAssociatedType() { + return TYPE; + } + + @Override + protected void dispatch(ShowFeedsRelatedToUserStatisticsEventHandler handler) { + handler.onShowRelatedFeeds(this); + } +} diff --git a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/ShowFeedsRelatedToUserStatisticsEventHandler.java b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/ShowFeedsRelatedToUserStatisticsEventHandler.java new file mode 100644 index 0000000..32819cc --- /dev/null +++ b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/events/ShowFeedsRelatedToUserStatisticsEventHandler.java @@ -0,0 +1,11 @@ +package org.gcube.portlet.user.userstatisticsportlet.client.events; + +import com.google.gwt.event.shared.EventHandler; + +/** + * Handler related to the ShowFeedsRelatedToUserStatisticsEvent class + * @author Costantino Perciante at ISTI-CNR + */ +public interface ShowFeedsRelatedToUserStatisticsEventHandler extends EventHandler { + void onShowRelatedFeeds(ShowFeedsRelatedToUserStatisticsEvent event); +} diff --git a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/ui/CommentsAndLikesWidget.java b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/ui/CommentsAndLikesWidget.java index 18ce41a..b224a29 100644 --- a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/ui/CommentsAndLikesWidget.java +++ b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/client/ui/CommentsAndLikesWidget.java @@ -1,6 +1,13 @@ package org.gcube.portlet.user.userstatisticsportlet.client.ui; +import org.gcube.portal.databook.shared.ShowUserStatisticAction; +import org.gcube.portlet.user.userstatisticsportlet.client.events.ShowFeedsRelatedToUserStatisticsEvent; + import com.google.gwt.core.client.GWT; +import com.google.gwt.dom.client.Style.Cursor; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; @@ -28,24 +35,60 @@ public class CommentsAndLikesWidget extends Composite { @UiField Label commentsValue; + + private HandlerManager busEvents; public CommentsAndLikesWidget() { initWidget(uiBinder.createAndBindUi(this)); } - public void setComments(String url, String value, String tipIcon, String tipValue){ + public void setComments(String url, String value, String tipIcon, String tipValue, final ShowUserStatisticAction actionToTakeOnClick){ this.commentsImage.setUrl(url); this.commentsImage.setTitle(tipIcon); this.commentsValue.setText(value); this.commentsValue.setTitle(tipValue); + + if(busEvents != null && actionToTakeOnClick != null){ + + commentsValue.getElement().getStyle().setCursor(Cursor.POINTER); + commentsValue.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + busEvents.fireEvent(new ShowFeedsRelatedToUserStatisticsEvent(actionToTakeOnClick)); + + } + }); + + } } - public void setLikes(String url, String value, String tipIcon, String tipValue){ + public void setLikes(String url, String value, String tipIcon, String tipValue, final ShowUserStatisticAction actionToTakeOnClick){ this.likesImage.setUrl(url); this.likesImage.setTitle(tipIcon); this.likesValue.setText(value); this.likesValue.setTitle(tipValue); + + if(busEvents != null && actionToTakeOnClick != null){ + + likesValue.getElement().getStyle().setCursor(Cursor.POINTER); + likesValue.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + busEvents.fireEvent(new ShowFeedsRelatedToUserStatisticsEvent(actionToTakeOnClick)); + + } + }); + + } + } + + public void setEventBus(HandlerManager busEvents){ + this.busEvents = busEvents; } } diff --git a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/server/ServerUtils.java b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/server/ServerUtils.java new file mode 100644 index 0000000..0ed8e27 --- /dev/null +++ b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/server/ServerUtils.java @@ -0,0 +1,294 @@ +package org.gcube.portlet.user.userstatisticsportlet.server; + +import java.io.Serializable; +import java.text.DecimalFormat; +import java.util.List; + +import javax.servlet.http.HttpSession; + +import org.gcube.application.framework.core.session.ASLSession; +import org.gcube.application.framework.core.session.SessionManager; +import org.gcube.portal.custom.scopemanager.scopehelper.ScopeHelper; +import org.gcube.vomanagement.usermanagement.GroupManager; +import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; +import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; +import org.gcube.vomanagement.usermanagement.util.ManagementUtils; +import org.slf4j.LoggerFactory; + +import com.liferay.portal.model.Contact; +import com.liferay.portal.model.User; +import com.liferay.portal.model.Website; +import com.liferay.portal.security.auth.PrincipalThreadLocal; +import com.liferay.portal.security.permission.PermissionChecker; +import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; +import com.liferay.portal.security.permission.PermissionThreadLocal; +import com.liferay.portal.service.UserLocalServiceUtil; +import com.liferay.portal.service.WebsiteLocalServiceUtil; +import com.liferay.portlet.expando.model.ExpandoColumnConstants; + +/** + * This class contains server side utils methods + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class ServerUtils { + + // Logger + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ServerUtils.class); + + /** + * the current ASLSession + * @return the session + */ + public static ASLSession getASLSession(HttpSession session) { + + String sessionID = session.getId(); + String user = (String) session.getAttribute(ScopeHelper.USERNAME_ATTRIBUTE); + + if (user == null) { + + logger.warn("USER IS NULL setting " + UserStatisticsServiceImpl.defaultUserId + " and Running OUTSIDE PORTAL"); + user = getDevelopmentUser(); + SessionManager.getInstance().getASLSession(sessionID, user).setScope(UserStatisticsServiceImpl.vreID); + + } + + return SessionManager.getInstance().getASLSession(sessionID, user); + } + + /** + * when packaging test will fail if the user is not set to test.user + * @return . + */ + public static String getDevelopmentUser() { + String user = UserStatisticsServiceImpl.defaultUserId; + // user = "costantino.perciante"; + return user; + } + + /** + * Indicates whether the scope is the whole infrastructure. + * @param userid in case userid is not null, the user is visiting a profile page and + * the statistics to return are the ones available in the whole infrastructure + * @return true if it is, false otherwise. + */ + public static boolean isInfrastructureScope(String userid, HttpSession session) { + boolean toReturn = false; + try { + GroupManager manager = new LiferayGroupManager(); + long groupId = manager.getGroupIdFromInfrastructureScope(getASLSession(session).getScope()); + toReturn = !manager.isVRE(groupId) || userid != null; + return toReturn; + } + catch (Exception e) { + logger.error("NullPointerException in isInfrastructureScope returning false"); + return false; + } + } + + /** + * Online or in development mode? + * @return true if you're running into the portal, false if in development + */ + public static boolean isWithinPortal() { + try { + UserLocalServiceUtil.getService(); + return true; + } + catch (com.liferay.portal.kernel.bean.BeanLocatorException ex) { + logger.trace("Development Mode ON"); + return false; + } + } + + /** + * returns dynamically the formated size. + * + * @param size the size + * @return the string + */ + public static String formatFileSize(long size) { + String formattedSize = null; + + double b = size; + double k = size/1024.0; + double m = ((size/1024.0)/1024.0); + double g = (((size/1024.0)/1024.0)/1024.0); + double t = ((((size/1024.0)/1024.0)/1024.0)/1024.0); + + DecimalFormat dec = new DecimalFormat("0.00"); + + if ( t >= 1.0 ) { + formattedSize = dec.format(t).concat(" TB"); + } else if ( g >= 1.0 ) { + formattedSize = dec.format(g).concat(" GB"); + } else if ( m >= 1.0 ) { + formattedSize = dec.format(m).concat(" MB"); + } else if ( k >= 1.0 ) { + formattedSize = dec.format(k).concat(" KB"); + } else { + formattedSize = dec.format(b).concat(" Bytes"); + } + return formattedSize; + } + + /** + * Evaluates the profile strenght of the user + * @param user + * @return a int in [0, 100] + */ + public static int evaluateProfileStrenght(User user, boolean imageIsPresent) { + + int score = evaluateContactScore(user); + score += evaluateInformationScore(user, imageIsPresent); + + return score; + } + + + /** + * Evaluates a score according to the information of the user such as job, organization, comments + * @param user + * @return a score in [0, 65] + */ + public static int evaluateInformationScore(User user, boolean imageIsPresent) { + int score = 0; + + if(user.getJobTitle() != null) + score += !user.getJobTitle().isEmpty() ? 20 : 0; + if(user.getOpenId() != null) + score += !user.getOpenId().isEmpty() ? 20 : 0; + String summary = getSummary(user); + if(summary != null){ + int lenght = summary.replace(" ", "").length(); + float partialScore = ((float)lenght / 10.0f); + score += partialScore > 20f ? 20 : (int)partialScore; + } + + if(imageIsPresent) + score += 5; + + return score; + } + + /** + * get the user's comment + * @param user + * @return + */ + public static String getSummary(User user) { + if(user.getComments() != null){ + String toReturn = escapeHtml(user.getComments()); + // replace all the line breaks by
    + toReturn = toReturn.replaceAll("(\r\n|\n)","
    "); + // then replace all the double spaces by the html version   + toReturn = toReturn.replaceAll("\\s\\s","  "); + return toReturn; + }else + return null; + } + + /** + * 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 + */ + public static String escapeHtml(String html) { + if (html == null) { + return null; + } + return html.replaceAll("&", "&").replaceAll("<", "<") + .replaceAll(">", ">"); + } + + /** + * Evaluates user's contact information + * @param user + * @return a value in [0, 35] + */ + public static int evaluateContactScore(User user){ + + int score = 0; + + try{ + Contact contact = user.getContact(); + + if(contact.getMySpaceSn() != null) + score += !contact.getMySpaceSn().isEmpty() ? 5 : 0; + if(contact.getTwitterSn() != null) + score += !contact.getTwitterSn().isEmpty() ? 5 : 0; + if(contact.getFacebookSn() != null) + score += !contact.getFacebookSn().isEmpty() ? 5 : 0; + if(contact.getSkypeSn() != null) + score += !contact.getSkypeSn().isEmpty() ? 5 : 0; + if(contact.getJabberSn() != null) + score += !contact.getJabberSn().isEmpty() ? 5 : 0; + if(contact.getAimSn() != null) + score += !contact.getAimSn().isEmpty() ? 5 : 0; + + List websites = WebsiteLocalServiceUtil.getWebsites(user.getCompanyId(), "com.liferay.portal.model.Contact", contact.getContactId()); + score += websites.size() > 0 ? 5 : 0; + }catch(Exception e ){ + + logger.error("Contact profile score evaluation failed!!"); + score = 0; + } + + return score; + } + + /** + * Set the permission checker to set/get custom fields into liferay + */ + public static void setPermissionChecker(){ + + // set permission checker + try{ + long adminId = LiferayUserManager.getAdmin().getUserId(); + PrincipalThreadLocal.setName(adminId); + PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(UserLocalServiceUtil.getUser(adminId)); + PermissionThreadLocal.setPermissionChecker(permissionChecker); + }catch(Exception e){ + logger.error("Unable to set permission checker. Custom fields set/get operations are likely to fail..."); + } + + } + + /** + * On servlet instanciation, create the custom field and set it to startingValue + * @param customFieldNameUserStatisticsVisibility + * @param b + */ + public static void createUserCustomField( + String customFieldNameUserStatisticsVisibility, boolean startingValue) { + + // set permission checker + ServerUtils.setPermissionChecker(); + + try{ + + User defaultUser = UserLocalServiceUtil.getDefaultUser(ManagementUtils.getCompany().getCompanyId()); + + // check if it exists + boolean exists = defaultUser.getExpandoBridge().hasAttribute(customFieldNameUserStatisticsVisibility); + + if(exists){ + + logger.debug("Custom field already exists... There is no need to create it"); + + }else{ + + logger.debug("Creating custom field " + customFieldNameUserStatisticsVisibility + + " with starting value " + startingValue); + + // create + defaultUser.getExpandoBridge().addAttribute(customFieldNameUserStatisticsVisibility, ExpandoColumnConstants.BOOLEAN, (Serializable)(true)); + + } + + }catch(Exception e){ + logger.error("Unable to create custom field " + customFieldNameUserStatisticsVisibility); + } + } +} diff --git a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/server/UserStatisticsServiceImpl.java b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/server/UserStatisticsServiceImpl.java index f5c38f0..30afb32 100644 --- a/src/main/java/org/gcube/portlet/user/userstatisticsportlet/server/UserStatisticsServiceImpl.java +++ b/src/main/java/org/gcube/portlet/user/userstatisticsportlet/server/UserStatisticsServiceImpl.java @@ -1,19 +1,15 @@ package org.gcube.portlet.user.userstatisticsportlet.server; -import java.io.Serializable; -import java.text.DecimalFormat; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.gcube.application.framework.core.session.ASLSession; -import org.gcube.application.framework.core.session.SessionManager; import org.gcube.common.homelibrary.home.HomeLibrary; import org.gcube.common.homelibrary.home.workspace.Workspace; import org.gcube.common.portal.PortalContext; import org.gcube.portal.custom.communitymanager.SiteManagerUtil; -import org.gcube.portal.custom.scopemanager.scopehelper.ScopeHelper; import org.gcube.portal.databook.server.DBCassandraAstyanaxImpl; import org.gcube.portal.databook.server.DatabookStore; import org.gcube.portal.databook.shared.Comment; @@ -22,27 +18,17 @@ import org.gcube.portlet.user.userstatisticsportlet.client.UserStatisticsService import org.gcube.portlet.user.userstatisticsportlet.server.cache.UserInfrastructureSpaceCache; import org.gcube.portlet.user.userstatisticsportlet.shared.PostsStatsBean; import org.gcube.portlet.user.userstatisticsportlet.shared.UserInformation; -import org.gcube.vomanagement.usermanagement.GroupManager; import org.gcube.vomanagement.usermanagement.UserManager; 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.LiferayUserManager; import org.gcube.vomanagement.usermanagement.util.ManagementUtils; import org.slf4j.LoggerFactory; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.liferay.portal.kernel.cache.CacheRegistryUtil; -import com.liferay.portal.model.Contact; import com.liferay.portal.model.User; -import com.liferay.portal.model.Website; -import com.liferay.portal.security.auth.PrincipalThreadLocal; -import com.liferay.portal.security.permission.PermissionChecker; -import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; -import com.liferay.portal.security.permission.PermissionThreadLocal; import com.liferay.portal.service.UserLocalServiceUtil; -import com.liferay.portal.service.WebsiteLocalServiceUtil; -import com.liferay.portlet.expando.model.ExpandoColumnConstants; /** * The server side implementation of the RPC service. @@ -51,13 +37,13 @@ import com.liferay.portlet.expando.model.ExpandoColumnConstants; public class UserStatisticsServiceImpl extends RemoteServiceServlet implements UserStatisticsService { // Logger - private static final org.slf4j.Logger _log = LoggerFactory.getLogger(UserStatisticsServiceImpl.class); + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UserStatisticsServiceImpl.class); //dev user public static final String defaultUserId = "test.user"; //dev vre - private static final String vreID = "/gcube/devsec/devVRE"; + public static final String vreID = "/gcube/devsec/devVRE"; // Cassandra connection private DatabookStore store; @@ -67,95 +53,30 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U @Override public void init() { + // get connection to Cassandra - _log.debug("Getting connection to Cassandra.."); + logger.debug("Getting connection to Cassandra.."); store = new DBCassandraAstyanaxImpl(); // add statistics option for profile pages and set to true - createUserCustomField(CUSTOM_FIELD_NAME_USER_STATISTICS_VISIBILITY, true); + ServerUtils.createUserCustomField(CUSTOM_FIELD_NAME_USER_STATISTICS_VISIBILITY, true); } @Override public void destroy(){ // shutting down connection to Cassandra - _log.info("Closing connection to Cassandra"); + logger.info("Closing connection to Cassandra"); store.closeConnection(); } - /** - * the current ASLSession - * @return the session - */ - private ASLSession getASLSession() { - - String sessionID = this.getThreadLocalRequest().getSession().getId(); - String user = (String) this.getThreadLocalRequest().getSession().getAttribute(ScopeHelper.USERNAME_ATTRIBUTE); - - if (user == null) { - - _log.warn("USER IS NULL setting " + defaultUserId + " and Running OUTSIDE PORTAL"); - user = getDevelopmentUser(); - SessionManager.getInstance().getASLSession(sessionID, user).setScope(vreID); - - } - - return SessionManager.getInstance().getASLSession(sessionID, user); - } - - /** - * Indicates whether the scope is the whole infrastructure. - * @param userid in case userid is not null, the user is visiting a profile page and - * the statistics to return are the ones available in the whole infrastructure - * @return true if it is, false otherwise. - */ - private boolean isInfrastructureScope(String userid) { - boolean toReturn = false; - try { - GroupManager manager = new LiferayGroupManager(); - long groupId = manager.getGroupIdFromInfrastructureScope(getASLSession().getScope()); - toReturn = !manager.isVRE(groupId) || userid != null; - return toReturn; - } - catch (Exception e) { - _log.error("NullPointerException in isInfrastructureScope returning false"); - return false; - } - } - - /** - * Online or in development mode? - * @return true if you're running into the portal, false if in development - */ - private boolean isWithinPortal() { - try { - UserLocalServiceUtil.getService(); - return true; - } - catch (com.liferay.portal.kernel.bean.BeanLocatorException ex) { - _log.trace("Development Mode ON"); - return false; - } - } - - /** - * when packaging test will fail if the user is not set to test.user - * @return . - */ - public String getDevelopmentUser() { - String user = defaultUserId; - // user = "costantino.perciante"; - return user; - } - - @Override public String getTotalSpaceInUse(String userid) { String storageInUse = null; // get the session - ASLSession session = getASLSession(); + ASLSession session = ServerUtils.getASLSession(this.getThreadLocalRequest().getSession()); // username in the session String userName = session.getUsername(); @@ -170,12 +91,12 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U //this check just return nothing if that happens if (userName.compareTo(defaultUserId) == 0) { - _log.debug("Found " + userName + " returning nothing"); + logger.debug("Found " + userName + " returning nothing"); return null; }else{ - _log.debug("Getting " + statisticsOfUsername + " amount of workspace in use."); + logger.debug("Getting " + statisticsOfUsername + " amount of workspace in use."); try{ @@ -190,23 +111,23 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U // if not, ask the workspace if(storageInUseLong == null){ - _log.debug("Information not available in the cache, asking workspace"); + logger.debug("Information not available in the cache, asking workspace"); Workspace workspace = HomeLibrary.getUserWorkspace(statisticsOfUsername); storageInUseLong = workspace.getDiskUsage(); - _log.debug("Put information in the cache"); + logger.debug("Put information in the cache"); cacheWorkspace.insert(statisticsOfUsername, storageInUseLong); } - storageInUse = formatFileSize(storageInUseLong); + storageInUse = ServerUtils.formatFileSize(storageInUseLong); long end = System.currentTimeMillis(); - _log.debug("[USER-STATISTICS] time taken to retrieve user space is " + (end - init) + "ms"); + logger.debug("[USER-STATISTICS] time taken to retrieve user space is " + (end - init) + "ms"); }catch(Exception e){ - _log.error("Unable to retrieve workspace information!"); + logger.error("Unable to retrieve workspace information!"); } } @@ -220,7 +141,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U int profileStrenght = -1; // get the session - ASLSession session = getASLSession(); + ASLSession session = ServerUtils.getASLSession(this.getThreadLocalRequest().getSession()); // username String userName = session.getUsername(); @@ -234,12 +155,12 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U //in case the portal is restarted and you have the social home open it will get test.user (no callback to set session info) //this check just return nothing if that happens if (userName.compareTo(defaultUserId) == 0) { - _log.debug("Found " + userName + " returning nothing"); + logger.debug("Found " + userName + " returning nothing"); return profileStrenght; }else{ // valuate profile strength - if(isWithinPortal()){ + if(ServerUtils.isWithinPortal()){ try{ @@ -249,14 +170,14 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U boolean avatarPresent = (new LiferayUserManager().getUserAvatarBytes(statisticsOfUsername) != null); User user = UserLocalServiceUtil.getUserByScreenName(SiteManagerUtil.getCompany().getCompanyId(), statisticsOfUsername); - profileStrenght = evaluateProfileStrenght(user, avatarPresent); + profileStrenght = ServerUtils.evaluateProfileStrenght(user, avatarPresent); long end = System.currentTimeMillis(); - _log.debug("[USER-STATISTICS] time taken to evaluate user profile strenght is " + (end - init) + "ms"); + logger.debug("[USER-STATISTICS] time taken to evaluate user profile strenght is " + (end - init) + "ms"); }catch(Exception e){ - _log.error("Profile strenght evaluation failed!!" + e.toString(), e); + logger.error("Profile strenght evaluation failed!!" + e.toString(), e); } } @@ -269,7 +190,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U public UserInformation getUserSettings(String userid) { // get the session - ASLSession session = getASLSession(); + ASLSession session = ServerUtils.getASLSession(this.getThreadLocalRequest().getSession()); //username of the asl session String userName = session.getUsername(); @@ -293,21 +214,21 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U statisticsOfUsername = userid; isProfileShowable = checkUserPrivacyOption(statisticsOfUsername); - _log.info("Is profile showable for user " + userid + " " + isProfileShowable); + logger.info("Is profile showable for user " + userid + " " + isProfileShowable); } //in case the portal is restarted and you have the social home open it will get test.user (no callback to set session info) //this check just return nothing if that happens if (userName.compareTo(defaultUserId) == 0) { - _log.debug("Found " + userName + " returning nothing"); + logger.debug("Found " + userName + " returning nothing"); return null; } - if(isWithinPortal()){ + if(ServerUtils.isWithinPortal()){ // If the user is in the root panel (or is visiting a profile page), we have to send him the overall number of posts made, comments/likes(received) and the space in use. // Otherwise we have to filter on the vre. - boolean isInfrastructure = isInfrastructureScope(userid); - _log.debug("User scope is " + (isInfrastructure ? " the whole infrastucture " : " a VRE")); + boolean isInfrastructure = ServerUtils.isInfrastructureScope(userid, this.getThreadLocalRequest().getSession()); + logger.debug("User scope is " + (isInfrastructure ? " the whole infrastucture " : " a VRE")); // get path of the avatar UserManager um = new LiferayUserManager(); @@ -316,12 +237,12 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U try { thumbnailURL = um.getUserByUsername(statisticsOfUsername).getUserAvatarURL(); } catch (UserManagementSystemException e) { - _log.error("Unable to retrieve avatar url for user " + statisticsOfUsername, e); + logger.error("Unable to retrieve avatar url for user " + statisticsOfUsername, e); } catch (UserRetrievalFault e) { - _log.error("Unable to retrieve avatar url for user " + statisticsOfUsername, e); + logger.error("Unable to retrieve avatar url for user " + statisticsOfUsername, e); } - _log.debug(statisticsOfUsername + " avatar has url " + thumbnailURL); + logger.debug(statisticsOfUsername + " avatar has url " + thumbnailURL); // get the vre (if not in the infrastructure) String actualVre = null; @@ -352,7 +273,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U try{ // set permission checker - setPermissionChecker(); + ServerUtils.setPermissionChecker(); //needed to avoid cache use by liferay API CacheRegistryUtil.clear(); @@ -367,7 +288,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U }catch(Exception e){ - _log.error("Unable to retrieve user's privacy option for his statistics"); + logger.error("Unable to retrieve user's privacy option for his statistics"); return true; } } @@ -376,7 +297,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U public PostsStatsBean getPostsStats(String userid){ // get the session - ASLSession session = getASLSession(); + ASLSession session = ServerUtils.getASLSession(this.getThreadLocalRequest().getSession()); //username String userName = session.getUsername(); @@ -390,31 +311,31 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U //in case the portal is restarted and you have the social home open it will get test.user (no callback to set session info) //this check just return nothing if that happens if (userName.compareTo(defaultUserId) == 0) { - _log.debug("Found " + userName + " returning nothing"); + logger.debug("Found " + userName + " returning nothing"); return null; } long feedsMade = 0, likesGot = 0, commentsGot = 0, commentsMade = 0, likesMade = 0; // check if the user is or not in a VRE - boolean isInfrastructure = isInfrastructureScope(userid); + boolean isInfrastructure = ServerUtils.isInfrastructureScope(userid, this.getThreadLocalRequest().getSession()); // date corresponding to one year ago Calendar oneYearAgo = Calendar.getInstance(); oneYearAgo.set(Calendar.YEAR, oneYearAgo.get(Calendar.YEAR) - 1); - _log.debug("Reference time is " + oneYearAgo.getTime()); + logger.debug("Reference time is " + oneYearAgo.getTime()); try { long init = System.currentTimeMillis(); - - _log.debug("Getting " + statisticsOfUsername + " feeds in the last year."); + + logger.debug("Getting " + statisticsOfUsername + " feeds in the last year."); // retrieve the most recent user's feeds List userFeeds = store.getRecentFeedsByUserAndDate(statisticsOfUsername, oneYearAgo.getTime().getTime()); - _log.debug("Evaluating number of comments and likes of " + statisticsOfUsername + "'s feeds."); + logger.debug("Evaluating number of comments and likes of " + statisticsOfUsername + "'s feeds."); for (Feed feed : userFeeds) { @@ -432,7 +353,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U likesGot += Integer.parseInt(feed.getLikesNo()); }catch(NumberFormatException e){ - _log.error(e.toString()); + logger.error(e.toString()); } } @@ -462,7 +383,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U } parentFeed = parentFeeds.get(comment.getFeedid()); - + // check if the user is in the root, if not check if the VRE of the feed is the current one if(!isInfrastructure && !parentFeed.getVreid().equals(session.getScope())) continue; @@ -472,15 +393,15 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U long end = System.currentTimeMillis(); - _log.debug("[USER-STATISTICS] time taken to retrieve statistics is " + (end - init) + " ms"); - _log.debug("Total number of feeds made (after time filtering) of " + statisticsOfUsername + " is " + feedsMade); - _log.debug("Total number of likes got (after time filtering) for " + statisticsOfUsername + " is " + likesGot); - _log.debug("Total number of comments got (after time filtering) for " + statisticsOfUsername + " is " + commentsGot); - _log.debug("Total number of likes made (after time filtering) for " + statisticsOfUsername + " is " + likesMade); - _log.debug("Total number of comments made (after time filtering) for " + statisticsOfUsername + " is " + commentsMade); + logger.debug("[USER-STATISTICS] time taken to retrieve statistics is " + (end - init) + " ms"); + logger.debug("Total number of feeds made (after time filtering) of " + statisticsOfUsername + " is " + feedsMade); + logger.debug("Total number of likes got (after time filtering) for " + statisticsOfUsername + " is " + likesGot); + logger.debug("Total number of comments got (after time filtering) for " + statisticsOfUsername + " is " + commentsGot); + logger.debug("Total number of likes made (after time filtering) for " + statisticsOfUsername + " is " + likesMade); + logger.debug("Total number of comments made (after time filtering) for " + statisticsOfUsername + " is " + commentsMade); }catch(Exception e){ - _log.error(e.toString()); + logger.error(e.toString()); return null; } @@ -491,28 +412,28 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U @Override public void setShowMyOwnStatisticsToOtherPeople(boolean show) { - if(isWithinPortal()){ + if(ServerUtils.isWithinPortal()){ - ASLSession session = getASLSession(); + ASLSession session = ServerUtils.getASLSession(this.getThreadLocalRequest().getSession()); String username = session.getUsername(); //in case the portal is restarted and you have the social home open it will get test.user (no callback to set session info) //this check just return nothing if that happens if (username.compareTo(defaultUserId) == 0) { - _log.debug("Found " + username + " returning nothing"); + logger.debug("Found " + username + " returning nothing"); return; } try{ // set permission checker - setPermissionChecker(); + ServerUtils.setPermissionChecker(); //needed to avoid cache use by liferay API CacheRegistryUtil.clear(); - _log.debug("User " + username + (show ? " want to show " : " doesn't want to show ") + " his statistics"); + logger.debug("User " + username + (show ? " want to show " : " doesn't want to show ") + " his statistics"); User user = UserLocalServiceUtil.getUserByScreenName(ManagementUtils.getCompany().getCompanyId(), username); boolean hasAttribute = user.getExpandoBridge().hasAttribute(CUSTOM_FIELD_NAME_USER_STATISTICS_VISIBILITY); @@ -520,7 +441,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U if(hasAttribute){ // set the new value - _log.debug("Setting custom field value to " + show + " for user " + username); + logger.debug("Setting custom field value to " + show + " for user " + username); // set the current value user.getExpandoBridge().setAttribute(CUSTOM_FIELD_NAME_USER_STATISTICS_VISIBILITY, show); @@ -528,201 +449,9 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U } }catch(Exception e){ - _log.error("Unable to check user's privacy for his statistics", e); + logger.error("Unable to check user's privacy for his statistics", e); } } } - - /** - * On servlet instanciation, create the custom field and set it to startingValue - * @param customFieldNameUserStatisticsVisibility - * @param b - */ - private void createUserCustomField( - String customFieldNameUserStatisticsVisibility, boolean startingValue) { - - // set permission checker - setPermissionChecker(); - - try{ - - User defaultUser = UserLocalServiceUtil.getDefaultUser(ManagementUtils.getCompany().getCompanyId()); - - // check if it exists - boolean exists = defaultUser.getExpandoBridge().hasAttribute(customFieldNameUserStatisticsVisibility); - - if(exists){ - - _log.debug("Custom field already exists... There is no need to create it"); - - }else{ - - _log.debug("Creating custom field " + customFieldNameUserStatisticsVisibility + - " with starting value " + startingValue); - - // create - defaultUser.getExpandoBridge().addAttribute(CUSTOM_FIELD_NAME_USER_STATISTICS_VISIBILITY, ExpandoColumnConstants.BOOLEAN, (Serializable)(true)); - - } - - }catch(Exception e){ - _log.error("Unable to create custom field " + customFieldNameUserStatisticsVisibility); - } - } - - /** - * returns dynamically the formated size. - * - * @param size the size - * @return the string - */ - private static String formatFileSize(long size) { - String formattedSize = null; - - double b = size; - double k = size/1024.0; - double m = ((size/1024.0)/1024.0); - double g = (((size/1024.0)/1024.0)/1024.0); - double t = ((((size/1024.0)/1024.0)/1024.0)/1024.0); - - DecimalFormat dec = new DecimalFormat("0.00"); - - if ( t >= 1.0 ) { - formattedSize = dec.format(t).concat(" TB"); - } else if ( g >= 1.0 ) { - formattedSize = dec.format(g).concat(" GB"); - } else if ( m >= 1.0 ) { - formattedSize = dec.format(m).concat(" MB"); - } else if ( k >= 1.0 ) { - formattedSize = dec.format(k).concat(" KB"); - } else { - formattedSize = dec.format(b).concat(" Bytes"); - } - return formattedSize; - } - - /** - * Evaluates the profile strenght of the user - * @param user - * @return a int in [0, 100] - */ - private static int evaluateProfileStrenght(User user, boolean imageIsPresent) { - - int score = evaluateContactScore(user); - score += evaluateInformationScore(user, imageIsPresent); - - return score; - } - - - /** - * Evaluates a score according to the information of the user such as job, organization, comments - * @param user - * @return a score in [0, 65] - */ - private static int evaluateInformationScore(User user, boolean imageIsPresent) { - int score = 0; - - if(user.getJobTitle() != null) - score += !user.getJobTitle().isEmpty() ? 20 : 0; - if(user.getOpenId() != null) - score += !user.getOpenId().isEmpty() ? 20 : 0; - String summary = getSummary(user); - if(summary != null){ - int lenght = summary.replace(" ", "").length(); - float partialScore = ((float)lenght / 10.0f); - score += partialScore > 20f ? 20 : (int)partialScore; - } - - if(imageIsPresent) - score += 5; - - return score; - } - - /** - * get the user's comment - * @param user - * @return - */ - private static String getSummary(User user) { - if(user.getComments() != null){ - String toReturn = escapeHtml(user.getComments()); - // replace all the line breaks by
    - toReturn = toReturn.replaceAll("(\r\n|\n)","
    "); - // then replace all the double spaces by the html version   - toReturn = toReturn.replaceAll("\\s\\s","  "); - return toReturn; - }else - return null; - } - - /** - * 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 - */ - private static String escapeHtml(String html) { - if (html == null) { - return null; - } - return html.replaceAll("&", "&").replaceAll("<", "<") - .replaceAll(">", ">"); - } - - /** - * Evaluates user's contact information - * @param user - * @return a value in [0, 35] - */ - private static int evaluateContactScore(User user){ - - int score = 0; - - try{ - Contact contact = user.getContact(); - - if(contact.getMySpaceSn() != null) - score += !contact.getMySpaceSn().isEmpty() ? 5 : 0; - if(contact.getTwitterSn() != null) - score += !contact.getTwitterSn().isEmpty() ? 5 : 0; - if(contact.getFacebookSn() != null) - score += !contact.getFacebookSn().isEmpty() ? 5 : 0; - if(contact.getSkypeSn() != null) - score += !contact.getSkypeSn().isEmpty() ? 5 : 0; - if(contact.getJabberSn() != null) - score += !contact.getJabberSn().isEmpty() ? 5 : 0; - if(contact.getAimSn() != null) - score += !contact.getAimSn().isEmpty() ? 5 : 0; - - List websites = WebsiteLocalServiceUtil.getWebsites(user.getCompanyId(), "com.liferay.portal.model.Contact", contact.getContactId()); - score += websites.size() > 0 ? 5 : 0; - }catch(Exception e ){ - - _log.error("Contact profile score evaluation failed!!"); - score = 0; - } - - return score; - } - - /** - * Set the permission checker to set/get custom fields into liferay - */ - private void setPermissionChecker(){ - - // set permission checker - try{ - long adminId = LiferayUserManager.getAdmin().getUserId(); - PrincipalThreadLocal.setName(adminId); - PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(UserLocalServiceUtil.getUser(adminId)); - PermissionThreadLocal.setPermissionChecker(permissionChecker); - }catch(Exception e){ - _log.error("Unable to set permission checker. Custom fields set/get operations are likely to fail..."); - } - - } } diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml index 5c96f44..018029a 100644 --- a/src/main/webapp/WEB-INF/web.xml +++ b/src/main/webapp/WEB-INF/web.xml @@ -24,15 +24,15 @@ /statistics/scopeService - - widgettourServlet - org.gcube.portlets.widgets.widgettour.server.TourManagerServicesImpl - + + + + - - widgettourServlet - /statistics/tourmanagerservice - + + + + diff --git a/src/test/java/org/gcube/portlet/user/userstatisticsportlet/client/TestForDeploy.java b/src/test/java/org/gcube/portlet/user/userstatisticsportlet/client/TestForDeploy.java index 6c3a8ed..ae686d1 100644 --- a/src/test/java/org/gcube/portlet/user/userstatisticsportlet/client/TestForDeploy.java +++ b/src/test/java/org/gcube/portlet/user/userstatisticsportlet/client/TestForDeploy.java @@ -1,7 +1,8 @@ package org.gcube.portlet.user.userstatisticsportlet.client; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; +import org.gcube.portlet.user.userstatisticsportlet.server.ServerUtils; import org.gcube.portlet.user.userstatisticsportlet.server.UserStatisticsServiceImpl; import org.junit.Test; @@ -9,8 +10,7 @@ public class TestForDeploy { @Test public void testUserIsTestUser() { - UserStatisticsServiceImpl serviceImpl = new UserStatisticsServiceImpl(); - String username = serviceImpl.getDevelopmentUser(); + String username = ServerUtils.getDevelopmentUser(); System.out.println("username for deploy is: " + username); assertTrue(username.compareTo(UserStatisticsServiceImpl.defaultUserId) == 0); System.out.println("Test OK!");