Added gcube-url-shortener as new dependency, so I've removed internal classes for shortener

git-svn-id: http://svn.d4science-ii.research-infrastructures.eu/gcube/trunk/portlets/user/workspace-tree-widget@131346 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Francesco Mangiacrapa 2016-09-14 12:30:33 +00:00
parent bc2c710a4e
commit 554b237a81
9 changed files with 154 additions and 559 deletions

View File

@ -4,6 +4,7 @@
<Change>[Feature #2335] Added "Get Folder Link" facility</Change>
<Change>[Incident #4878] Fixed: Workspace tree not displaying user's
name</Change>
<Change>Added 'gcube-url-shortener' dependency, removed internal classes for shortener</Change>
</Changeset>
<Changeset component="org.gcube.portlets-user.workspace-portlet-tree.6-13-0"
date="2016-05-31">

View File

@ -123,6 +123,13 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.portlets.user</groupId>
<artifactId>gcube-url-shortener</artifactId>
<version>[1.0.0-SNAPSHOT,2.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>accesslogger</artifactId>

View File

@ -43,6 +43,7 @@ import org.gcube.common.homelibrary.home.workspace.trash.WorkspaceTrashItem;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.datacatalogue.ckanutillibrary.CKanUtils;
import org.gcube.datacatalogue.ckanutillibrary.CkanUtilsFactory;
import org.gcube.portlets.user.urlshortener.UrlShortener;
import org.gcube.portlets.user.workspace.client.ConstantsExplorer;
import org.gcube.portlets.user.workspace.client.interfaces.GXTCategoryItemInterface;
import org.gcube.portlets.user.workspace.client.model.FileDetailsModel;
@ -62,7 +63,6 @@ import org.gcube.portlets.user.workspace.server.notifications.NotificationsUtil;
import org.gcube.portlets.user.workspace.server.reader.ApplicationProfile;
import org.gcube.portlets.user.workspace.server.reader.ApplicationProfileReader;
import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex;
import org.gcube.portlets.user.workspace.server.shortener.UrlShortener;
import org.gcube.portlets.user.workspace.server.util.AclTypeComparator;
import org.gcube.portlets.user.workspace.server.util.DifferenceBetweenInfoContactModel;
import org.gcube.portlets.user.workspace.server.util.UserUtil;
@ -2326,7 +2326,7 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT
}catch (Exception e) {
workspaceLogger.error("Error get short url for ", e);
return longUrl;
return null;
}
}
@ -2363,8 +2363,10 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT
String shortURL = null;
if(shortenUrl)
if(shortenUrl){
shortURL = getShortUrl(uriRequest);
shortURL = shortURL!=null?shortURL:"not available";
}
return new PublicLink(uriRequest, shortURL);
@ -3551,7 +3553,16 @@ public class GWTWorkspaceServiceImpl extends RemoteServiceServlet implements GWT
ApplicationProfileReader apReader = new ApplicationProfileReader("Workspace-Explorer-App", "org.gcube.portlets.user.workspaceexplorerapp.server.WorkspaceExplorerAppServiceImpl");
ApplicationProfile ap = apReader.readProfileFromInfrastrucure();
workspaceLogger.info("Application profile returning url: "+ap.getUrl());
return new PublicLink(ap.getUrl()+"?folderId="+folderId, "not available");
String folderLink = ap.getUrl()+"?folderId="+folderId;
String shortURL = null;
try{
shortURL = getShortUrl(folderLink);
shortURL = shortURL!=null?shortURL:"not available";
}catch(Exception e){
workspaceLogger.warn("Short url error, skipping");
shortURL = "not available";
}
return new PublicLink(folderLink, shortURL);
}else
throw new NoGcubeItemTypeException("The item is not a Gcube Item");

View File

@ -17,7 +17,7 @@ import org.apache.log4j.Logger;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.user.workspace.server.shortener.UrlEncoderUtil;
import org.gcube.portlets.user.workspace.server.util.UrlEncoderUtil;
import org.gcube.portlets.user.workspace.server.util.scope.ScopeUtilFilter;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.impl.XQuery;

View File

