removed unused classes

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/data-transfer/uri-resolver@173982 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Francesco Mangiacrapa 2018-11-06 13:43:47 +00:00
parent c8b415bebd
commit cb45b401a1
35 changed files with 363 additions and 2440 deletions

View File

@ -1,25 +0,0 @@
/**
*
*/
package org.gcube.datatransfer.resolver;
import javax.servlet.ServletException;
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Aug 29, 2017
*/
public class BadRequestException extends ServletException {
private static final long serialVersionUID = 567117691399245474L;
public BadRequestException() {
super();
}
public BadRequestException(String arg0){
super(arg0);
}
}

View File

@ -1,6 +0,0 @@
package org.gcube.datatransfer.resolver;
public class Constants {
public static final String SERVLET_GEONETWORK = "geonetwork";
}

View File

@ -1,123 +0,0 @@
/**
*
*/
package org.gcube.datatransfer.resolver;
import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters.MODE;
import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters.VISIBILITY;
/**
* The Class GeonetworkRequestCriteria.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jun 15, 2016
*/
public class GeonetworkRequestCriteria {
private String scope;
private MODE mode;
private String owner; //This is optional
private VISIBILITY visibility;
/**
* @param scope
* @param mode
* @param owner
* @param visibility
*/
public GeonetworkRequestCriteria(
String scope, MODE mode, String owner, VISIBILITY visibility) {
super();
this.scope = scope;
this.mode = mode;
this.owner = owner;
this.visibility = visibility;
}
/**
* @return the scope
*/
public String getScope() {
return scope;
}
/**
* @return the mode
*/
public MODE getMode() {
return mode;
}
/**
* @return the owner
*/
public String getOwner() {
return owner;
}
/**
* @return the visibility
*/
public VISIBILITY getVisibility() {
return visibility;
}
/**
* @param scope the scope to set
*/
public void setScope(String scope) {
this.scope = scope;
}
/**
* @param mode the mode to set
*/
public void setMode(MODE mode) {
this.mode = mode;
}
/**
* @param owner the owner to set
*/
public void setOwner(String owner) {
this.owner = owner;
}
/**
* @param visibility the visibility to set
*/
public void setVisibility(VISIBILITY visibility) {
this.visibility = visibility;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("GeonetworkRequestCriteria [scope=");
builder.append(scope);
builder.append(", mode=");
builder.append(mode);
builder.append(", owner=");
builder.append(owner);
builder.append(", visibility=");
builder.append(visibility);
builder.append("]");
return builder.toString();
}
}

View File

@ -1,242 +0,0 @@
///**
// *
// */
//package org.gcube.datatransfer.resolver;
//
//import javax.servlet.ServletException;
//
//import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters.MODE;
//import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters.VISIBILITY;
//import org.gcube.datatransfer.resolver.gis.geonetwork.GeonetworkResolver;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//
///**
// * The Class GeonetworkRequestDecoder.
// *
// * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
// * Jul 27, 2016
// *
// * This class parses a request from servletpath and queryString
// *
// * The request must be: SCOPE#PARMETERS
// * SCOPE must be: separated by {@link GeonetworkRequestDecoder#SCOPE_SEPARATOR}
// * PARAMETERS can be:
// * {@link GeonetworkResolver#PARAMETER_FILTER_PUBLIC_IDS}
// * {@link GeonetworkResolver#PARAMETER_NO_AUTHENTICATION}
// */
//public class GeonetworkRequestDecoder {
//
// /**
// *
// */
// public static final String SCOPE_SEPARATOR = "|";
//
// public static final Logger logger = LoggerFactory.getLogger(GeonetworkRequestDecoder.class);
//
// private String gnResolverUriRequest;
//
// private GeonetworkRequestCriteria geonetworkRequestCriteria;
//
// /**
// * Instantiates a new geonetwork request decoder.
// *
// * @param theServletPath the the servlet path
// * @param queryString the query string
// * @throws ServletException the servlet exception
// */
// public GeonetworkRequestDecoder(String theServletPath, String queryString) throws ServletException{
//
// int index = theServletPath.indexOf(GeonetworkRequestFilterParameters.REQUEST_DELIMITIER);
//
// if(index==-1)
// throw new BadRequestException("Invalid request. Your request must append the '"+GeonetworkRequestFilterParameters.REQUEST_DELIMITIER+"' as final delimiter");
//
// int delimiterIndex = index+GeonetworkRequestFilterParameters.REQUEST_DELIMITIER.length();
//
// String pathWithoutGN = theServletPath.substring(UriResolverRewriteFilter.SERVLET_GEONETWORK.length()+1, index);
// logger.debug("servlet path without "+UriResolverRewriteFilter.SERVLET_GEONETWORK + " is: " +pathWithoutGN);
// geonetworkRequestCriteria = getGeonetworkRequestCriteria(pathWithoutGN);
// logger.info("performing query by filters: "+geonetworkRequestCriteria);
// logger.debug("scope value is: "+geonetworkRequestCriteria.getScope());
// //newURI = UriResolverRewriteFilter.SERVLET_GEONETWORK + "?" + GeonetworkResolver.SCOPE + "=" + geonetworkRequestCriteria.getScope() +"&"+ GeonetworkResolver.PARAMETER_FILTER_PUBLIC_IDS +"="+geonetworkRequestCriteria.isValueOfFilterPublicIds() +"&"+GeonetworkResolver.PARAMETER_NO_AUTHENTICATION+"="+geonetworkRequestCriteria.isNoAuthOnGeonetwork();
//
// gnResolverUriRequest = UriResolverRewriteFilter.SERVLET_GEONETWORK + "?"
// + GeonetworkResolver.SCOPE + "=" + geonetworkRequestCriteria.getScope() +"&"
// + GeonetworkRequestFilterParameters.MODE.class.getSimpleName() +"="+geonetworkRequestCriteria.getMode() +"&"
// + GeonetworkRequestFilterParameters.VISIBILITY.class.getSimpleName()+"="+geonetworkRequestCriteria.getVisibility();
//
// if(geonetworkRequestCriteria.getOwner()!=null){
// gnResolverUriRequest+="&"+GeonetworkRequestFilterParameters.OWNER_PARAM +"="+geonetworkRequestCriteria.getOwner();
// }
//
// //BUILDING REMAINING PATH WITHOUT GeonetworkRequestFilterParameters.REQUEST_DELIMITIER
// if(delimiterIndex<theServletPath.length()){
// String remainPath = theServletPath.substring(delimiterIndex, theServletPath.length());
// gnResolverUriRequest +="&"+GeonetworkResolver.REMAIN_PATH_PARAM+"="+remainPath;
// }
//
// if(queryString!=null && !queryString.isEmpty())
// gnResolverUriRequest+="&"+queryString;
//
// logger.info("built Geonetwork Resolver GET Request: "+gnResolverUriRequest);
// /*
// String[] params = pathWithoutGN.split("/");
// if(params[0]==null || params[0].isEmpty()){
// logger.error("Scope is null or empty, you must set a valid scope /geonetwork/root|vo|vre");
// throw new ServletException("Scope is null or empty, you must set a valid scope /geonetwork/root"+SCOPE_SEPARATOR+"vo"+SCOPE_SEPARATOR+"vre");
// }
//
// geonetworkRequestCriteria = getGeonetworkRequestCriteria(params[0]);
// logger.debug("scope value is: "+geonetworkRequestCriteria.getScope());
// newURI = UriResolverRewriteFilter.SERVLET_GEONETWORK + "?" + GeonetworkResolver.SCOPE + "=" + geonetworkRequestCriteria.getScope() +"&"+ GeonetworkResolver.PARAMETER_FILTER_PUBLIC_IDS +"="+geonetworkRequestCriteria.isValueOfFilterPublicIds() +"&"+GeonetworkResolver.PARAMETER_NO_AUTHENTICATION+"="+geonetworkRequestCriteria.isNoAuthOnGeonetwork();
// logger.debug(GeonetworkResolver.PARAMETER_FILTER_PUBLIC_IDS +" is: "+geonetworkRequestCriteria.isValueOfFilterPublicIds());
// logger.debug(GeonetworkResolver.PARAMETER_NO_AUTHENTICATION +" is: "+geonetworkRequestCriteria.isNoAuthOnGeonetwork());
// */
//// if(params.length>1){
//// String remainPath = "";
////// newURI +="&remainPath=";
//// for (int i = 1; i < params.length; i++) {
//// String httpGetParam = params[i];
//// if(httpGetParam!=null && !httpGetParam.isEmpty())
//// remainPath+="/"+httpGetParam;
//// }
//// newURI +="&"+GeonetworkResolver.REMAIN_PATH+"="+remainPath;
//// }
////
//// if(queryString!=null && !queryString.isEmpty())
//// newURI+="&"+queryString;
//
// }
//
//
// /**
// * Gets the geonetwork request criteria.
//
// * Creates a request criteria from input parameter pathWithoutGN
// * The parameter pathWithoutGN should be an ordered string (like REST request):
// * MODE/SCOPE/VISIBILITY/OWNER
// * MODE must be: {@link MODE}
// * SCOPE must be: ROOT|VO|VRE
// * VISIBILITY must be: {@link VISIBILITY}
// * OWNER (is optional): filter by owner
// * @param pathWithoutGN the path without Geonetwork base URL
// *
// * @return the geonetwork request criteria
// * @throws ServletException the servlet exception
// */
// private static GeonetworkRequestCriteria getGeonetworkRequestCriteria(String pathWithoutGN) throws ServletException{
//
// String[] params = pathWithoutGN.split("/");
// MODE mode = null;
// String theScope = null;
// VISIBILITY visibility = null;
// String owner = null;
//
// if(params.length < 3){
// throw new BadRequestException("Bad request. Read the request "+pathWithoutGN+". You must pass a valid request like [GEONETWORK_BASE_URL]/SCOPE/MODE/VISIBILITY/OWNER");
// }
//
// //SCOPE
// if(params[0]!=null && !params[0].isEmpty()){
// theScope = params[0];
// logger.debug("Read parameter scope: "+theScope);
// theScope = theScope.replaceAll("\\"+SCOPE_SEPARATOR, "/");
// if (!theScope.startsWith("/"))
// theScope="/"+theScope;
// }else{
// logger.error("The first parameter 'scope' is null or empty, you must set a valid scope as ROOT"+SCOPE_SEPARATOR+"VO"+SCOPE_SEPARATOR+"VRE as first parameter");
// throw new ServletException("Scope is null or empty. You must pass a valid scope as ROOT"+SCOPE_SEPARATOR+"VO"+SCOPE_SEPARATOR+"VRE as first parameter");
// }
//
// //MODE
// if(params[1]!=null && !params[1].isEmpty()){
// String modeTU = params[1].toUpperCase();
// logger.debug("Read parameter mode (to upper case): "+modeTU);
// try{
// mode = MODE.valueOf(modeTU);
// if(mode==null){
// logger.error("Mode is null");
// throw new Exception("Mode is null");
// }
//
// logger.info("MODE IS: "+mode);
//
// }catch (Exception e) {
// logger.error("The second parameter is wrong, Have you pass a valid parameter MODE like vre/harvest?");
// throw new BadRequestException("Bad parameter. You must set a valid MODE parameter as "+MODE.VRE + " or "+MODE.HARVEST+" as second parameter");
// }
// }else
// throw new BadRequestException("The parameter MODE is null or empty. You must pass a valid MODE parameter as "+MODE.VRE + " or "+MODE.HARVEST +" as second parameter");
//
// //VISIBILITY
// if(params[2]!=null && !params[2].isEmpty()){
// String visTU = params[2].toUpperCase();
// logger.debug("Read parameter mode (to upper case): "+visTU);
// try{
// visibility = VISIBILITY.valueOf(visTU);
// if(visibility==null){
// logger.error("VISIBILITY is null");
// throw new Exception("VISIBILITY is null");
// }
//
// logger.info("VISIBILITY IS: "+visibility);
//
// }catch (Exception e) {
// logger.error("The third parameter is wrong, Have you pass a valid parameter VISIBILITY like vre/harvest?");
// throw new BadRequestException("Bad parameter. You must set a valid VISIBILITY parameter as "+VISIBILITY.PRV + " or "+VISIBILITY.PUB+ " as third parameter");
// }
// }else
// throw new BadRequestException("The parameter VISIBILITY is null or empty. You must pass a valid VISIBILITY parameter as "+VISIBILITY.PRV + " or "+VISIBILITY.PUB +" as third parameter");
//
//
// //OWNER
// if(params.length > 3 && params[3]!=null && params[3]!=GeonetworkRequestFilterParameters.REQUEST_DELIMITIER){
// owner = params[3];
// logger.debug("Read parameter owner: "+owner);
// }
//
// return new GeonetworkRequestCriteria(theScope, mode, owner, visibility);
// }
//
//
// /**
// * Gets the geonetwork resolver uri request.
// *
// * @return the geonetwork resolver uri request
// */
// public String getGeonetworkResolverURIRequest() {
//
// return gnResolverUriRequest;
// }
//
// /**
// * Gets the geonetwork request criteria.
// *
// * @return the geonetworkRequestCriteria
// */
// public GeonetworkRequestCriteria getGeonetworkRequestCriteria() {
//
// return geonetworkRequestCriteria;
// }
//
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
//
// StringBuilder builder = new StringBuilder();
// builder.append("GeonetworkRequestDecoder [gnResolverUriRequest=");
// builder.append(gnResolverUriRequest);
// builder.append(", geonetworkRequestCriteria=");
// builder.append(geonetworkRequestCriteria);
// builder.append("]");
// return builder.toString();
// }
//
//
//
//}

