You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
catalogue-badge-portlet/src/main/java/org/gcube/portlets/user/cataloguebadge/PortletViewController.java

212 lines
8.2 KiB
Java

package org.gcube.portlets.user.cataloguebadge;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import javax.portlet.PortletPreferences;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;
import org.gcube.common.portal.GCubePortalConstants;
import org.gcube.common.portal.PortalContext;
import org.gcube.datacatalogue.ckanutillibrary.server.ApplicationProfileScopePerUrlReader;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogueFactory;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogueImpl;
import org.gcube.datacatalogue.ckanutillibrary.shared.Statistics;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ReleaseInfo;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.Group;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
@Controller
@RequestMapping("VIEW")
public class PortletViewController {
private static Log _log = LogFactoryUtil.getLog(PortletViewController.class);
// private static final String IMAGES_BASE_URL = "https://catalogue.d4science.org/";
private static final long K = 1000;
private static final long M = K * K;
private static final long G = M * K;
private DataCatalogueFactory factory = DataCatalogueFactory.getFactory();
private static GroupManager gm = new LiferayGroupManager();
@RenderMapping
public String question(RenderRequest request,RenderResponse response, Model model) {
model.addAttribute("releaseInfo", ReleaseInfo.getReleaseInfo());
PortletPreferences prefs = request.getPreferences();
String catalogueBaseURL = GetterUtil.getString(prefs.getValue("catalogueURL", StringPool.BLANK));
String catalogueTypes2Show = GetterUtil.getString(prefs.getValue("catalogueTypes2ShowNo", StringPool.BLANK));
int typesNo = 5;
if (catalogueTypes2Show != null && !catalogueTypes2Show.equals(StringPool.BLANK)) {
try{
typesNo = Integer.parseInt(catalogueTypes2Show);
} catch (Exception e) {
System.out.println(e.getMessage());
typesNo = 5;
}
}
model.addAttribute("catalogueActualURL", catalogueBaseURL);
HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(request);
long groupId = -1;
boolean isRootVO = false;
String catalogueURL = "";
try {
groupId = PortalUtil.getScopeGroupId(request);
isRootVO = gm.isRootVO(groupId);
catalogueURL = getCatalougeFriendlyURL(GroupLocalServiceUtil.getGroup(groupId));
} catch (Exception e1) {
e1.printStackTrace();
}
model.addAttribute("isRootVO", isRootVO);
if (catalogueBaseURL != null && catalogueBaseURL.compareTo("") != 0) { //if the config textbox with catalogueURL is filled in we show the types
try {
List<CatalogueType> theTypes = parseTypes(catalogueBaseURL+"/type", catalogueURL, catalogueBaseURL);
Collections.sort(theTypes, Collections.reverseOrder());
List<CatalogueType> theFiveTypes = new ArrayList<>();
int limit = typesNo-1;
if (theTypes.size() <= limit)
limit = theTypes.size()-1;
for (int i = 0; i <= limit; i++) {
theFiveTypes.add(theTypes.get(i));
}
model.addAttribute("catalogueTypes", theFiveTypes);
model.addAttribute("catalogueURL", catalogueURL);
} catch (Exception e) {
e.printStackTrace();
}
}
else { //in VRE
try {
PortalContext pContext = PortalContext.getConfiguration();
String context = pContext.getCurrentScope(""+groupId);
DataCatalogueImpl utils = null;
if (isRootVO) {
String gatewaySiteURL = pContext.getGatewayURL(httpServletRequest);
if (!gatewaySiteURL.startsWith("https"))
gatewaySiteURL = gatewaySiteURL.replaceAll("http:", "https:");
String siteLandingPage = pContext.getSiteLandingPagePath(httpServletRequest);
String clientURL = gatewaySiteURL+siteLandingPage;
try {
String appPerScopeURL = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientURL);
_log.info("Catalogue for this Gateway is in this scope: " + appPerScopeURL);
utils = factory.getUtilsPerScope(appPerScopeURL);
_log.info("Here I instanciated factory.getUtilsPerScope with scope " + appPerScopeURL);
} catch (Exception e) {
_log.warn("Returning default catalogue for the context, could not find the catologue for this Gateway: " + clientURL);
utils = factory.getUtilsPerScope(context);
}
}
else {
utils = factory.getUtilsPerScope(context);
_log.info("regular factory.getUtilsPerScope with context: " + context);
}
Statistics stats = utils.getStatistics();
_log.info("Got Statistics ... ");
model.addAttribute("itemsNo", convertToStringRepresentation(stats.getNumItems()));
model.addAttribute("groupsNo", stats.getNumGroups());
model.addAttribute("organisationsNo", stats.getNumOrganizations());
model.addAttribute("typesNo", stats.getNumTypes());
model.addAttribute("catalogueURL", catalogueURL);
} catch (Exception e) {
e.printStackTrace();
}
}
return "Catalogue-badge-portlet/view";
}
private List<CatalogueType> parseTypes(String url, String catalogueURL, String catalogueBaseURL) throws Exception {
List<CatalogueType> toReturn = new ArrayList<>();
Document doc = Jsoup.connect(url)
.userAgent("Mozilla")
.timeout(5000)
.referrer("http://www.d4science.org")
.header("headersecurity", "xyz123")
.get();
Elements types = doc.select("article li");
for (Element type : types) {
Element imgElement = type.select("div img").first();
String imgUrl = imgElement.attr("src");
Element aElement = type.select("h3 a").first();
Element h3Element = type.select("h3").first();
//String href = aElement.attr("href");
String name = aElement.text();
String nameAndOccurrence = h3Element.text();
int occurrence = 0;
String query = "systemtype="+name;
String encodedQuery = Base64.getEncoder().encodeToString(query.getBytes());
String hrefPortlet = catalogueURL+"?path=dataset&query="+encodedQuery;
try {
int bracketOpen = nameAndOccurrence.indexOf("(");
int brackeClosed = nameAndOccurrence.indexOf(")");
String numberToParse = nameAndOccurrence.substring(bracketOpen+1, brackeClosed);
occurrence = Integer.parseInt(numberToParse);
} catch (Exception e) {
_log.error("Could not find occurrence in string "+ nameAndOccurrence);
}
toReturn.add(new CatalogueType(name, catalogueBaseURL+imgUrl, hrefPortlet, occurrence));
}
return toReturn;
}
public static String convertToStringRepresentation(final long value){
final long[] dividers = new long[] { G, M, K, 1 };
final String[] units = new String[] {"Giga", "M", "K", ""};
if(value < 1)
throw new IllegalArgumentException("Invalid file size: " + value);
String result = null;
for(int i = 0; i < dividers.length; i++){
final long divider = dividers[i];
if(value >= divider){
result = format(value, divider, units[i]);
break;
}
}
return result;
}
private static String format(final long value,
final long divider,
final String unit){
final double result =
divider > 1 ? (double) value / (double) divider : (double) value;
return new DecimalFormat("#,##0.#").format(result) + " " + unit;
}
/**
* @param currentGroup
* @return Returns the friendly u r l of this group.
*/
private static String getCatalougeFriendlyURL(final Group currentGroup) throws Exception {
String friendlyURL = GCubePortalConstants.PREFIX_GROUP_URL;
StringBuffer sb = new StringBuffer();
sb.append(friendlyURL).append(currentGroup.getFriendlyURL())
.append(GCubePortalConstants.CATALOGUE_FRIENDLY_URL);
return sb.toString();
}
}