@ -1,179 +0,0 @@
/**
*
*/
package org.gcube.portlets.user.workspace.server.shortener;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* @Jun 4, 2013
*
*/
public class HttpCallerUtil {
public static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(HttpCallerUtil.class);
public static final int TIME_OUT_REQUESTS = 5000;
private String urlService = "";
private HttpClient httpClient = null;
private String username = "";
private String password = "";
public HttpCallerUtil(String url, String user, String password) {
this.urlService = url;
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setSoTimeout(TIME_OUT_REQUESTS);
this.httpClient = new HttpClient(connectionManager);
this.username = user;
this.password = password;
Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
}
public String callGet(String urlMethod, Map<String, String> parameters) throws Exception {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
String query = UrlEncoderUtil.encodeQueryValues(parameters);
String fullUrl = urlService+"/"+urlMethod+"?"+query;
logger.info("call get .... " + fullUrl);
// Create a method instance.
GetMethod method = new GetMethod(fullUrl);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.error("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary
// data
return new String(responseBody);
} catch (HttpException e) {
logger.error("Fatal protocol violation: " + e.getMessage());
throw new Exception("Fatal protocol violation: " + e.getMessage());
} catch (IOException e) {
logger.error("Fatal transport error: " + e.getMessage());
throw new Exception("Fatal transport violation: " + e.getMessage());
} finally {
// Release the connection.
method.releaseConnection();
}
}
public String callPost(String urlMethod, String body, String contentType) throws Exception {
// Create a method instance.
PostMethod method = new PostMethod(this.urlService + "/" + urlMethod);
method.setRequestHeader("Content-type", contentType);
logger.trace("call post .... " + this.urlService + "/" + urlMethod);
logger.debug(" call post body.... " + body);
// System.out.println("post body .... " + body);
method.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
// Provide custom retry handler is necessary
// method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));
byte[] responseBody = null;
try {
// Execute the method.
int statusCode = httpClient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
logger.error("Method failed: " + method.getStatusLine()+"; Response bpdy: "+method.getResponseBody());
method.releaseConnection();
throw new Exception("Method failed: " + method.getStatusLine()+"; Response body: "+new String(method.getResponseBody()));
}
// Read the response body.
responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
// System.out.println(new String(responseBody));
} catch (HttpException e) {
logger.error("Fatal protocol violation: ", e);
// e.printStackTrace();
method.releaseConnection();
throw new Exception("Fatal protocol violation: " + e.getMessage());
} catch (Exception e) {
logger.error("Fatal transport error: ", e);
// e.printStackTrace();
method.releaseConnection();
throw new Exception("Fatal transport error: " + e.getMessage());
}
method.releaseConnection();
return new String(responseBody);
}
public String getUrlservice() {
return urlService;
}
public void setUrlservice(String urlservice) {
this.urlService = urlservice;
}
public HttpClient getClient() {
return httpClient;
}
public void setClient(HttpClient client) {
this.httpClient = client;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -1,232 +0,0 @@
/**
*
*/
package org.gcube.portlets.user.workspace.server.shortener;
/**
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* @Jun 28, 2013
*
*/
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.log4j.Logger;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.user.workspace.server.util.scope.ScopeUtilFilter;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.impl.XQuery;
import org.json.JSONObject;
import org.json.JSONTokener;
public final class UrlShortener {
/**
*
*/
protected static final String NO_HTTP_URL_SHORTENER_AVAILABLE = "No HTTP URL Shortener available";
protected static final String APPLICATION_JSON = "application/json";
protected static final String LONG_URL = "longUrl";
// protected static String shortnerServerUrl = "https://www.googleapis.com/urlshortener/v1/url";
// protected static String urlMethod = "";
// protected static String authenticationKeyParam = "key";
// protected static String authenticationKeyValue ="AIzaSyDfMO0VY3o8GjRUqnTfqScjm_EsFEuBa3g";
private static String shortnerServerUrl = "";
protected static final String KEY = "key";
private static String paramKeyValue ="";
protected static Logger logger = Logger.getLogger(UrlShortener.class);
private String uriRequest;
private boolean isAvailable = false;
/*
* @throws Exception
* @throws InvalidResultException
* @throws DiscoveryException
* @throws IllegalStateException *
*
*/
public UrlShortener(String scope) throws Exception {
try{
logger.trace("Tentative reading HTTP-URL-Shortener RR");
ScopeUtilFilter scopeUtil = new ScopeUtilFilter(scope,true);
ScopeProvider.instance.set(scopeUtil.getScopeRoot());
XQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq 'HTTP-URL-Shortener'").setResult("$resource/Profile/AccessPoint");
DiscoveryClient<AccessPoint> client = clientFor(AccessPoint.class);
List<AccessPoint> endpoints = client.submit(query);
if (endpoints.size() == 0){
isAvailable = false;
logger.trace("HTTP-URL-Shortener not found");
throw new Exception(NO_HTTP_URL_SHORTENER_AVAILABLE);
}
//Base Address
// System.out.println(endpoints.get(0).address());
shortnerServerUrl = endpoints.get(0)!=null?endpoints.get(0).address():"";
if(endpoints.get(0)!=null){
paramKeyValue = endpoints.get(0).propertyMap()!=null?endpoints.get(0).propertyMap().get(KEY).value():"";
}
String getParam = "";
logger.trace("paramKeyValue: "+paramKeyValue);
//ACTIVE THIS AFTER RELEASE
if(paramKeyValue!=null && !paramKeyValue.isEmpty()){
getParam = "?"+KEY +"="+paramKeyValue;
}
uriRequest = shortnerServerUrl+getParam;
logger.trace("HTTP-URL-Shortener found, uriRequest: "+uriRequest);
//DEBUG
// System.out.println("HTTP-URL-Shortener found, uriRequest: "+uriRequest);
isAvailable = true;
}catch (Exception e) {
isAvailable = false;
logger.error("an error occurred in reading RR: ", e);
throw new Exception(NO_HTTP_URL_SHORTENER_AVAILABLE);
}finally{
ScopeProvider.instance.reset();
}
}
public boolean isAvailable() {
return isAvailable;
}
/**
*
* @param longUrl
* @return a shorten url
*/
public String shorten(String longUrl) throws Exception{
if (longUrl == null) {
return longUrl;
}
try {
logger.trace("shorten longUrl: "+longUrl);
URL url = new URL(uriRequest);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", APPLICATION_JSON);
JSONObject jsonObj = new JSONObject();
jsonObj.put(LONG_URL, longUrl);
// //ACTIVE THIS AFTER RELEASE
// if(paramKeyValue!=null && !paramKeyValue.isEmpty()){
// jsonObj.put(KEY, paramKeyValue);
// }
logger.trace("request json : "+jsonObj.toString());
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(jsonObj.toString());
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
JSONTokener tokener = new JSONTokener(rd);
JSONObject jsonObject = new JSONObject(tokener);
// JSONParser parser = new JSONParser();
// JSONObject jsonObject = (JSONObject) parser.parse(rd);
logger.trace("response received json : "+jsonObject.toString());
wr.close();
rd.close();
return (String) jsonObject.get("id"); //is shorted url
} catch (MalformedURLException e) {
logger.error("MalformedURLException error in UrlShortener", e);
return longUrl;
} catch (IOException e) {
e.printStackTrace();
logger.error("IOException error in UrlShortener", e);
return longUrl;
}
}
public static String getShortnerServerUrl() {
return shortnerServerUrl;
}
public static String getKey() {
return KEY;
}
public static String getParamKeyValue() {
return paramKeyValue;
}
public String getUriRequest() {
return uriRequest;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UrlShortener [uriRequest=");
builder.append(uriRequest);
builder.append(", isAvailable=");
builder.append(isAvailable);
builder.append("]");
return builder.toString();
}
public static void main(String[] args) {
String shorten;
try {
UrlShortener urlSh = new UrlShortener("/d4science.research-infrastructures.eu");
System.out.println("UrlShortener: "+urlSh);
shorten = urlSh.shorten("https://dev.d4science.org/group/data-e-infrastructure-gateway/workspace?itemid=056648-c7ce-4de3-a4c7-e1411816cc12&operation=gotofolder");
System.out.println("Shorted: "+shorten);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.portlets.user.workspace.server.shortener;
package org.gcube.portlets.user.workspace.server.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@ -9,13 +9,11 @@ import java.util.Map;
import org.apache.log4j.Logger;
/**
* The Class UrlEncoderUtil.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 13, 2016
* Sep 14, 2016
*/
public class UrlEncoderUtil {
@ -124,14 +122,4 @@ public class UrlEncoderUtil {
UrlEncoderUtil.charset = charset;
}
/*
public static void main(String[] args) {
// System.out.println(UrlEncoderUtil.encodeQuery("request=GetStyles", "layers=test Name", "service=WMS", "version=1.1.1"));
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("request", "GetStyles");
parameters.put("layers", "test Name");
parameters.put("version", "1.1.1");
System.out.println(UrlEncoderUtil.encodeQuery(parameters));
}*/
}

View File

@ -21,12 +21,12 @@ import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.exceptions.WorkspaceFolderNotFoundException;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.custom.scopemanager.scopehelper.ScopeHelper;
import org.gcube.portlets.user.urlshortener.UrlShortener;
import org.gcube.portlets.user.workspace.client.model.InfoContactModel;
import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder;
import org.gcube.portlets.user.workspace.server.notifications.NotificationsProducer;
import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex;
import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex.RESOLVER_TYPE;
import org.gcube.portlets.user.workspace.server.shortener.UrlShortener;
import org.gcube.portlets.user.workspace.server.util.resource.PropertySpecialFolderReader;
import org.gcube.portlets.user.workspace.server.util.scope.ScopeUtilFilter;

View File

@ -26,7 +26,6 @@ import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.user.workspace.server.GWTWorkspaceBuilder;
import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex;
import org.gcube.portlets.user.workspace.server.resolver.UriResolverReaderParameterForResolverIndex.RESOLVER_TYPE;
import org.gcube.portlets.user.workspace.server.shortener.UrlShortener;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.impl.XQuery;