View File

@ -1,181 +1,181 @@
/**
*
*/
package org.gcube.datatransfer.resolver;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
/**
* The Class MultiReadHttpServletRequest.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Apr 26, 2016
*/
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private ByteArrayOutputStream cachedBytes;
private final Map<String, String[]> modifiableParameters;
private Map<String, String[]> allParameters = null;
/**
* Instantiates a new multi read http servlet request.
*
* @param request the request
*/
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
modifiableParameters = new TreeMap<String, String[]>();
}
/**
* Create a new request wrapper that will merge additional parameters into
* the request object without prematurely reading parameters from the
* original request.
*
* @param request
* the request
* @param additionalParams
* the additional params
*/
public MultiReadHttpServletRequest(
final HttpServletRequest request,
final Map<String, String[]> additionalParams) {
super(request);
modifiableParameters = new TreeMap<String, String[]>();
modifiableParameters.putAll(additionalParams);
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequestWrapper#getInputStream()
*/
@Override
public ServletInputStream getInputStream() throws IOException {
if (cachedBytes == null)
cacheInputStream();
return new CachedServletInputStream();
}
/* (non-Javadoc)
* @see javax.servlet.ServletRequestWrapper#getReader()
*/
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
/**
* Cache input stream.
*
* @throws IOException Signals that an I/O exception has occurred.
*/
private void cacheInputStream()
throws IOException {
/*
* Cache the inputstream in order to read it multiple times. For
* convenience, I use apache.commons IOUtils
*/
cachedBytes = new ByteArrayOutputStream();
IOUtils.copy(super.getInputStream(), cachedBytes);
}
/* An inputstream which reads the cached request body */
/**
* The Class CachedServletInputStream.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Apr 26, 2016
*/
public class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream input;
/**
* Instantiates a new cached servlet input stream.
*/
public CachedServletInputStream() {
/* create a new input stream from the cached request body */
input = new ByteArrayInputStream(cachedBytes.toByteArray());
}
/* (non-Javadoc)
* @see java.io.InputStream#read()
*/
@Override
public int read() throws IOException {
return input.read();
}
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
*/
@Override
public String getParameter(final String name) {
String[] strings = getParameterMap().get(name);
if (strings != null) {
return strings[0];
}
return super.getParameter(name);
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletRequestWrapper#getParameterMap()
*/
@Override
public Map<String, String[]> getParameterMap() {
if (allParameters == null) {
allParameters = new TreeMap<String, String[]>();
allParameters.putAll(super.getParameterMap());
allParameters.putAll(modifiableParameters);
}
// Return an unmodifiable collection because we need to uphold the
// interface contract.
return Collections.unmodifiableMap(allParameters);
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletRequestWrapper#getParameterNames()
*/
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(getParameterMap().keySet());
}
/*
* (non-Javadoc)
* @see
* javax.servlet.ServletRequestWrapper#getParameterValues(java.lang.String)
*/
@Override
public String[] getParameterValues(final String name) {
return getParameterMap().get(name);
}
}
///**
// *
// */
//
//package org.gcube.datatransfer.resolver;
//
//import java.io.BufferedReader;
//import java.io.ByteArrayInputStream;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.util.Collections;
//import java.util.Enumeration;
//import java.util.Map;
//import java.util.TreeMap;
//
//import javax.servlet.ServletInputStream;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletRequestWrapper;
//
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.io.output.ByteArrayOutputStream;
//
//
///**
// * The Class MultiReadHttpServletRequest.
// *
// * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
// * Apr 26, 2016
// */
//public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
//
// private ByteArrayOutputStream cachedBytes;
// private final Map<String, String[]> modifiableParameters;
// private Map<String, String[]> allParameters = null;
//
// /**
// * Instantiates a new multi read http servlet request.
// *
// * @param request the request
// */
// public MultiReadHttpServletRequest(HttpServletRequest request) {
// super(request);
// modifiableParameters = new TreeMap<String, String[]>();
// }
//
// /**
// * Create a new request wrapper that will merge additional parameters into
// * the request object without prematurely reading parameters from the
// * original request.
// *
// * @param request
// * the request
// * @param additionalParams
// * the additional params
// */
// public MultiReadHttpServletRequest(
// final HttpServletRequest request,
// final Map<String, String[]> additionalParams) {
//
// super(request);
// modifiableParameters = new TreeMap<String, String[]>();
// modifiableParameters.putAll(additionalParams);
// }
//
// /* (non-Javadoc)
// * @see javax.servlet.ServletRequestWrapper#getInputStream()
// */
// @Override
// public ServletInputStream getInputStream() throws IOException {
//
// if (cachedBytes == null)
// cacheInputStream();
// return new CachedServletInputStream();
// }
//
// /* (non-Javadoc)
// * @see javax.servlet.ServletRequestWrapper#getReader()
// */
// @Override
// public BufferedReader getReader() throws IOException {
//
// return new BufferedReader(new InputStreamReader(getInputStream()));
// }
//
// /**
// * Cache input stream.
// *
// * @throws IOException Signals that an I/O exception has occurred.
// */
// private void cacheInputStream()
// throws IOException {
//
// /*
// * Cache the inputstream in order to read it multiple times. For
// * convenience, I use apache.commons IOUtils
// */
// cachedBytes = new ByteArrayOutputStream();
// IOUtils.copy(super.getInputStream(), cachedBytes);
// }
//
// /* An inputstream which reads the cached request body */
// /**
// * The Class CachedServletInputStream.
// *
// * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
// * Apr 26, 2016
// */
// public class CachedServletInputStream extends ServletInputStream {
//
// private ByteArrayInputStream input;
//
// /**
// * Instantiates a new cached servlet input stream.
// */
// public CachedServletInputStream() {
//
// /* create a new input stream from the cached request body */
// input = new ByteArrayInputStream(cachedBytes.toByteArray());
// }
//
// /* (non-Javadoc)
// * @see java.io.InputStream#read()
// */
// @Override
// public int read() throws IOException {
// return input.read();
// }
// }
//
// /*
// * (non-Javadoc)
// * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
// */
// @Override
// public String getParameter(final String name) {
//
// String[] strings = getParameterMap().get(name);
// if (strings != null) {
// return strings[0];
// }
// return super.getParameter(name);
// }
//
// /*
// * (non-Javadoc)
// * @see javax.servlet.ServletRequestWrapper#getParameterMap()
// */
// @Override
// public Map<String, String[]> getParameterMap() {
//
// if (allParameters == null) {
// allParameters = new TreeMap<String, String[]>();
// allParameters.putAll(super.getParameterMap());
// allParameters.putAll(modifiableParameters);
// }
// // Return an unmodifiable collection because we need to uphold the
// // interface contract.
// return Collections.unmodifiableMap(allParameters);
// }
//
// /*
// * (non-Javadoc)
// * @see javax.servlet.ServletRequestWrapper#getParameterNames()
// */
// @Override
// public Enumeration<String> getParameterNames() {
//
// return Collections.enumeration(getParameterMap().keySet());
// }
//
// /*
// * (non-Javadoc)
// * @see
// * javax.servlet.ServletRequestWrapper#getParameterValues(java.lang.String)
// */
// @Override
// public String[] getParameterValues(final String name) {
//
// return getParameterMap().get(name);
// }
//}

View File

@ -1,90 +0,0 @@
/**
*
*/
package org.gcube.datatransfer.resolver.catalogue;
import java.util.HashMap;
import java.util.Map;
/**
* The Class CatalogueEntityRequest.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Dec 2, 2016
*/
public class CatalogueEntityRequest {
private Map<String,String> parameters = new HashMap<String, String>();
/**
* Instantiates a new catalogue entity request.
*/
public CatalogueEntityRequest() {
}
/**
* Adds the parameter to request.
*
* @param key the key
* @param value the value
*/
public void addParameterToRequest(String key, String value) {
this.parameters.put(key, value);
}
/**
* Removes the parameter to request.
*
* @param key the key
*/
public void removeParameterToRequest(String key) {
this.parameters.remove(key);
}
/**
* Gets the parameters.
*
* @return the parameters
*/
public Map<String, String> getParameters() {
return parameters;
}
/**
* Gets the value of parameter.
*
* @param key the key
* @return the value of parameter
*/
public String getValueOfParameter(String key) {
return this.parameters.get(key);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CatalogueEntityRequest [parameters=");
builder.append(parameters);
builder.append("]");
return builder.toString();
}
}

View File

@ -1,79 +0,0 @@
/**
*
*/
package org.gcube.datatransfer.resolver.catalogue;
/**
* The Class CatalogueParameter.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Dec 2, 2016
*/
public class CatalogueParameter {
private String key;
private boolean mandatory;
/**
* Instantiates a new catalogue parameter.
*
* @param key the key
* @param mandatory the mandatory
*/
public CatalogueParameter(String key, boolean mandatory) {
this.key = key;
this.mandatory = mandatory;
}
/**
* @return the key
*/
public String getKey() {
return key;
}
/**
* @return the mandatory
*/
public boolean isMandatory() {
return mandatory;
}
/**
* @param key the key to set
*/
public void setKey(String key) {
this.key = key;
}
/**
* @param mandatory the mandatory to set
*/
public void setMandatory(boolean mandatory) {
this.mandatory = mandatory;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CatalogueParameter [key=");
builder.append(key);
builder.append(", mandatory=");
builder.append(mandatory);
builder.append("]");
return builder.toString();
}
}

View File

@ -1,17 +1,43 @@
package org.gcube.datatransfer.resolver.catalogue;
/**
* The Class CatalogueRequest.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Nov 6, 2018
*
* Binding Catalogue Request as a JSON
*/
public class CatalogueRequest {
private String gcube_scope;
private String entity_context;
private String entity_name;
/**
* Gets the gcube_scope.
*
* @return the gcube_scope
*/
public String getGcube_scope() {
return gcube_scope;
}
/**
* Gets the entity_context.
*
* @return the entity_context
*/
public String getEntity_context() {
return entity_context;
}
/**
* Gets the entity_name.
*
* @return the entity_name
*/
public String getEntity_name() {
return entity_name;
}

View File

@ -1,46 +0,0 @@
/**
*
*/
package org.gcube.datatransfer.resolver.catalogue;
/**
* The Interface CatalogueRequestParameter.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Dec 2, 2016
*/
public enum CatalogueRequestParameter {
GCUBE_SCOPE("gcube_scope",true),
ENTITY_CONTEXT("entity_context",true),
ENTITY_NAME("entity_name",true),
CLEAR_URL("clear_url",false),
QUERY_STRING("query_string",false);
private String key;
private boolean mandatory;
/**
*
*/
private CatalogueRequestParameter(String key, boolean isMandatory) {
this.key = key;
this.mandatory = isMandatory;
}
/**
* @return the key
*/
public String getKey() {
return key;
}
/**
* @return the mandatory
*/
public boolean isMandatory() {
return mandatory;
}
}

View File

@ -1,546 +0,0 @@
///**
// *
// */
//package org.gcube.datatransfer.resolver.catalogue;
//
//import java.io.IOException;
//import java.io.StringReader;
//import java.io.UnsupportedEncodingException;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//import org.apache.commons.codec.binary.Base64;
//import org.apache.commons.httpclient.HttpStatus;
//import org.apache.commons.io.IOUtils;
//import org.gcube.common.encryption.StringEncrypter;
//import org.gcube.common.scope.api.ScopeProvider;
//import org.gcube.datatransfer.resolver.ResourceCatalogueCodes;
//import org.gcube.datatransfer.resolver.UriResolverRewriteFilter;
//import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileNotFoundException;
//import org.gcube.datatransfer.resolver.catalogue.resource.ApplicationProfileReaderForCatalogueResolver;
//import org.gcube.datatransfer.resolver.catalogue.resource.CkanCatalogueConfigurationsReader;
//import org.gcube.datatransfer.resolver.catalogue.resource.GatewayCKANCatalogueReference;
//import org.gcube.datatransfer.resolver.catalogue.resource.UpdateApplicationProfileCatalogueResolver;
//import org.gcube.datatransfer.resolver.scope.ScopeUtil;
//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import eu.trentorise.opendata.jackan.model.CkanDataset;
//
//
///**
// * The Class GisResolver.
// *
// * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
// * Jan 7, 2016
// */
//public class CatalogueResolver extends HttpServlet{
//
// private static final long serialVersionUID = -8273405286016095823L;
//
// private static final String TEXT_PALIN_CHARSET_UTF_8 = "text/plain;charset=UTF-8";
// public static final String UTF_8 = "UTF-8";
//
// public static final String ENC_CATALOGUE_LINK_PARAM = UriResolverRewriteFilter.PARAMETER_ENC_CATALOGUE_LINK;
//
// public static final String DIRECT_CATALOGUE_LINK_PARAM = UriResolverRewriteFilter.PARAMETER_DIRECT_CATALOGUE_LINK;
//
// private static final String PATH_SEPARATOR = "/";
//
// public static final String PARAMETER_PATH = "path";
//
// public static final String ENV_SCOPE = "SCOPE"; //Environment Variable
//
// /** The logger. */
// private static final Logger logger = LoggerFactory.getLogger(CatalogueResolver.class);
//
// private ApplicationProfileReaderForCatalogueResolver appPrCatResolver;
//
//
// /** The scope to enc decr. */
// private String scopeToEncDecr = null;
//
//
// /* (non-Javadoc)
// * @see javax.servlet.GenericServlet#init()
// */
// @Override
// public void init() throws ServletException {
// initScopeFromEnv();
// }
//
//
// /**
// * Inits the scope from env.
// *
// * @return the string
// * @throws ServletException the servlet exception
// */
// private String initScopeFromEnv() throws ServletException{
//
// if(scopeToEncDecr!=null)
// return scopeToEncDecr;
//
// try{
// scopeToEncDecr = ScopeUtil.getScopeFromEnvironment();
// }catch(ServletException e){
// logger.error("I cannot encrypt/descrypt: ", e);
// throw new ServletException(CatalogueResolver.class.getName() +" cannot work without set the Environment Variable: "+ENV_SCOPE);
// }
//
// appPrCatResolver = new ApplicationProfileReaderForCatalogueResolver(scopeToEncDecr, true);
// logger.info("Resource read for CatalogueResolver: "+appPrCatResolver);
// return scopeToEncDecr;
// }
//
// /* (non-Javadoc)
// * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
// */
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
// String originalScope = ScopeProvider.instance.get();
// String clearCatalogueQueryLink = req.getParameter(DIRECT_CATALOGUE_LINK_PARAM);
// String encryptedCatalogueQueryLink = req.getParameter(ENC_CATALOGUE_LINK_PARAM);
// logger.debug("Read original scope from ScopeProvider: "+originalScope);
//
// boolean foundClearLink = false;
// if(clearCatalogueQueryLink==null || clearCatalogueQueryLink.isEmpty()){
// logger.info("Link is not a direct link to catalogue");
// }else
// foundClearLink = true;
//
// String queryStringToCat = "";
// if(foundClearLink){
// logger.info("Trying to resolve clear link to catalogue using query link: "+clearCatalogueQueryLink);
// queryStringToCat = clearCatalogueQueryLink;
// }else{
// logger.info("Trying to resolve encripted link to catalogue using query link: "+encryptedCatalogueQueryLink);
// if(encryptedCatalogueQueryLink==null || encryptedCatalogueQueryLink.isEmpty()){
// logger.error("Data Catalogue Link is malformed, set "+ENC_CATALOGUE_LINK_PARAM+" parameter");
// sendError(resp, HttpStatus.SC_BAD_REQUEST, "Data Catalogue Link is malformed, either you must set "+ENC_CATALOGUE_LINK_PARAM+" parameter or "+DIRECT_CATALOGUE_LINK_PARAM+ " parameter");
// return;
// }
// String base64DecodedId = "";
//
// try {
//
// base64DecodedId = base64DecodeString(encryptedCatalogueQueryLink);
// logger.info("Base 64 decoded Data Catalogue Link: "+base64DecodedId +", now decrypting...");
//
// if(scopeToEncDecr==null)
// initScopeFromEnv();
//
// ScopeProvider.instance.set(scopeToEncDecr);
// queryStringToCat = StringEncrypter.getEncrypter().decrypt(base64DecodedId);
// logger.info("Decrypted Data Catalogue Link: "+queryStringToCat);
//
// }catch (Exception e) {
// logger.error("An error occurred during decrypting data catalogue link: "+base64DecodedId+", using the scope: "+scopeToEncDecr, e);
// sendError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR, "The system cannot decrypt the Catalogue Link");
// return;
// }finally{
//
// if(originalScope!=null){
// ScopeProvider.instance.set(originalScope);
// logger.info("scope provider set to orginal scope: "+originalScope);
// }else{
// ScopeProvider.instance.reset();
// logger.info("scope provider reset");
// }
//
// }
// }
//
// CatalogueEntityRequest cer = new CatalogueEntityRequest();
// for (CatalogueRequestParameter parameter : CatalogueRequestParameter.values()) {
// String value = getValueOfParameter(parameter.getKey(), queryStringToCat);
// cer.addParameterToRequest(parameter.getKey(), value);
// }
//
// if(cer.getValueOfParameter(CatalogueRequestParameter.ENTITY_CONTEXT.getKey()).compareToIgnoreCase("product")==0){
// logger.debug("Read "+CatalogueRequestParameter.ENTITY_CONTEXT.getKey() + " value: 'product' replacing with 'dataset'");
// cer.addParameterToRequest(CatalogueRequestParameter.ENTITY_CONTEXT.getKey(), "dataset");
// }
//
// logger.debug("Read parameters: "+cer.toString());
//
// String scope = cer.getValueOfParameter(CatalogueRequestParameter.GCUBE_SCOPE.getKey());
// if(scope==null || scope.isEmpty()){
// logger.error("An error occurred during resolving data catalogue link: the scope to search CKan Portlet is null or empty");
// sendError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR, "The system cannot resolve the Catalogue Link, the scope is null or empty");
// return;
// }
//
// /**
// * I'm replacing VRE_NAME passed into parameter GCUBE_SCOPE with the scope read from ApplicationProfileReaderForCatalogueResolver#RESOURCE_NAME
// * that is the full scope
// */
// if(foundClearLink){
// if(appPrCatResolver==null)
// appPrCatResolver = new ApplicationProfileReaderForCatalogueResolver(scopeToEncDecr, true);
//
// String fullScope = appPrCatResolver.getHashVreNameScope().get(scope);
//
// if(fullScope==null){
// logger.debug("FullScope is null for VRE_NAME: "+scope+" into Application Profile: "+ApplicationProfileReaderForCatalogueResolver.RESOURCE_NAME+", reading profile again");
// appPrCatResolver = new ApplicationProfileReaderForCatalogueResolver(scopeToEncDecr, true);
// fullScope = appPrCatResolver.getHashVreNameScope().get(scope);
// }
//
// logger.debug("Read fullScope: "+fullScope + " for VRE_NAME: "+scope +" into Application Profile "+ApplicationProfileReaderForCatalogueResolver.RESOURCE_NAME);
// cer.addParameterToRequest(CatalogueRequestParameter.GCUBE_SCOPE.getKey(), fullScope);
// scope = fullScope;
// }
//
// String ckanPorltetUrl = "";
// try{
// logger.info("Setting scope "+scope+ " to search Ckan Portlet URL from IS");
// ScopeProvider.instance.set(scope);
// GatewayCKANCatalogueReference ckanCatalogueReference = CkanCatalogueConfigurationsReader.loadCatalogueEndPoints();
//
// //IS THE PRODUCT PLUBLIC OR PRIVATE?
// //USING ACCESS TO PUBLIC PORTLET IF THE ITEM IS PUBLIC, OTHERWISE ACCESS TO PRIVATE PORTLET
// ckanPorltetUrl = ckanCatalogueReference.getPrivatePortletURL();
// String datasetName = cer.getValueOfParameter(CatalogueRequestParameter.ENTITY_NAME.getKey());
// if(ckanCatalogueReference.getCkanURL()!=null){
// try{
// CkanDataset dataset = CkanCatalogueConfigurationsReader.getDataset(datasetName, ckanCatalogueReference.getCkanURL());
// if(dataset!=null){
// ckanPorltetUrl = ckanCatalogueReference.getPublicPortletURL();
// logger.info("The dataset "+datasetName+" is a public item using public access to CKAN portlet: "+ckanPorltetUrl);
// }
// }catch(Exception e){
// logger.warn("Error on checking if dataset: "+datasetName+" is private or not", e);
// ckanPorltetUrl = ckanCatalogueReference.getPublicPortletURL();
// }
// }
//
//
// if(ckanPorltetUrl == null || ckanPorltetUrl.isEmpty()){
// sendError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR, "An error occurred during discovery the resource: "+CkanCatalogueConfigurationsReader.APPLICATION_PROFILE_NAME+" in the scope: "+scope+", try again later");
// return;
// }
//
//
// }catch(Exception e){
// logger.error("Error during discovery the resource: "+CkanCatalogueConfigurationsReader.APPLICATION_PROFILE_NAME+" in the scope: "+scope, e);
// sendError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR, "An error occurred during discovery the resource: "+CkanCatalogueConfigurationsReader.APPLICATION_PROFILE_NAME+" in the scope: "+scope+", try again later");
// return;
//
// }finally{
//
// if(originalScope!=null){
// ScopeProvider.instance.set(originalScope);
// logger.info("scope provider set to orginal scope: "+originalScope);
// }else{
// ScopeProvider.instance.reset();
// logger.info("scope provider reset");
// }
//
// }
//
// //UrlEncoderUtil.encodeQuery(cer.getParameters());
// String buildPath = PARAMETER_PATH +"=";
// buildPath+= PATH_SEPARATOR+cer.getValueOfParameter(CatalogueRequestParameter.ENTITY_CONTEXT.getKey()) + PATH_SEPARATOR;
// buildPath+=cer.getValueOfParameter(CatalogueRequestParameter.ENTITY_NAME.getKey());
//
//
// String finalUrl = ckanPorltetUrl+"?"+buildPath;
// logger.info("Builded final URL: "+finalUrl);
// resp.sendRedirect(resp.encodeRedirectURL(finalUrl));
// }
//
//
// /* (non-Javadoc)
// * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
// */
// @Override
// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
// String originalScope = ScopeProvider.instance.get();
// final CatalogueEntityRequest cer = new CatalogueEntityRequest();
// try{
// String jsonRequest = IOUtils.toString(req.getInputStream());
// logger.debug("Read json request: "+jsonRequest);
// JSONObject inputJson = new JSONObject(jsonRequest);
//
// for (CatalogueRequestParameter parameter : CatalogueRequestParameter.values()) {
//
// try{
//
// switch (parameter) {
// case QUERY_STRING:
// //TODO must be implemented
// JSONArray queryString = inputJson.getJSONArray(parameter.getKey());
// break;
// default:
// String value = inputJson.getString(parameter.getKey());
// logger.debug("Read value: "+value+", for parameter: "+parameter.getKey());
// cer.addParameterToRequest(parameter.getKey(), value);
// break;
// }
//
// }catch(Exception e){
// String error = "";
// try {
//
// if(parameter.isMandatory()){
// error = parameter.getKey() +" not found";
// sendError(resp, HttpStatus.SC_BAD_REQUEST, error);
// return;
// }
// else
// logger.debug("Not Mandatory parameter: "+parameter.getKey()+", not found, continuing...");
//
// }catch (IOException e1) {
// //silent
// }
// }
//
// }
// }catch(JSONException e){
// try {
// logger.error("Json passed is malformed: ", e);
// sendError(resp, HttpStatus.SC_BAD_REQUEST, "Json passed is malformed");
// }
// catch (IOException e1) {
// //silent
// }
// return;
// }
//
// try{
// //CHECK IF INPUT SCOPE IS VALID
// String scope = cer.getValueOfParameter(CatalogueRequestParameter.GCUBE_SCOPE.getKey());
// if(!scope.startsWith("/")){
// logger.info("Scope not start with char '/' adding it");
// scope+="/"+scope;
// cer.addParameterToRequest(CatalogueRequestParameter.GCUBE_SCOPE.getKey(), scope);
// }
//
// String buildLink = getServerURL(req);
// //buildLink += req.getRequestURI(); //AVOIDNG TO ADD THE SERVLET NAME: 'catalogue', THERE IS THE URL REWRITE USED FOR 'uri-resolver'
//
// String clearURL = cer.getValueOfParameter(CatalogueRequestParameter.CLEAR_URL.getKey());
//
// boolean bClearURL = false;
// try{
// bClearURL = Boolean.parseBoolean(clearURL);
// }catch(Exception e){
// //silent
// }
//
// resp.setContentType(TEXT_PALIN_CHARSET_UTF_8);
// resp.setCharacterEncoding(UTF_8);
//
// logger.info("Clear URL is: "+bClearURL);
// if(bClearURL){
//
// final String vreName = scope.substring(scope.lastIndexOf("/")+1, scope.length());
// //buildLink+=PATH_SEPARATOR+vreName+PATH_SEPARATOR+cer.getValueOfParameter(CatalogueRequestParameter.ENTITY_CONTEXT.getKey())+PATH_SEPARATOR+cer.getValueOfParameter(CatalogueRequestParameter.ENTITY_NAME.getKey());
// String econtext = cer.getValueOfParameter(CatalogueRequestParameter.ENTITY_CONTEXT.getKey());
// ResourceCatalogueCodes rc = ResourceCatalogueCodes.valueOfCodeValue(econtext);
// if(rc==null){
// logger.error("Entity context is null/malformed");
// sendError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error during generating Data Catalogue Link, the entity context passed is not recognized. Is it malformed?");
// return;
// }
// buildLink += PATH_SEPARATOR+rc.getId()+PATH_SEPARATOR+vreName+PATH_SEPARATOR+cer.getValueOfParameter(CatalogueRequestParameter.ENTITY_NAME.getKey());
// logger.info("Writing Decoded Catalogue Link: "+buildLink);
//
// //IT'S GOING TO UPDATE THE GENERIC RESOURCE IF IS NEEDED
// new Thread(){
// public void run() {
// try {
// String fullScope = cer.getValueOfParameter(CatalogueRequestParameter.GCUBE_SCOPE.getKey());
// boolean endPointUpdated = UpdateApplicationProfileCatalogueResolver.validateEndPoint(scopeToEncDecr, vreName, fullScope);
//
// if(endPointUpdated)
// appPrCatResolver = new ApplicationProfileReaderForCatalogueResolver(scopeToEncDecr, true);
//
// }
// catch (ApplicationProfileNotFoundException e) {
// logger.error("Error during validating Application Profile", e);
// }
// };
// }.start();
//
// }else{
// //ADDING THE SERVLET NAME
// buildLink += req.getRequestURI();
//
// cer.removeParameterToRequest(CatalogueRequestParameter.CLEAR_URL.getKey());
// logger.info("Using scope "+scopeToEncDecr+ " from env to get encrypt key");
// ScopeProvider.instance.set(scopeToEncDecr);
// //String query = UrlEncoderUtil.encodeQuery(cer.getParameters());
// String query = "";
// for (String key : cer.getParameters().keySet()) {
// query+=key+"="+ cer.getParameters().get(key) +"&";
// }
// query = UrlEncoderUtil.removeLastChar(query);
// logger.info("Builded query string: "+query);
// String encriptedQuery = StringEncrypter.getEncrypter().encrypt(query);
// logger.info("Encrypted query: "+encriptedQuery);
// String encodedQuery = base64EncodeStringURLSafe(encriptedQuery);
// logger.info("Catalogue Query Link: "+encodedQuery);
// buildLink+=PATH_SEPARATOR+encodedQuery;
// logger.info("Writing Encoded Catalogue Link: "+buildLink);
// }
//
// resp.getWriter().write(buildLink);
//
// }catch(Exception e){
// try {
// logger.error("An internal error is occurred: ", e);
// sendError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR, "An error occurred during generating Data Catalogue Link, try again later");
// return;
// }
// catch (IOException e1) {
// //silent
// }
// }finally{
//
// if(originalScope!=null){
// ScopeProvider.instance.set(originalScope);
// logger.info("scope provider set to orginal scope: "+originalScope);
// }else{
// ScopeProvider.instance.reset();
// logger.info("scope provider reset");
// }
// }
//
// }
//
// /**
// * Send error.
// *
// * @param response the response
// * @param status the status
// * @param message the message
// * @throws IOException Signals that an I/O exception has occurred.
// */
// protected static void sendError(HttpServletResponse response, int status, String message) throws IOException{
//
// logger.error("error message: "+message);
// logger.info("writing response...");
//
// if(response==null)
// return;
//
// response.setStatus(status);
// StringReader sr = new StringReader(message);
// IOUtils.copy(sr, response.getOutputStream());
// logger.info("response writed");
// response.flushBuffer();
// }
//
//
// /**
// * Gets the server url.
// *
// * @param req the req
// * @return the server url
// */
// public String getServerURL(HttpServletRequest req) {
//
// String scheme = req.getScheme(); // http
// String serverName = req.getServerName(); // hostname.com
// int serverPort = req.getServerPort(); // 80
// //String contextPath = req.getContextPath(); // /mywebapp
//
// // Reconstruct original requesting URL
// StringBuffer url = new StringBuffer();
// url.append(scheme).append("://").append(serverName);
//
// if (serverPort != 80 && serverPort != 443)
// url.append(":").append(serverPort);
//
//// if(contextPath!=null)
//// url.append(":").append(contextPath);
//
// String uToS = url.toString();
// logger.debug("returning servlet context URL: "+uToS);
// return uToS;
// }
//
//
// /**
// * Gets the value of parameter in the passed query string, null otherwise
// *
// * @param parameter the parameter
// * @param httpQueryString the http query string
// * @return the value of parameter if exists, null otherwise
// */
// public static String getValueOfParameter(String parameter, String httpQueryString) {
//// logger.trace("finding: "+wmsParam +" into "+url);
// int index = httpQueryString.toLowerCase().indexOf(parameter.toLowerCase()+"="); //ADDING CHAR "=" IN TAIL TO BE SECURE IT IS A PARAMETER
//// logger.trace("start index of "+wmsParam+ " is: "+index);
// String value = "";
// if(index > -1){
//
// int start = index + parameter.length()+1; //add +1 for char '='
// String sub = httpQueryString.substring(start, httpQueryString.length());
// int indexOfSeparator = sub.indexOf("&");
// int end = indexOfSeparator!=-1?indexOfSeparator:sub.length();
// value = sub.substring(0, end);
// }else
// return null;
//
//// logger.trace("return value: "+value);
// return value;
// }
//
// /**
// * Base64 encode string url safe.
// *
// * @param s the s
// * @return the string
// */
// public static String base64EncodeStringURLSafe(String s) {
//
// try {
// return Base64.encodeBase64URLSafeString(s.getBytes(UTF_8));
// }
// catch (UnsupportedEncodingException e) {
// logger.error("Failed to decode the String", e);
// logger.error("Returning input string: " + s);
// return s;
// }
// }
//
// /**
// * Base64 decode string.
// *
// * @param s the s
// * @return the string
// */
// public static String base64DecodeString(String s) {
//
// try {
// return new String(Base64.decodeBase64(s.getBytes(UTF_8)));
// }
// catch (UnsupportedEncodingException e) {
// logger.error("Failed to decode the String", e);
// logger.error("Returning input string: " + s);
// return s;
// }
// }
//
// public static void main(String[] args) {
//
// try{
// String scope = "/d4science.research-infrastructures.eu";
// ApplicationProfileReaderForCatalogueResolver appPrCatResolver = new ApplicationProfileReaderForCatalogueResolver(scope, true);
// logger.info("Reosurce for Catalogue Resolver: "+appPrCatResolver);
// }catch(Exception e){
// e.printStackTrace();
// }
// }
//}

View File

@ -82,7 +82,6 @@ public class CatalogueServiceEndpointReader {
return toReturn;
}

View File

@ -1,84 +0,0 @@
///**
// *
// */
//
//package org.gcube.datatransfer.resolver.catalogue.resource;
//
//import static org.gcube.resources.discovery.icclient.ICFactory.client;
//
//import java.io.StringReader;
//import java.util.List;
//
//import javax.xml.parsers.DocumentBuilder;
//import javax.xml.parsers.DocumentBuilderFactory;
//
//import org.gcube.common.resources.gcore.utils.XPathHelper;
//import org.gcube.common.scope.api.ScopeProvider;
//import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileNotFoundException;
//import org.gcube.resources.discovery.client.api.DiscoveryClient;
//import org.gcube.resources.discovery.client.queries.api.Query;
//import org.gcube.resources.discovery.client.queries.impl.QueryBox;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.w3c.dom.Node;
//import org.xml.sax.InputSource;
//
//
///**
// * The Class CkanPorltetApplicationProfile.
// *
// * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
// * May 16, 2017
// */
//public class CkanPorltetApplicationProfile {
//
// private static final Logger logger = LoggerFactory.getLogger(CkanPorltetApplicationProfile.class);
// private final static String APPLICATION_PROFILE_NAME = "CkanPortlet";
//
// /**
// * Gets the portlet url from infrastrucure.
// *
// * @return the portlet url from infrastrucure
// * @throws Exception the exception
// */
// public static String getPortletUrlFromInfrastrucure() throws Exception {
//
// String scope = ScopeProvider.instance.get();
// logger.debug("Trying to fetch applicationProfile profile from the infrastructure for " +
// APPLICATION_PROFILE_NAME + " scope: " + scope);
// try {
// Query q =
// new QueryBox(
// "for $profile in collection('/db/Profiles/GenericResource')//Resource " +
// "where $profile/Profile/SecondaryType/string() eq 'ApplicationProfile' and $profile/Profile/Name/string() " +
// " eq '" +
// APPLICATION_PROFILE_NAME +
// "'" +
// "return $profile");
// DiscoveryClient<String> client = client();
// List<String> appProfile = client.submit(q);
// if (appProfile == null || appProfile.size() == 0)
// throw new ApplicationProfileNotFoundException(
// "Your applicationProfile is not registered in the infrastructure");
// else {
// String elem = appProfile.get(0);
// DocumentBuilder docBuilder =
// DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
// XPathHelper helper = new XPathHelper(node);
// List<String> currValue = null;
// currValue =
// helper.evaluate("/Resource/Profile/Body/url/text()");
// if (currValue != null && currValue.size() > 0) {
// logger.debug("CKAN Portlet url found is " + currValue.get(0));
// return currValue.get(0);
// }
// }
// }
// catch (Exception e) {
// throw new Exception("Error while trying to fetch applicationProfile profile for name "+APPLICATION_PROFILE_NAME+"from the infrastructure, using scope: "+scope);
// }
//
// return null;
// }
//}

View File

@ -1,524 +0,0 @@
///**
// *
// */
//package org.gcube.datatransfer.resolver.gis;
//
//import java.io.IOException;
//import java.io.StringReader;
//import java.net.URLEncoder;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Random;
//import java.util.Timer;
//import java.util.TimerTask;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//import org.apache.commons.io.IOUtils;
//import org.gcube.common.scope.api.ScopeProvider;
//import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileReader;
//import org.gcube.datatransfer.resolver.gis.GeonetworkAccessParameter.GeonetworkLoginLevel;
//import org.gcube.datatransfer.resolver.gis.entity.GisLayerItem;
//import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException;
//import org.gcube.datatransfer.resolver.gis.exception.IllegalArgumentException;
//import org.gcube.datatransfer.resolver.gis.property.ApplicationProfileGenericResourceReader;
//import org.gcube.datatransfer.resolver.gis.property.PropertyFileNotFoundException;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//
///**
// * The Class GisResolver.
// *
// * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
// * Jan 7, 2016
// */
//public class GisResolver extends HttpServlet{
//
// private static final String UTF_8 = "UTF-8";
// private static final String TEXT_PLAIN = "text/plain";
// public static final String PARAM_SEPARATOR_REPLACEMENT_VALUE = "%%";
// public static final String PARAM_SEPARATOR_REPLACEMENT_KEY = "separtor";
// private static final long serialVersionUID = 5605107730993617579L;
//
// public static final String GIS_UUID = "gis-UUID";
// public static final String SCOPE = "scope";
// public static final String GEO_EXPLORER_LAYER_UUID = "geo-exp";
//
// protected static final String GIS_VIEWER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "gisviewerappgenericresource.properties";
// protected static final String GEO_EXPLORER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "geoexplorerappgenericresource.properties";
//
//
// /** The logger. */
// private static final Logger logger = LoggerFactory.getLogger(GisResolver.class);
//
// protected Map<String, GeonetworkInstance> cachedGeonetworkInstances; //A cache: scope - geonetwork instances
// protected Map<String, String> cachedGisViewerApplHostname; //A cache: scope - GisViewerApp hostname
// protected Map<String, String> cachedGeoExplorerApplHostname; //A cache: scope - GisViewerApp hostname
//
// private Timer timer;
// private ApplicationProfileGenericResourceReader gisViewerAppPropertyReader;
// private ApplicationProfileGenericResourceReader geoEplorerAppPropertyReader;
//
// //THIRTY MINUTES
// public static final long CACHE_RESET_TIME = 30*60*1000;
//
// //TEN MINUTES
// public static final long CACHE_RESET_DELAY = 10*60*1000;
//
// /* (non-Javadoc)
// * @see javax.servlet.GenericServlet#init()
// */
// @Override
// public void init() throws ServletException {
// super.init();
// timer = new Timer(true);
// timer.schedule(new TimerTask() {
// @Override
// public void run() {
// logger.info("Resetting cache...");
// reseCacheServerParameters();
// resetGisViewerAppEndPoint();
// reseCacheGisViewerApplicationHostname();
// reseCacheGeoExplorerApplicationHostname();
// }
// }, CACHE_RESET_DELAY, CACHE_RESET_TIME);
// }
//
//
//
// /**
// * Gets the cached geonetwork instance.
// *
// * @param scope the scope
// * @return the cached geonetwork instance
// * @throws Exception the exception
// */
// protected GeonetworkInstance getCachedGeonetworkInstance(String scope) throws Exception{
//
// if(cachedGeonetworkInstances==null)
// reseCacheServerParameters();
//
// logger.info("Attempt to get the GeonetworkInstance from cache by scope: "+scope);
// GeonetworkInstance geonInstance = cachedGeonetworkInstances.get(scope);
//
// if(geonInstance==null){
// logger.info("GeonetworkInstance is null in cache, reading from library...");
// try {
// geonInstance = discoveryGeonetworkInstance(scope);
// cachedGeonetworkInstances.put(scope, geonInstance);
// logger.info("Updated GeonetworkInstance cache! Scope "+scope+" linking "+geonInstance);
// } catch (Exception e) {
// logger.error("An error occurred on getting GeonetworkInstance for scope: "+scope, e);
// throw new Exception("Sorry, An error occurred on getting GeonetworkInstance for scope: "+scope);
// }
// }else
// logger.info("GeonetworkInstance is not null using it");
//
// logger.info("returning GeonetworkInstance: "+geonInstance);
//
// return geonInstance;
// }
//
//
// /**
// * Discovery geonetwork instance.
// *
// * @param scope the scope
// * @return the geonetwork instance
// * @throws GeonetworkInstanceException the geonetwork instance exception
// */
// private GeonetworkInstance discoveryGeonetworkInstance(String scope) throws GeonetworkInstanceException{
//
// GeonetworkAccessParameter gntwAccess = new GeonetworkAccessParameter(scope);
//
// if(cachedGeonetworkInstances==null)
// reseCacheServerParameters();
//
// return gntwAccess.getGeonetworkInstance(true, GeonetworkLoginLevel.ADMIN);
// }
//
//
// /**
// * Rese cache server parameters.
// */
// private void reseCacheServerParameters(){
// cachedGeonetworkInstances = new HashMap<String, GeonetworkInstance>();
// logger.info("Cache of GeonetworkInstances reset!");
// }
//
// /**
// * Rese cache gis viewer application hostname.
// */
// private void reseCacheGisViewerApplicationHostname(){
// cachedGisViewerApplHostname = new HashMap<String, String>();
// logger.info("Cache of Gis Viewer Hostname reset!");
// }
//
// /**
// * Rese cache geo explorer application hostname.
// */
// private void reseCacheGeoExplorerApplicationHostname() {
// cachedGeoExplorerApplHostname = new HashMap<String, String>();
// logger.info("Cache of Geo Explorer Hostname reset!");
// }
//
//// /**
//// * Reset gis viewer app end point.
//// */
//// private void resetGisViewerAppEndPoint(){
//// try {
//// gisViewerAppPropertyReader = new ApplicationProfileGenericResourceReader(GIS_VIEWER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES);
//// logger.info("GisViewerApp end point updated!");
//// } catch (PropertyFileNotFoundException e) {
//// logger.error("Error on reset GisViewerAppEndPoint ",e);
//// }
//// }
////
////
//// /**
//// * Reset geo explorer app end point.
//// */
//// private void resetGeoExplorerAppEndPoint(){
//// try {
//// geoEplorerAppPropertyReader = new ApplicationProfileGenericResourceReader(GEO_EXPLORER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES);
//// logger.info("GeoExplorer end point updated!");
//// } catch (PropertyFileNotFoundException e) {
//// logger.error("Error on reset GeoExplorerEndPoint ",e);
//// }
//// }
//
// /**
// * Gets the gis viewer application url.
// *
// * @param scope the scope
// * @return the gis viewer application url
// * @throws Exception the exception
// */
// protected String getGisViewerApplicationURL(String scope) throws Exception{
//
// if(cachedGisViewerApplHostname==null)
// reseCacheGisViewerApplicationHostname();
//
// logger.info("Tentative of recovering gis viewer application hostname from cache for scope: "+scope);
// String gisViewerAppHostname = cachedGisViewerApplHostname.get(scope);
// if(gisViewerAppHostname==null){
// logger.info("Gis viewer application hostname is null, reading from application profile..");
// if(gisViewerAppPropertyReader==null)
// resetGisViewerAppEndPoint();
//
// ApplicationProfileReader reader = new ApplicationProfileReader(scope, gisViewerAppPropertyReader.getGenericResource(), gisViewerAppPropertyReader.getAppId(), false);
// String url = reader.getApplicationProfile().getUrl();
// cachedGisViewerApplHostname.put(scope, url);
// logger.info("Updated GisViewerApplication cache! Scope "+scope+" linking "+url);
// return url;
// }else
// logger.info("Cache for GisViewerApplication end point is not null using it");
//
// return gisViewerAppHostname;
// }
//
//
// /**
// * Gets the geo explorer application url.
// *
// * @param scope the scope
// * @return the geo explorer application url
// * @throws Exception the exception
// */
// protected String getGeoExplorerApplicationURL(String scope) throws Exception{
//
// if(cachedGeoExplorerApplHostname==null)
// reseCacheGeoExplorerApplicationHostname();
//
// logger.info("Tentative of recovering geo explorer application hostname from cache for scope: "+scope);
// String geoExplorerApplicationHostname = cachedGeoExplorerApplHostname.get(scope);
// if(geoExplorerApplicationHostname==null){
// logger.info("GeoExplorer application hostname is null, reading from application profile..");
// if(geoEplorerAppPropertyReader==null)
// resetGeoExplorerAppEndPoint();
//
// ApplicationProfileReader reader = new ApplicationProfileReader(scope, geoEplorerAppPropertyReader.getGenericResource(), geoEplorerAppPropertyReader.getAppId(), true);
// String url = reader.getApplicationProfile().getUrl();
// cachedGeoExplorerApplHostname.put(scope, url);
// logger.info("Updated GeoExplorerApplication cache! Scope "+scope+" linking "+url);
// return url;
// }else
// logger.info("Cache for GeoExplorerApplication end point is not null using it");
//
// return geoExplorerApplicationHostname;
//
//
// }
//
// /* (non-Javadoc)
// * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
// */
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
// String originalScope = ScopeProvider.instance.get();
//
// logger.info("The http session id is: " + req.getSession().getId());
// String scope = req.getParameter(SCOPE);
//
// if (scope == null || scope.isEmpty()) {
// logger.error(SCOPE+" not found");
// sendError(resp, HttpServletResponse.SC_BAD_REQUEST, SCOPE+" not found or empty");
// return;
// }
// logger.info("SCOPE is: " + scope);
//
// boolean isGisLink = false;
// boolean isGeoExplorerLink = false;
// String gisUUID = req.getParameter(GIS_UUID);
//
// if (gisUUID == null || gisUUID.isEmpty()) {
// logger.debug(GIS_UUID+" not found");
// }else
// isGisLink = true;
//
// logger.info(GIS_UUID +" is: " + gisUUID);
//
// String geoExplorerUUID = req.getParameter(GEO_EXPLORER_LAYER_UUID);
//
// if (geoExplorerUUID == null || geoExplorerUUID.isEmpty()) {
// logger.debug(GEO_EXPLORER_LAYER_UUID+ " not found");
// }else
// isGeoExplorerLink = true;
//
// logger.info(GEO_EXPLORER_LAYER_UUID +" is: " + geoExplorerUUID);
//
// if(!isGisLink && !isGeoExplorerLink){
// String err = GIS_UUID+" and "+GEO_EXPLORER_LAYER_UUID+" not found or empty";
// logger.error(err);
// sendError(resp, HttpServletResponse.SC_BAD_REQUEST, err);
// return;
// }
//
// try {
//
// if(isGisLink){
// //ScopeProvider.instance.set(scope);
// //ServerParameters geonetworkParams = getCachedServerParameters(scope);
//
// GisLayerItem gisLayerItem = getGisLayerForLayerUUID(scope, gisUUID);
// logger.info("wms url is: " + gisLayerItem.getFullWmsUrlRequest());
// String wmsRequest = URLEncoder.encode(gisLayerItem.getFullWmsUrlRequest(), UTF_8);
// logger.info("encoded WMS url is: " + wmsRequest);
//
// String layerTitle = null;
// if(gisLayerItem.getCitationTitle()!=null && !gisLayerItem.getCitationTitle().isEmpty())
// layerTitle = URLEncoder.encode(gisLayerItem.getCitationTitle(), UTF_8);
//
// logger.info("layer Title encoded is: " + layerTitle);
//
// String gisViewerPortletUrl = getGisViewerApplicationURL(scope);
// logger.info("Gis Viewer Application url is: " + gisViewerPortletUrl);
// gisViewerPortletUrl+="?rid="+new Random().nextLong()
// +"&wmsrequest="+wmsRequest
// +"&uuid="+URLEncoder.encode(gisUUID, UTF_8);
//
// if(layerTitle!=null)
// gisViewerPortletUrl+="&layertitle="+layerTitle;
//
// /*resp.setContentType(TEXT_PLAIN);
// resp.setCharacterEncoding(UTF_8);
// PrintWriter out = resp.getWriter();
// out.println(gisPortletUrl);
// logger.info("returning link: " + gisPortletUrl);
// out.close();*/
// logger.info("Redirecting to: "+gisViewerPortletUrl);
// urlRedirect(req, resp, gisViewerPortletUrl);
// }
//
// if(isGeoExplorerLink){
// ScopeProvider.instance.set(scope);
// String geoExplorerPortletUrl = getGeoExplorerApplicationURL(scope);
// logger.info("GeoExplorer Application url is: " + geoExplorerPortletUrl);
// geoExplorerPortletUrl+="?rid="+new Random().nextLong()
// +"&luuid="+URLEncoder.encode(geoExplorerUUID, UTF_8);
// urlRedirect(req, resp, geoExplorerPortletUrl);
// }
//
// } catch (IllegalArgumentException e){
// logger.error("IllegalArgumentException:", e);
// sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Illegal argument to carry out the request!");
// return;
//
// } catch (Exception e) {
// logger.error("Exception:", e);
// String error = "Sorry, an error occurred on resolving request with UUID "+gisUUID+" and scope "+scope+". Please, contact support!";
// sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
// return;
// }finally{
// if(originalScope!=null){
// ScopeProvider.instance.set(originalScope);
// logger.info("scope provider set to orginal scope: "+originalScope);
// }else{
// ScopeProvider.instance.reset();
// logger.info("scope provider reset");
// }
// }
//
// }
//
// /**
// * Encode url with param delimiter.
// *
// * @param wmsRequest the wms request
// * @return the string
// */
// private String encodeURLWithParamDelimiter(String wmsRequest){
// return wmsRequest.replaceAll("&", PARAM_SEPARATOR_REPLACEMENT_VALUE);
// }
//
// /**
// * Decode url with param delimiter.
// *
// * @param wmsRequest the wms request
// * @return the string
// */
// private String decodeURLWithParamDelimiter(String wmsRequest){
// return wmsRequest.replaceAll(PARAM_SEPARATOR_REPLACEMENT_VALUE, "&");
// }
//
// /**
// * Append param replacement.
// *
// * @param wmsRequest the wms request
// * @return the string
// */
// private String appendParamReplacement(String wmsRequest){
// return wmsRequest+"&"+PARAM_SEPARATOR_REPLACEMENT_KEY+"="+PARAM_SEPARATOR_REPLACEMENT_VALUE;
// }
//
//
// /**
// * Gets the gis layer for layer uuid.
// *
// * @param scope the scope
// * @param gisUUID the gis uuid
// * @return the gis layer for layer uuid
// * @throws Exception the exception
// */
// protected GisLayerItem getGisLayerForLayerUUID(String scope, String gisUUID) throws Exception{
//
// try {
// GeonetworkInstance gi = getCachedGeonetworkInstance(scope);
// GisLayerItem gisLayerItem = MetadataConverter.getWMSOnLineResource(gi, gisUUID);
// return gisLayerItem;
// //TODO CREATE A BEAN ADDING WMS REQUEST AND LAYER TITLE MetadataConverter.
// }catch (GeonetworkInstanceException e){
// logger.error("An error occurred when instancing geonetowrk gis layer with UUID "+gisUUID, e);
// throw new IllegalArgumentException("Sorry, An error occurred when instancing geonetwork with UUID: "+gisUUID);
// } catch (Exception e) {
// logger.error("An error occurred when retrieving gis layer with UUID "+gisUUID, e);
// throw new IllegalArgumentException("Sorry, An error occurred when retrieving gis layer with UUID "+gisUUID);
// }
// }
//
//
// /* (non-Javadoc)
// * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
// */
// @Override
// protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
// this.doGet(req, resp);
// }
//
//
// /**
// * Send error.
// *
// * @param response the response
// * @param status the status
// * @param message the message
// * @throws IOException Signals that an I/O exception has occurred.
// */
// protected void sendError(HttpServletResponse response, int status, String message) throws IOException{
// response.setStatus(status);
// logger.info("error message: "+message);
// logger.info("writing response...");
// StringReader sr = new StringReader(message);
// IOUtils.copy(sr, response.getOutputStream());
// logger.info("response writed");
// response.flushBuffer();
// }
//
// /**
// * Url redirect.
// *
// * @param req the req
// * @param response the response
// * @param redirectTo the redirect to
// * @throws IOException Signals that an I/O exception has occurred.
// */
// protected void urlRedirect(HttpServletRequest req, HttpServletResponse response, String redirectTo) throws IOException {
// response.sendRedirect(response.encodeRedirectURL(redirectTo));
// }
//
//
// /**
// * Gets the request url.
// *
// * @param req the req
// * @return the request url
// */
// public static String getRequestURL(HttpServletRequest req) {
//
// String scheme = req.getScheme(); // http
// String serverName = req.getServerName(); // hostname.com
// int serverPort = req.getServerPort(); // 80
// String contextPath = req.getContextPath(); // /mywebapp
// StringBuffer url = new StringBuffer();
// url.append(scheme).append("://").append(serverName);
//
// if (serverPort != 80 && serverPort != 443) {
// url.append(":").append(serverPort);
// }
//
// logger.trace("server: "+url);
// logger.trace("omitted contextPath: "+contextPath);
// return url.toString();
// }
//
//// /**
//// * The main method.
//// *
//// * @param args the arguments
//// */
//// public static void main(String[] args) {
//// GisResolver gisResolver = new GisResolver();
//// String scope = "/gcube/devsec/devVRE";
//// String UUID = "177e1c3c-4a22-4ad9-b015-bfc443d16cb8";
//// try {
////// ScopeProvider.instance.set(scope);
////// ServerParameters geonetworkParams = gisResolver.getCachedServerParameters(scope);
////// String wmsRequest = gisResolver.getLayerWmsRequest(scope, UUID, geonetworkParams);
////// logger.info("Final url is: " + wmsRequest);
////// wmsRequest = URLEncoder.encode(wmsRequest, UTF_8);
////// logger.info("Encoded WMS request is: " + wmsRequest);
////// String gisPortletUrl = gisResolver.getGisViewerApplicationURL(scope);
////// logger.info("Gis Viewer Application url is: " + gisPortletUrl);
//////// logger.info("WmsRequest is: " + wmsRequest);
//////// wmsRequest = encodeURLWithParamDelimiter(wmsRequest);
//////// logger.info("Encoded url is: " + wmsRequest);
//////// wmsRequest = appendParamReplacement(wmsRequest);
////// gisPortletUrl+="?wmsrequest="+wmsRequest;
//////
////// System.out.println(gisPortletUrl);
////// urlRedirect(req, resp, gisPortletUrl);
////
//// ScopeProvider.instance.set(scope);
//// String geoExplorerURL = gisResolver.getGeoExplorerApplicationURL(scope);
//// logger.info("GeoExplorer url is: " + geoExplorerURL);
//// } catch (Exception e) {
//// // TODO Auto-generated catch block
//// e.printStackTrace();
//// }
//// }
//}

View File

@ -4,7 +4,7 @@ import java.util.Collection;
import org.gcube.datatransfer.resolver.gis.entity.GeoserverBaseUri;
import org.gcube.datatransfer.resolver.gis.entity.GisLayerItem;
import org.gcube.datatransfer.resolver.gis.util.HttpRequestUtil;
import org.gcube.datatransfer.resolver.util.HttpRequestUtil;
import org.opengis.metadata.Metadata;
import org.opengis.metadata.citation.Citation;
import org.opengis.metadata.citation.OnlineResource;

View File

@ -4,6 +4,7 @@
package org.gcube.datatransfer.resolver.gis.geonetwork;
import org.apache.commons.httpclient.HttpStatus;
import org.gcube.datatransfer.resolver.util.HTTPCallsUtils;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

View File

@ -32,8 +32,9 @@ import org.gcube.datatransfer.resolver.gis.GeonetworkAccessParameter;
import org.gcube.datatransfer.resolver.gis.GeonetworkInstance;
import org.gcube.datatransfer.resolver.gis.GeonetworkServiceInterface;
import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException;
import org.gcube.datatransfer.resolver.gis.geonetwork.HTTPCallsUtils.HttpResponse;
import org.gcube.datatransfer.resolver.gis.util.GetResponseRecordFilter;
import org.gcube.datatransfer.resolver.util.GetResponseRecordFilter;
import org.gcube.datatransfer.resolver.util.HTTPCallsUtils;
import org.gcube.datatransfer.resolver.util.HTTPCallsUtils.HttpResponse;
import org.gcube.spatial.data.geonetwork.configuration.Configuration;
import org.gcube.spatial.data.geonetwork.model.Account;
import org.gcube.spatial.data.geonetwork.model.Account.Type;

View File

@ -1,21 +0,0 @@
/**
*
*/
package org.gcube.datatransfer.resolver.http;
/**
* The Class ConstantsHttpResolver.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 21, 2015
*/
public class ConstantsHttpResolver {
public static final String CONTENT_DISPOSITION = "content-disposition";
public static final String DEFAULT_CONTENTTYPE_UNKNOWN_UNKNOWN = "unknown/unknown";
public static final String DEFAULT_FILENAME_FROM_STORAGE_MANAGER = "fromStorageManager";
protected static final String HPC = "hproxycheck"; //for hproxycheck
}

View File

@ -1,317 +0,0 @@
package org.gcube.datatransfer.resolver.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.gcube.contentmanager.storageclient.model.protocol.smp.Handler;
import org.gcube.contentmanager.storageclient.model.protocol.smp.SMPURLConnection;
import org.gcube.datatransfer.resolver.MultiReadHttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class HttpResolver.
*
* @author Andrea Manzi(CERN)
* updated by Francesco Mangiacrapa
*/
public class HttpResolver extends HttpServlet {
protected static final String SMP_URI = "smp-uri";
protected static final String VALIDATION = "validation";
protected static final String CONTENT_TYPE = "contentType";
protected static final String FILE_NAME = "fileName";
protected static final String SMP_PATH_SEPARATOR = "/";
private static final long serialVersionUID = 1L;
/** The logger. */
private static final Logger logger = LoggerFactory.getLogger(HttpResolver.class);
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
public void init(ServletConfig conf) throws ServletException {
Handler.activateProtocol();
super.init(conf);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String uri =null;
String fileName =null;
String contentType =null;
boolean validatingURI = false;
// logger.info("The http session id is: " + request.getSession().getId());
uri = request.getParameter(SMP_URI);
if (uri == null || uri.equals("")) {
logger.warn("URI not found");
response.sendError(404);
return;
}
fileName = request.getParameter(FILE_NAME);
if (fileName == null || fileName.equals("")) {
logger.warn("fileName not found");
fileName = null;
}
contentType = request.getParameter(CONTENT_TYPE);
if (contentType == null || contentType.equals("")) {
logger.warn("contentType not found");
contentType = null;
}
String validation = request.getParameter(VALIDATION);
validatingURI = Boolean.parseBoolean(validation);
logger.info("validation? "+validatingURI);
//we should not unescape the filename with spaces
logger.debug("uri = "+uri);
int index= uri.indexOf("?");
if (index!= -1){
logger.debug("Found char ?");
String firsPart = uri.substring(0, index);
//PATCH TO FIX #2695
try {
firsPart = validateItemName(firsPart, fileName);
logger.trace("valid smp path is: "+firsPart);
}
catch (Exception e) {
logger.warn("An error occurred during check right filename into SMP PATH");
}
String secondPart= uri.substring( index+1);
logger.debug("replacing in smp-uri char space with char + ...");
//FIXED BY FRANCESCO M.
secondPart = secondPart.replace(" ","+");//the char + is removed when the servlet is doing unescaping of the query parameters, we just put it back
logger.debug("new secondPart: "+secondPart);
uri= firsPart+"?"+secondPart;
}else {
logger.debug("Not found char ?");
uri = uri.replace(" ","+");//the char + is removed when the servlet is doing unescaping of the query parameters, we just put it back
}
logger.info("URI = "+ uri);
InputStream in = null;
try {
OutputStream out = response.getOutputStream();
if (fileName != null){
//The filename should be a quoted string. (According to Section 19.5.1 of RFC 2616)
//http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1
response.setHeader(ConstantsHttpResolver.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
// response.addHeader("content-disposition", "attachment; filename=" +fileName);
}else
response.addHeader("content-disposition", "attachment; filename="+ConstantsHttpResolver.DEFAULT_FILENAME_FROM_STORAGE_MANAGER);
if (contentType!= null)
response.setContentType(contentType);
else
response.setContentType(ConstantsHttpResolver.DEFAULT_CONTENTTYPE_UNKNOWN_UNKNOWN);
URL url = new URL(null, uri, new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new SMPURLConnection(u);
}
});
URLConnection uc = null;
try {
uc = url.openConnection();
in = uc.getInputStream();
}
catch(Exception e){
response.sendError(404);
logger.error("URLConnection Exception:", e);
return;
}
//CASE InputStream NULL
if(in==null){
logger.warn("Input stream is null, sending status error 404");
sendErrorQuietly(response, 404);
return;
}
//CASE VALIDATION
if(validatingURI){
byte[] bytes = new byte[1]; //1B
int c = in.read(bytes);
logger.info(c+" byte read from InputStream");
if(c>0){
logger.info("at least 1 byte read, returning status 200");
IOUtils.closeQuietly(in);
response.setStatus(200);
return;
}
}
//CHANGED BY FRANCESCO M.
try {
IOUtils.copy(in, out);
} catch (IOException e){
logger.warn("IOException class name: "+e.getClass().getSimpleName());
if (e.getClass().getSimpleName().equals("ClientAbortException"))
logger.warn("Skipping ClientAbortException: "+e.getMessage());
else
throw e; //Sending Exceptions
} catch (NullPointerException e) {
logger.warn("NullPointerException during copy, skipping printStrackTrace");
sendErrorQuietly(response, 404);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
} catch (Exception e) {
logger.error("Exception:", e);
IOUtils.closeQuietly(in);
sendErrorQuietly(response, 404);
return;
}
}
/**
* Validate item name.
* Since the right filename is in the URI (fileName=COL_Mammalia_taxa.taf.gz), if SMP path does't contain it the right file is overwritten into SMP PATH
*
* @param smpPath the smp path
* @param fileName the file name
* @return the string
* @throws Exception the exception
*/
protected static String validateItemName(String smpPath, String fileName) throws Exception{
logger.debug("Checking right filename into SMP path..");
if(smpPath==null)
throw new Exception("Invalid smp path: "+smpPath);
int lastSp = smpPath.lastIndexOf(SMP_PATH_SEPARATOR);
if(lastSp<0)
throw new Exception(SMP_PATH_SEPARATOR + " not found in "+smpPath);
String smpItemName = smpPath.substring(lastSp+1, smpPath.length());
if(smpItemName.compareTo(fileName)!=0){
logger.info("SMP PATH contains a different filename, overrinding with "+fileName);
return smpPath.substring(0, lastSp+1)+fileName;
}
logger.info("SMP PATH contains same filename, returning");
return smpPath;
}
/**
* Send error quietly.
*
* @param response the response
* @param code the code
*/
protected void sendErrorQuietly(HttpServletResponse response, int code){
if(response!=null){
try {
response.sendError(code);
logger.info("Response sent error: "+code);
} catch (IOException ioe) {
// ignore
}
}
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doHead(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.info("doHead working..");
String hpc = req.getParameter(ConstantsHttpResolver.HPC); //for HProxy check
try{
if(hpc==null || Boolean.parseBoolean(hpc)){
logger.trace("returning status 200 for Hproxy check");
resp.setStatus(200);
return;
}
}catch (Exception e) {
//silent exception to continue..
}
//ADDING PARAMETER TO PERFORM ONLY VALIDATION
Map<String, String[]> additionalParams = new HashMap<String, String[]>();
String[] value = new String[1];
value[0] = "true";
additionalParams.put(VALIDATION, value);
MultiReadHttpServletRequest request = new MultiReadHttpServletRequest(req, additionalParams);
doGet(request, resp);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
doGet(request,response);
}
// /**
// * The main method.
// *
// * @param args the arguments
// */
// public static void main(String[] args) {
//
// String fileName = "COL_taxa.taf.gz";
// String smpPath = "smp://Share/89971b8f-a993-4e7b-9a95-8d774cb68a99/Work+Packages/WP+6+-+Virtual+Research+Environments+Deployment+and+Operation/T6.2+Resources+and+Tools/COMET-Species-Matching-Engine/YASMEEN/1.2.0/Data/BiOnymTAF/COL_taxa.taf.gz";
// try {
// System.out.println(validateItemName(smpPath, fileName));
// }
// catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}

View File

@ -35,13 +35,13 @@ import org.gcube.datatransfer.resolver.gis.GeonetworkServiceInterface;
import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException;
import org.gcube.datatransfer.resolver.gis.geonetwork.FilterGetRecords;
import org.gcube.datatransfer.resolver.gis.geonetwork.GNAuthentication;
import org.gcube.datatransfer.resolver.gis.geonetwork.HTTPCallsUtils;
import org.gcube.datatransfer.resolver.gis.geonetwork.HTTPCallsUtils.HttpResponse;
import org.gcube.datatransfer.resolver.gis.geonetwork.ReusableInputStream;
import org.gcube.datatransfer.resolver.gis.util.GetResponseRecordFilter;
import org.gcube.datatransfer.resolver.scope.ScopeUtil;
import org.gcube.datatransfer.resolver.services.error.ExceptionManager;
import org.gcube.datatransfer.resolver.services.exceptions.InternalServerException;
import org.gcube.datatransfer.resolver.util.GetResponseRecordFilter;
import org.gcube.datatransfer.resolver.util.HTTPCallsUtils;
import org.gcube.datatransfer.resolver.util.ScopeUtil;
import org.gcube.datatransfer.resolver.util.HTTPCallsUtils.HttpResponse;
import org.gcube.spatial.data.geonetwork.configuration.Configuration;
import org.gcube.spatial.data.geonetwork.model.Account;
import org.gcube.spatial.data.geonetwork.model.Account.Type;

View File

@ -12,9 +12,9 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.datatransfer.resolver.Util;
import org.gcube.datatransfer.resolver.services.error.ErrorReport;
import org.gcube.datatransfer.resolver.services.error.ExceptionReport;
import org.gcube.datatransfer.resolver.util.Util;
;

View File

@ -12,9 +12,9 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.datatransfer.resolver.Util;
import org.gcube.datatransfer.resolver.services.error.ErrorReport;
import org.gcube.datatransfer.resolver.services.error.ExceptionReport;
import org.gcube.datatransfer.resolver.util.Util;
;
/**

View File

@ -12,9 +12,9 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.datatransfer.resolver.Util;
import org.gcube.datatransfer.resolver.services.error.ErrorReport;
import org.gcube.datatransfer.resolver.services.error.ExceptionReport;
import org.gcube.datatransfer.resolver.util.Util;
;

View File

@ -12,9 +12,9 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.datatransfer.resolver.Util;
import org.gcube.datatransfer.resolver.services.error.ErrorReport;
import org.gcube.datatransfer.resolver.services.error.ExceptionReport;
import org.gcube.datatransfer.resolver.util.Util;
;

View File

@ -12,9 +12,9 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.datatransfer.resolver.Util;
import org.gcube.datatransfer.resolver.services.error.ErrorReport;
import org.gcube.datatransfer.resolver.services.error.ExceptionReport;
import org.gcube.datatransfer.resolver.util.Util;
;
/**

View File

@ -12,9 +12,9 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.datatransfer.resolver.Util;
import org.gcube.datatransfer.resolver.services.error.ErrorReport;
import org.gcube.datatransfer.resolver.services.error.ExceptionReport;
import org.gcube.datatransfer.resolver.util.Util;
/**

View File

@ -12,9 +12,9 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.datatransfer.resolver.Util;
import org.gcube.datatransfer.resolver.services.error.ErrorReport;
import org.gcube.datatransfer.resolver.services.error.ExceptionReport;
import org.gcube.datatransfer.resolver.util.Util;
;

View File

@ -2,7 +2,7 @@
*
*/
package org.gcube.datatransfer.resolver.gis.util;
package org.gcube.datatransfer.resolver.util;
import it.geosolutions.geonetwork.exception.GNLibException;
import it.geosolutions.geonetwork.exception.GNServerException;
@ -34,8 +34,7 @@ import org.apache.commons.httpclient.HttpStatus;
import org.gcube.datatransfer.resolver.gis.GeonetworkInstance;
import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException;
import org.gcube.datatransfer.resolver.gis.geonetwork.GNAuthentication;
import org.gcube.datatransfer.resolver.gis.geonetwork.HTTPCallsUtils;
import org.gcube.datatransfer.resolver.gis.geonetwork.HTTPCallsUtils.HttpResponse;
import org.gcube.datatransfer.resolver.util.HTTPCallsUtils.HttpResponse;
import org.gcube.spatial.data.geonetwork.LoginLevel;
import org.gcube.spatial.data.geonetwork.model.Account.Type;
import org.gcube.spatial.data.geonetwork.model.faults.MissingServiceEndpointException;

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.datatransfer.resolver.gis.geonetwork;
package org.gcube.datatransfer.resolver.util;
import java.io.ByteArrayInputStream;

View File

@ -1,4 +1,4 @@
package org.gcube.datatransfer.resolver.gis.util;
package org.gcube.datatransfer.resolver.util;
import java.io.BufferedReader;
import java.io.IOException;

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.datatransfer.resolver.gis.util;
package org.gcube.datatransfer.resolver.util;
import java.util.HashMap;
import java.util.Iterator;

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.datatransfer.resolver.gis.util;
package org.gcube.datatransfer.resolver.util;

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.datatransfer.resolver.scope;
package org.gcube.datatransfer.resolver.util;
/**

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.datatransfer.resolver.catalogue;
package org.gcube.datatransfer.resolver.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

View File

@ -1,7 +1,7 @@
/**
*
*/
package org.gcube.datatransfer.resolver;
package org.gcube.datatransfer.resolver.util;
import javax.servlet.http.HttpServletRequest;

View File

@ -1,128 +1,128 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.datatransfer.resolver.gis.geonetwork.GeonetworkResolver;
import org.gcube.datatransfer.resolver.gis.geonetwork.HTTPCallsUtils;
import org.gcube.datatransfer.resolver.gis.util.GetResponseRecordFilter;
import org.gcube.spatial.data.geonetwork.GeoNetwork;
import org.gcube.spatial.data.geonetwork.GeoNetworkPublisher;
import org.gcube.spatial.data.geonetwork.LoginLevel;
import org.gcube.spatial.data.geonetwork.configuration.Configuration;
import org.gcube.spatial.data.geonetwork.model.Account;
import org.gcube.spatial.data.geonetwork.model.Account.Type;
/**
*
*/
/**
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Sep 8, 2016
*/
public class GeonetworkResolverTest {
private static String scope = "/d4science.research-infrastructures.eu";
private static LoginLevel loginLevel = LoginLevel.SCOPE;
private static Type accountType = Type.CKAN;
/**
* The main method.
*
* @param args the arguments
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
public static void main(String[] args) throws UnsupportedEncodingException {
/*String scopeValue ="/gcube/devsec/devVRE";
String remainValue = "/srv/en/mef.export";
String queryString = "scope=/gcube/devsec/devVRE&remainPath=/srv/en/mef.export&version=2.0.2&request=GetCapabilities&service=CSW";
ServerParameters geonetworkParams = new ServerParameters("http://geoserver-dev2.d4science-ii.research-infrastructures.eu/geonetwork", "", "");
String newQueryString = purgeScopeFromQueryString(scopeValue, queryString);
logger.info("Purged query string from "+scopeValue+" is: "+newQueryString);
String baseURL = remainValue==null ||remainValue.isEmpty()?geonetworkParams.getUrl()+"/"+CSW_SERVER:geonetworkParams.getUrl()+"/"+CSW_SERVER+remainValue;
logger.info("New base URL "+baseURL);
newQueryString = purgeRemainFromQueryString(remainValue, newQueryString);
logger.info("Purged query string from "+remainValue+" is: "+newQueryString);
String gnGetlURL = newQueryString==null || newQueryString.isEmpty()? baseURL : baseURL+"?"+newQueryString;
logger.info("Sending get request to URL: "+gnGetlURL);*/
try{
HTTPCallsUtils httpUtils = new HTTPCallsUtils();
String data ="";
ScopeProvider.instance.set(scope);
GeoNetworkPublisher reader=GeoNetwork.get();
Configuration config = reader.getConfiguration();
Account account=config.getScopeConfiguration().getAccounts().get(accountType);
reader.login(loginLevel);
String contentType = "application/xml ; charset=\"UTF-8\"";
String uuid = "c15ae8e5-71c0-4b8b-aa29-304cc4e97238";
String gnCSWlURL = "http://geonetwork.d4science.org/geonetwork/srv/en/csw";
// String gnCSWlURL = "http://geoserver-dev2.d4science-ii.research-infrastructures.eu/geonetwork/srv/en//srv/en/mef.export";
/*File file = File.createTempFile(uuid, ".xml");
InputStream response = httpUtils.post(gnCSWlURL, file, contentType);*/
//MAP
Map<String, String[]> map = new HashMap<String, String[]>();
String[] value = new String[1];
value[0]=uuid;
map.put(GeonetworkResolver.UUID, value);
// data = "<request><uuid>"+uuid+"</uuid></request>";
data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<csw:GetRecordById xmlns:csw=\"http://www.opengis.net/cat/csw/2.0.2\" service=\"CSW\" version=\"2.0.2\" " +
"outputSchema=\"csw:IsoRecord\" xsi:schemaLocation=\"http://www.opengis.net/cat/csw/2.0.2/CSW-discovery.xsd\" xmlns=\"http://www.opengis.net/cat/csw/2.0.2\" " +
"xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dct=\"http://purl.org/dc/terms/\" xmlns:gml=\"http://www.opengis.net/gml\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+
"<csw:Id>"+uuid+"</csw:Id>" +
"<ElementSetName typeNames=\"csw:Record\">full</ElementSetName>" +
"</csw:GetRecordById>";
byte[] byteArray = data.getBytes();
InputStream response = httpUtils.post(gnCSWlURL, new ByteArrayInputStream(byteArray), contentType, map);
// String respToString = IOUtils.toString(response);
// System.out.println("Response returned by request: \n"+respToString);
// InputStream responseToIs = IOUtils.toInputStream(respToString);
if(response!=null){
try {
InputStream re = GetResponseRecordFilter.overrideResponseIdsByListIds(response, new ArrayList<String>(), "Replaced UUID");
// String theString = IOUtils.toString(re);
// System.out.println("Response returned after overriding: \n"+theString);
final Path destination = Paths.get("test.xml");
Files.copy(re, destination);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
//import java.io.ByteArrayInputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.UnsupportedEncodingException;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.Map;
//
//import org.gcube.common.scope.api.ScopeProvider;
//import org.gcube.datatransfer.resolver.gis.geonetwork.GeonetworkResolver;
//import org.gcube.datatransfer.resolver.gis.geonetwork.HTTPCallsUtils;
//import org.gcube.datatransfer.resolver.gis.util.GetResponseRecordFilter;
//import org.gcube.spatial.data.geonetwork.GeoNetwork;
//import org.gcube.spatial.data.geonetwork.GeoNetworkPublisher;
//import org.gcube.spatial.data.geonetwork.LoginLevel;
//import org.gcube.spatial.data.geonetwork.configuration.Configuration;
//import org.gcube.spatial.data.geonetwork.model.Account;
//import org.gcube.spatial.data.geonetwork.model.Account.Type;
//
//
///**
// *
// */
///**
// *
// * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
// * Sep 8, 2016
// */
//public class GeonetworkResolverTest {
//
// private static String scope = "/d4science.research-infrastructures.eu";
//
// private static LoginLevel loginLevel = LoginLevel.SCOPE;
//
// private static Type accountType = Type.CKAN;
//
// /**
// * The main method.
// *
// * @param args the arguments
// * @throws UnsupportedEncodingException the unsupported encoding exception
// */
// public static void main(String[] args) throws UnsupportedEncodingException {
//
// /*String scopeValue ="/gcube/devsec/devVRE";
// String remainValue = "/srv/en/mef.export";
// String queryString = "scope=/gcube/devsec/devVRE&remainPath=/srv/en/mef.export&version=2.0.2&request=GetCapabilities&service=CSW";
// ServerParameters geonetworkParams = new ServerParameters("http://geoserver-dev2.d4science-ii.research-infrastructures.eu/geonetwork", "", "");
//
// String newQueryString = purgeScopeFromQueryString(scopeValue, queryString);
// logger.info("Purged query string from "+scopeValue+" is: "+newQueryString);
//
// String baseURL = remainValue==null ||remainValue.isEmpty()?geonetworkParams.getUrl()+"/"+CSW_SERVER:geonetworkParams.getUrl()+"/"+CSW_SERVER+remainValue;
// logger.info("New base URL "+baseURL);
// newQueryString = purgeRemainFromQueryString(remainValue, newQueryString);
// logger.info("Purged query string from "+remainValue+" is: "+newQueryString);
//
// String gnGetlURL = newQueryString==null || newQueryString.isEmpty()? baseURL : baseURL+"?"+newQueryString;
// logger.info("Sending get request to URL: "+gnGetlURL);*/
//
// try{
// HTTPCallsUtils httpUtils = new HTTPCallsUtils();
// String data ="";
//
// ScopeProvider.instance.set(scope);
// GeoNetworkPublisher reader=GeoNetwork.get();
//
//
// Configuration config = reader.getConfiguration();
// Account account=config.getScopeConfiguration().getAccounts().get(accountType);
// reader.login(loginLevel);
//
// String contentType = "application/xml ; charset=\"UTF-8\"";
// String uuid = "c15ae8e5-71c0-4b8b-aa29-304cc4e97238";
// String gnCSWlURL = "http://geonetwork.d4science.org/geonetwork/srv/en/csw";
//// String gnCSWlURL = "http://geoserver-dev2.d4science-ii.research-infrastructures.eu/geonetwork/srv/en//srv/en/mef.export";
//
// /*File file = File.createTempFile(uuid, ".xml");
// InputStream response = httpUtils.post(gnCSWlURL, file, contentType);*/
//
// //MAP
// Map<String, String[]> map = new HashMap<String, String[]>();
// String[] value = new String[1];
// value[0]=uuid;
// map.put(GeonetworkResolver.UUID, value);
//// data = "<request><uuid>"+uuid+"</uuid></request>";
//
// data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
// "<csw:GetRecordById xmlns:csw=\"http://www.opengis.net/cat/csw/2.0.2\" service=\"CSW\" version=\"2.0.2\" " +
// "outputSchema=\"csw:IsoRecord\" xsi:schemaLocation=\"http://www.opengis.net/cat/csw/2.0.2/CSW-discovery.xsd\" xmlns=\"http://www.opengis.net/cat/csw/2.0.2\" " +
// "xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dct=\"http://purl.org/dc/terms/\" xmlns:gml=\"http://www.opengis.net/gml\" " +
// "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+
// "<csw:Id>"+uuid+"</csw:Id>" +
// "<ElementSetName typeNames=\"csw:Record\">full</ElementSetName>" +
// "</csw:GetRecordById>";
//
// byte[] byteArray = data.getBytes();
// InputStream response = httpUtils.post(gnCSWlURL, new ByteArrayInputStream(byteArray), contentType, map);
//
//// String respToString = IOUtils.toString(response);
//// System.out.println("Response returned by request: \n"+respToString);
//// InputStream responseToIs = IOUtils.toInputStream(respToString);
// if(response!=null){
// try {
//
// InputStream re = GetResponseRecordFilter.overrideResponseIdsByListIds(response, new ArrayList<String>(), "Replaced UUID");
//// String theString = IOUtils.toString(re);
//// System.out.println("Response returned after overriding: \n"+theString);
//
// final Path destination = Paths.get("test.xml");
// Files.copy(re, destination);
// }
// catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// }catch (Exception e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
//
// }
//}