The portlet now perform a request to get the quota information first, and in case of falilures it requires the storage directly

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/portlets/user/user-statistics@142493 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Costantino Perciante 2017-02-13 13:37:12 +00:00
parent c98f908390
commit 57baa7a957
5 changed files with 109 additions and 87 deletions

View File

@ -70,14 +70,12 @@ public class StatisticsPanel extends Composite {
private final static String ACTIVITY_LABEL = "Activity"; private final static String ACTIVITY_LABEL = "Activity";
private final static String LIKES_COMMENTS_GOT_LABEL = "Got"; private final static String LIKES_COMMENTS_GOT_LABEL = "Got";
private final static String STORAGE_LABEL = "Space Used"; private final static String STORAGE_LABEL = "Space Used";
protected static final String QUOTA_LABEL = "Space Quota";
private final static String PROFILE_STRENGTH_LABEL = "Profile Strength"; private final static String PROFILE_STRENGTH_LABEL = "Profile Strength";
private final static String SHOW_STATISTICS_OPTION_LABEL = "Show my statistics to VRE Members"; private final static String SHOW_STATISTICS_OPTION_LABEL = "Show my statistics to VRE Members";
/** /**
* Some tooltips * Some tooltips
*/ */
protected static final String TOOLTIP_QUOTA_SPACE = "Space used in the storage area is $USED of $ALLOWED";
private final static String TOOLTIP_ACTIVITY_ROOT_PROFILE = "Posts, likes, replies done during the last year"; private final static String TOOLTIP_ACTIVITY_ROOT_PROFILE = "Posts, likes, replies done during the last year";
private final static String TOOLTIP_ACTIVITY_VRE = "Posts, likes, replies done in the last year in this VRE"; private final static String TOOLTIP_ACTIVITY_VRE = "Posts, likes, replies done in the last year in this VRE";
private final static String TOOLTIP_GOT_ROOT_PROFILE = "Likes and post replies got during the last year"; private final static String TOOLTIP_GOT_ROOT_PROFILE = "Likes and post replies got during the last year";
@ -313,9 +311,8 @@ public class StatisticsPanel extends Composite {
// append widget // append widget
mainPanel.add(activityGotWidgetContainer); mainPanel.add(activityGotWidgetContainer);
// the storage, quota, and the profile strength(only in root) // the storage and the profile strength(only in root)
final StatisticWidget storage = new StatisticWidget(isRoot); final StatisticWidget storage = new StatisticWidget(isRoot);
final StatisticWidget quotaStorage = new StatisticWidget(isRoot);
final StatisticWidget profileStrength = new StatisticWidget(isRoot); final StatisticWidget profileStrength = new StatisticWidget(isRoot);
if(isRoot || isProfilePage){ if(isRoot || isProfilePage){
@ -330,16 +327,6 @@ public class StatisticsPanel extends Composite {
mainPanel.add(storage); mainPanel.add(storage);
quotaStorage.setHeader(QUOTA_LABEL);
quotaStorage.setToolTip(TOOLTIP_QUOTA_SPACE);
// add loading image that will be replaced by the incoming values
Image quotaLoader = new Image(imagePath);
quotaLoader.setStyleName("loading-image-center-small");
quotaStorage.appendToPanel(quotaLoader);
mainPanel.add(quotaStorage);
profileStrength.setHeader(PROFILE_STRENGTH_LABEL); profileStrength.setHeader(PROFILE_STRENGTH_LABEL);
profileStrength.setToolTip(TOOLTIP_PROFILE_STRENGHT); profileStrength.setToolTip(TOOLTIP_PROFILE_STRENGHT);
@ -351,60 +338,77 @@ public class StatisticsPanel extends Composite {
// add to the panel // add to the panel
mainPanel.add(profileStrength); mainPanel.add(profileStrength);
// async requests that must be performed in root context
statisticsService.getTotalSpaceInUse(userid, new AsyncCallback<String>() {
@Override
public void onFailure(Throwable arg0) {
appendAlertIcon(storage);
}
@Override
public void onSuccess(String spaceInUse) {
if(spaceInUse == null){
appendAlertIcon(storage);
}else{
storage.clearPanelValues();
Button storageValue = new Button();
storageValue.setType(ButtonType.LINK);
storageValue.setText(spaceInUse);
storageValue.addStyleName("buttons-statistics-disabled-events");
storage.appendToPanel(storageValue);
}
}
});
// require quota information // require quota information
statisticsService.getQuotaStorage(userid, new AsyncCallback<QuotaInfo>() { statisticsService.getQuotaStorage(userid, new AsyncCallback<QuotaInfo>() {
@Override @Override
public void onSuccess(QuotaInfo quota) { public void onSuccess(QuotaInfo quota) {
if(quota == null){ if(quota == null){
quotaStorage.setVisible(false); // ask for partial value
statisticsService.getTotalSpaceInUse(userid, new AsyncCallback<String>() {
@Override
public void onFailure(Throwable arg0) {
appendAlertIcon(storage);
}
@Override
public void onSuccess(String spaceInUse) {
if(spaceInUse == null){
appendAlertIcon(storage);
}else{
storage.clearPanelValues();
Button storageValue = new Button();
storageValue.setType(ButtonType.LINK);
storageValue.setText(spaceInUse);
storageValue.addStyleName("buttons-statistics-disabled-events");
storage.appendToPanel(storageValue);
}
}
});
}else{ }else{
long max = quota.getMax(); Float max = quota.getMax();
long current = quota.getCurrent(); Float current = quota.getCurrent();
long percent = Long.divideUnsigned(current, max); float percent = ((float)((double)current/(double)max)) * 100.0f;
quotaStorage.clearPanelValues(); String decimalFormat = NumberFormat.getFormat("#.##").format(percent);
storage.clearPanelValues();
Button quotaStorageValue = new Button(); Button quotaStorageValue = new Button();
quotaStorageValue.setType(ButtonType.LINK); quotaStorageValue.setType(ButtonType.LINK);
quotaStorageValue.setText(percent + "%"); quotaStorageValue.setText(decimalFormat + "%");
quotaStorageValue.addStyleName("buttons-statistics-disabled-events"); quotaStorageValue.setTitle("You are currently using " + NumberFormat.getFormat("#.##").format(current) + "MB out of " + max + "MB in the Infrastructure Storage");
quotaStorage.appendToPanel(quotaStorageValue); storage.appendToPanel(quotaStorageValue);
} }
} }
@Override @Override
public void onFailure(Throwable arg0) { public void onFailure(Throwable arg0) {
quotaStorage.setVisible(false); // ask for partial value
statisticsService.getTotalSpaceInUse(userid, new AsyncCallback<String>() {
@Override
public void onFailure(Throwable arg0) {
appendAlertIcon(storage);
}
@Override
public void onSuccess(String spaceInUse) {
if(spaceInUse == null){
appendAlertIcon(storage);
}else{
storage.clearPanelValues();
Button storageValue = new Button();
storageValue.setType(ButtonType.LINK);
storageValue.setText(spaceInUse);
storageValue.addStyleName("buttons-statistics-disabled-events");
storage.appendToPanel(storageValue);
}
}
});
} }
}); });
// require profile strenght // require profile strenght
statisticsService.getProfileStrength(userid, new AsyncCallback<Integer>() { statisticsService.getProfileStrength(userid, new AsyncCallback<Integer>() {

View File

@ -5,6 +5,8 @@ import java.text.DecimalFormat;
import java.util.List; import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.portal.PortalContext; import org.gcube.common.portal.PortalContext;
@ -14,6 +16,7 @@ import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser; import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.gcube.vomanagement.usermanagement.util.ManagementUtils; import org.gcube.vomanagement.usermanagement.util.ManagementUtils;
import org.w3c.dom.Document;
import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.log.LogFactoryUtil;
@ -306,5 +309,24 @@ public class ServerUtils {
} }
} }
} }
/**
* Parse an xml object for quota information
* @param doc
* @param xpath
* @return
*/
public static Float queryQuotaService(Document doc, XPath xpath, String exprQuery) {
Float value = null;
logger.debug("Going to execute query " + exprQuery + " against " + doc.toString());
try {
//evaluate expression result on XML document
String text = xpath.evaluate(exprQuery, doc.getDocumentElement());
value = Float.valueOf(text);
} catch (XPathExpressionException e) {
logger.error("Parsing failed", e);
}
return value;
}
} }

View File

@ -14,9 +14,12 @@ import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactory;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.homelibrary.home.HomeLibrary; import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.workspace.Workspace; import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.portal.PortalContext; import org.gcube.common.portal.PortalContext;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.custom.communitymanager.SiteManagerUtil;
import org.gcube.portal.databook.server.DBCassandraAstyanaxImpl; import org.gcube.portal.databook.server.DBCassandraAstyanaxImpl;
import org.gcube.portal.databook.server.DatabookStore; import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.portal.databook.shared.Comment; import org.gcube.portal.databook.shared.Comment;
@ -78,29 +81,29 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U
QuotaInfo toReturn = null; QuotaInfo toReturn = null;
String userName = null; String userName = null;
String quotaOfUser = null;
if(quotaServiceBaseUrl != null){ if(quotaServiceBaseUrl != null){
userName = ServerUtils.getCurrentUser(this.getThreadLocalRequest()).getUsername(); userName = ServerUtils.getCurrentUser(this.getThreadLocalRequest()).getUsername();
String quotaOfUser = userName;
// do not show quota info to other users // do not show quota info to other users
if(userid != null && !userid.equals(userName)) if(userid != null && !userid.equals(userName))
return null; quotaOfUser = userid;
quotaOfUser = userName;
logger.debug("Fetching info for quota of user " + quotaOfUser); logger.debug("Fetching info for quota of user " + quotaOfUser);
try{ try{
UserInfrastructureQuotaStorageCache cache = UserInfrastructureQuotaStorageCache.getCacheInstance(); UserInfrastructureQuotaStorageCache cache = UserInfrastructureQuotaStorageCache.getCacheInstance();
if(cache.get(userName) != null) if(cache.get(quotaOfUser) != null)
toReturn = cache.get(userName); toReturn = cache.get(quotaOfUser);
else{ else{
// ask the service ... // ask the service ...
PortalContext pContext = PortalContext.getConfiguration(); PortalContext pContext = PortalContext.getConfiguration();
String rootContextToken = pContext.getCurrentUserToken("/" + pContext.getInfrastructureName(), userName); String rootContextToken = pContext.getCurrentUserToken("/" + pContext.getInfrastructureName(), quotaOfUser);
URL request = new URL(quotaServiceBaseUrl + "?timeinterval=FOREVER&gcube-token=" + rootContextToken); URL request = new URL(quotaServiceBaseUrl + "?timeinterval=FOREVER&gcube-token=" + rootContextToken);
InputStream result = request.openStream(); InputStream result = request.openStream();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
@ -109,15 +112,18 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U
document.getDocumentElement().normalize(); document.getDocumentElement().normalize();
logger.debug("Result is " + document); logger.debug("Result is " + document);
// look for the properties
// TO BE PARSED TODO
XPathFactory xpf = XPathFactory.newInstance(); XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath(); XPath xpath = xpf.newXPath();
//String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()", Float maxQuota = ServerUtils.queryQuotaService(document, xpath, "/quotaStatus/quotaValue/text()");
// document.getDocumentElement()); Float usageQuota = ServerUtils.queryQuotaService(document, xpath, "/quotaStatus/quotaUsage/text()");
// PUSH INTO THE CACHE logger.debug("Information retrieved are: maxQuota=" + maxQuota + " and usageQuota=" + usageQuota);
if(usageQuota != null && maxQuota != null && maxQuota > 0){
toReturn = new QuotaInfo(maxQuota, usageQuota);
cache.insert(quotaOfUser, toReturn);
}
} }
}catch(Exception e){ }catch(Exception e){
logger.error("Failed to retrieve quota information for user", e); logger.error("Failed to retrieve quota information for user", e);
@ -125,7 +131,7 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U
} }
logger.debug("Quota for user " + userName + " is " + toReturn); logger.debug("Quota for user " + quotaOfUser + " is " + toReturn);
return toReturn; return toReturn;
} }
@ -133,15 +139,6 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U
public String getTotalSpaceInUse(String userid) { public String getTotalSpaceInUse(String userid) {
String storageInUse = null; String storageInUse = null;
String userName = ServerUtils.getCurrentUser(this.getThreadLocalRequest()).getUsername(); String userName = ServerUtils.getCurrentUser(this.getThreadLocalRequest()).getUsername();
// get context & token and set
ServerUtils.getCurrentContext(this.getThreadLocalRequest(), true);
ServerUtils.getCurrentSecurityToken(this.getThreadLocalRequest(), true);
if(userName == null){
logger.warn("Unable to determine the current user, returing null");
}
String statisticsOfUsername = userName; String statisticsOfUsername = userName;
if(userid != null && !userid.equals(userName)) if(userid != null && !userid.equals(userName))
@ -151,13 +148,13 @@ public class UserStatisticsServiceImpl extends RemoteServiceServlet implements U
try{ try{
UserInfrastructureSpaceCache cacheWorkspace = UserInfrastructureSpaceCache.getCacheInstance(); UserInfrastructureSpaceCache cacheWorkspace = UserInfrastructureSpaceCache.getCacheInstance();
Long storageInUseLong = (Long) cacheWorkspace.get(statisticsOfUsername); Long storageInUseLong = (Long) cacheWorkspace.get(statisticsOfUsername);
if(storageInUseLong == null){ if(storageInUseLong == null){
String userToken = PortalContext.getConfiguration().getCurrentUserToken(ScopeProvider.instance.get(), statisticsOfUsername);
SecurityTokenProvider.instance.set(userToken);
Workspace workspace = HomeLibrary.getUserWorkspace(statisticsOfUsername); Workspace workspace = HomeLibrary.getUserWorkspace(statisticsOfUsername);
storageInUseLong = workspace.getDiskUsage(); storageInUseLong = workspace.getDiskUsage();
cacheWorkspace.insert(statisticsOfUsername, storageInUseLong); cacheWorkspace.insert(statisticsOfUsername, storageInUseLong);
} }
storageInUse = ServerUtils.formatFileSize(storageInUseLong); storageInUse = ServerUtils.formatFileSize(storageInUseLong);
}catch(Exception e){ }catch(Exception e){
logger.error("Unable to retrieve workspace information!", e); logger.error("Unable to retrieve workspace information!", e);

View File

@ -31,7 +31,7 @@ public class UserInfrastructureQuotaStorageCache implements CacheInterface<Strin
/** /**
* Cache entry expires after EXPIRED_AFTER ms * Cache entry expires after EXPIRED_AFTER ms
*/ */
private static final long EXPIRED_AFTER = 1000 * 60 * 60; // an hour private static final long EXPIRED_AFTER = 1000 * 60 * 10;
/** /**
* Private constructor * Private constructor

View File

@ -8,29 +8,28 @@ import java.io.Serializable;
*/ */
public class QuotaInfo implements Serializable{ public class QuotaInfo implements Serializable{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = -7823313890536756579L;
private long max; private Float max;
private long current; private Float current;
public QuotaInfo() { public QuotaInfo() {
super(); super();
} }
public QuotaInfo(long max, long current) { public QuotaInfo(Float max, Float current) {
super(); super();
this.max = max; this.max = max;
this.current = current; this.current = current;
} }
public long getMax() { public Float getMax() {
return max; return max;
} }
public void setMax(long max) { public void setMax(Float max) {
this.max = max; this.max = max;
} }
public long getCurrent() { public Float getCurrent() {
return current; return current;
} }
public void setCurrent(long current) { public void setCurrent(Float current) {
this.current = current; this.current = current;
} }
@Override @Override