diff --git a/distro/changelog.xml b/distro/changelog.xml index 5a672ba..783b11f 100644 --- a/distro/changelog.xml +++ b/distro/changelog.xml @@ -104,4 +104,9 @@ public/private items to public/private catalogue + + [Task #12740] Developed as web-service by using jersey + + \ No newline at end of file diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/ConstantsResolver.java b/src/main/java/org/gcube/datatransfer/resolver/services/ConstantsResolver.java index 7a296b1..c5c582f 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/ConstantsResolver.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/ConstantsResolver.java @@ -16,11 +16,12 @@ public class ConstantsResolver { public static final String DEFAULT_CONTENTTYPE_UNKNOWN_UNKNOWN = "unknown/unknown"; public static final String DEFAULT_FILENAME_FROM_STORAGE_MANAGER = "fromStorageManager"; public static final String CONTENT_LENGTH = "Content-Length"; + public static final String CONTENT_TYPE= "Content-Type"; protected static final String HPC = "hproxycheck"; //for hproxycheck - public static final String VALIDATION = "validation"; - public static final String CONTENT_TYPE = "contentType"; - public static final String FILE_NAME = "fileName"; + public static final String QUERY_PARAM_VALIDATION = "validation"; + public static final String QUERY_PARAM_CONTENT_TYPE = "contentType"; + public static final String QUERY_PARAM_FILE_NAME = "fileName"; } diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/GeonetworkResolver.java b/src/main/java/org/gcube/datatransfer/resolver/services/GeonetworkResolver.java new file mode 100644 index 0000000..e32291b --- /dev/null +++ b/src/main/java/org/gcube/datatransfer/resolver/services/GeonetworkResolver.java @@ -0,0 +1,620 @@ +package org.gcube.datatransfer.resolver.services; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.Nullable; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.StreamingOutput; + +import org.apache.commons.io.IOUtils; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.datatransfer.resolver.Constants; +import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters; +import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters.MODE; +import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters.VISIBILITY; +import org.gcube.datatransfer.resolver.SingleFileStreamingOutput; +import org.gcube.datatransfer.resolver.Util; +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.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.services.error.ExceptionManager; +import org.gcube.datatransfer.resolver.services.exceptions.InternalServerException; +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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * The Class GeonetworkResolver. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Oct 23, 2018 + */ +@Path(Constants.SERVLET_GEONETWORK) +public class GeonetworkResolver { + + private static Logger logger = LoggerFactory.getLogger(GeonetworkResolver.class); + + public static final String PATH_PARAM_MODE = "mode"; + public static final String PATH_PARAM_REQUEST_DELIMITER = "requestDelimiter"; + public static final String PATH_PARAM_OWNER = "owner"; + private static final String PATH_PARAM_VISIBILITY = "visibility"; + + private static final String PATH_PARAM_SCOPE = "scope"; + public static final String CSW_SERVER = "srv/en/csw"; + + public static final String PATH_PARAM_REQUEST_DELIMITIER = "/$$"; + public static final String PATH_PARAM_REMAINING = "remainPath"; + + public static final String QUERY_PARAM_RESET_CACHE_PARAM = "resetcache"; + public static final String QUERY_PARAM_RESET_CACHED_SCOPE_PARAM = "resetcachedscope"; + + public static final String SRV_EN_MEF_EXPORT = "/srv/en/mef.export"; //MEF Geonetwork service + + public static final String UUID = "uuid"; + + protected Map cacheGNInstances; + + private String help = "https://wiki.gcube-system.org/gcube/URI_Resolver#GIS_Resolver"; + + /** + * 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 req the req + * @param mode the mode + * @param scope the scope + * @param visibility the visibility + * @param owner the owner + * @param requestDelimiter the request delimiter + * @param resetCache the reset cache + * @param resetScope the reset scope + * @return the geonetwork request criteria + */ + +// /* (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 Geonetwork configuratiors cache..."); +// purgeCacheGeonetworkInstances(); +// } +// }, CACHE_RESET_DELAY, CACHE_RESET_TIME); +// } + + @GET + @Path("{"+PATH_PARAM_MODE+"}/{"+PATH_PARAM_SCOPE+"}/{"+PATH_PARAM_VISIBILITY+"}/{"+PATH_PARAM_OWNER+"}/{"+PATH_PARAM_REQUEST_DELIMITER+"}") + public Response submitGet(@Context HttpServletRequest req, + @PathParam(PATH_PARAM_MODE) MODE mode, + @PathParam(PATH_PARAM_SCOPE) String scope, + @PathParam(PATH_PARAM_VISIBILITY) VISIBILITY visibility, + @PathParam(PATH_PARAM_OWNER) @Nullable String owner, + @PathParam(PATH_PARAM_REQUEST_DELIMITER) String requestDelimiter, + @QueryParam(QUERY_PARAM_RESET_CACHE_PARAM) String resetCache, + @QueryParam(QUERY_PARAM_RESET_CACHED_SCOPE_PARAM) String resetScope) { + + + //Checking mandatory parameters + if(mode==null){ + logger.error("Path Parameter 'mode' not found"); + ExceptionManager.throwBadRequestException(req, "Missing mandatory path parameter 'mode' as value "+MODE.values(), GeonetworkResolver.class, help); + } + + if(scope==null || scope.isEmpty()){ + logger.error("Path Parameter 'scope' not found"); + ExceptionManager.throwBadRequestException(req, "Missing mandatory path parameter 'scope'", GeonetworkResolver.class, help); + } + + if(visibility==null){ + logger.error("Path Parameter 'visibility' not found"); + ExceptionManager.throwBadRequestException(req, "Missing mandatory path parameter 'visibility'", GeonetworkResolver.class, help); + } + + logger.info("Params are [mode: "+mode+", scope: "+scope+", visibility:"+visibility+", owner:"+owner+"]"); + + if(requestDelimiter==null){ + logger.error("Path Parameter to REQUEST_DELIMITIER '"+PATH_PARAM_REQUEST_DELIMITIER+"' not found"); + ExceptionManager.throwBadRequestException(req, "Path Parameter to REQUEST_DELIMITIER '"+PATH_PARAM_REQUEST_DELIMITIER+"' not found", GeonetworkResolver.class, help); + } + + if(resetCache!=null && Boolean.parseBoolean(resetCache)){ + purgeCacheGeonetworkInstances(); + } + + if(resetScope!=null && Boolean.parseBoolean(resetScope)){ + resetGeonetoworkInstanceCacheForScope(scope); + } + + String fullURL = Util.getFullURL(req); + int index = fullURL.indexOf(GeonetworkRequestFilterParameters.REQUEST_DELIMITIER); + int delimiterIndex = index+GeonetworkRequestFilterParameters.REQUEST_DELIMITIER.length(); + //BUILDING REMAINING PATH WITHOUT GeonetworkRequestFilterParameters.REQUEST_DELIMITIER + String remainPath = null; + if(delimiterIndex e = req.getParameterNames(); e.hasMoreElements();){ + String p = e.nextElement(); + logger.debug("param "+p + " value "+Arrays.toString(req.getParameterValues(p))); + } + + + //DEBUG BODY +// String readBody = IOUtils.toString(req.getReader()); +// logger.debug("doPost read body request: "+readBody); + ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); + + String geonetworkUrl = config.getGeoNetworkEndpoint(); + + // SPECIFIC HANDLER FOR GEONETWORK REQUEST: /srv/en/mef.export + if(remainPath!=null && remainPath.compareTo(SRV_EN_MEF_EXPORT)==0){ + logger.info("In case of mef.export, perfoming a custom handler"); + gnCSWlURL = geonetworkUrl + SRV_EN_MEF_EXPORT; + String[] uuidValues = req.getParameterValues(UUID); + if(uuidValues!=null){ + String data = null; + for (String uuid : uuidValues) { + data = UUID+"="+uuid; + } + if(data!=null){ + logger.debug("Writing "+data +" into byte array"); + byteArray.write(data.getBytes()); + }else + IOUtils.copy(req.getReader(), byteArray); + }else + IOUtils.copy(req.getReader(), byteArray); + }else{ + gnCSWlURL = remainPath==null ||remainPath.isEmpty()?geonetworkUrl+"/"+CSW_SERVER:geonetworkUrl+"/"+CSW_SERVER+remainPath; + IOUtils.copy(req.getReader(), byteArray); + } + + //filterPublicMetadata = theVisibility.equals(VISIBILITY.PRV)?true:false; + + HTTPCallsUtils httpUtils = new HTTPCallsUtils(); + + //PRIVATE LAYERS + if(visibility.equals(VISIBILITY.PRV)){ + logger.debug("Visibility: "+VISIBILITY.PRV+" getting private layers.."); + //VRE LAYERS + if(mode.equals(MODE.VRE)){ + logger.debug("Getting "+MODE.VRE+" layers.."); + + //HARVESTED LAYERS + }else{ + logger.debug("Getting "+MODE.HARVEST+" layers, I'm using the owner: '"+owner +"' passed as parameter to filter layer/s returned.."); + if(owner==null || owner.isEmpty()){ + String error = "Harvest owner is missing. It is not possible to filter layers for the request "+MODE.HARVEST + " in the scope: "+scope+", without a valid owner as input"; + logger.error(error); + ExceptionManager.throwBadRequestException(req, error, GeonetworkResolver.class, help); + } + } + + if(account.getUser()!=null){ + boolean authorized = GNAuthentication.login(httpUtils, geonetworkUrl, account.getUser(), account. getPassword()); + logger.trace("Authorized on "+geonetworkUrl +" ? "+authorized); + }else + logger.info("Skipping authentication, ckan user (the owner) is null"); + + //PUBLIC LAYERS + }else{ + logger.debug("Visibility: "+VISIBILITY.PUB+" getting public layers.."); + //VRE LAYERS + if(mode.equals(MODE.VRE)){ + logger.debug("Getting "+MODE.VRE+" layers, the VRE account: "+account.getUser() +" will be used as owner user for filtering... Is it right?"); + owner = account.getUser(); + + //HARVESTED LAYERS + }else{ + logger.debug("Getting "+MODE.HARVEST+" layers, I'm using the owner: '"+owner +"' passed as parameter to filter layer/s returned.."); + if(owner==null || owner.isEmpty()){ + String error = "Harvest owner is missing. It is not possible to filter layers for the request "+MODE.HARVEST + " in the scope: "+scope+", without a valid owner as input"; + logger.error(error); + ExceptionManager.throwBadRequestException(req, error, GeonetworkResolver.class, help); + } + } + } + + logger.info("Sending CSW POST request to URL: "+gnCSWlURL); + logger.debug("Content-Type: "+req.getContentType()); + + + //DEBUG + //logger.debug("POST - BODY : "+byteArray.toString()); + InputStream in = httpUtils.post(gnCSWlURL, new ByteArrayInputStream(byteArray.toByteArray()), req.getContentType(), req.getParameterMap()); +// resp.setContentType(httpUtils.getLastContentType()); +// OutputStream out = resp.getOutputStream(); + + if(in==null){ + logger.warn("Input stream returned is null, sending "+HttpServletResponse.SC_NOT_FOUND); + ExceptionManager.throwNotFoundException(req, "Input stream is null to the request "+gnCSWlURL+ " with body: "+byteArray.toString(), GeonetworkResolver.class, help); + } + + try{ + + ReusableInputStream reus = new ReusableInputStream(in); + + if(visibility.equals(VISIBILITY.PRV)){ + logger.info("Private VISIBILITY performing so getting public file identifiers to apply filtering.."); + FilterGetRecords filterGetRecords = new FilterGetRecords(byteArray.toString()); + if(filterGetRecords.getFoundPublicIds()!=null && filterGetRecords.getFoundPublicIds().size()>0){ + logger.info("I'm removing list of public IDs with "+filterGetRecords.getFoundPublicIds().size() +" item/s. Is it right?"); + in = GetResponseRecordFilter.overrideResponseIdsByListIds(reus, filterGetRecords.getFoundPublicIds(), "Replaced a public UUID, please ignore"); + } + }else { + + logger.info("Public VISIBILITY perfoming check on ownership..."); + Document doc = GetResponseRecordFilter.inputStreamToW3CDocument(reus); + List fileIdentifiers = GetResponseRecordFilter.getTextContentStringsForTagName(doc, "gmd:fileIdentifier"); + List noMatchingOwner = new ArrayList(); + for (String fileId : fileIdentifiers) { + String own = GetResponseRecordFilter.getMetaCategoryByFileIdentifier(fileId, config.getGeoNetworkEndpoint(),config.getAdminAccount().getUser(), config.getAdminAccount().getPassword()); + //String own = GetResponseRecordFilter.getMetaOwnerNameByFileIdentifier(fileId, config.getGeoNetworkEndpoint(),config.getAdminAccount().getUser(), config.getAdminAccount().getPassword()); + if(own.compareTo(owner)!=0){ + logger.debug("Owner of file Identifier "+fileId+" not matching the owner passed: "+owner+", removing it.."); + noMatchingOwner.add(fileId); + } + } + if(noMatchingOwner.size()>0){ + logger.info("Removing "+noMatchingOwner.size()+" layer/s not macthing the owner: "+owner); + in = GetResponseRecordFilter.overrideResponseIdsByListIds(reus, noMatchingOwner, "Replaced UUID owned by another user, please ignore"); + }else{ + logger.info("No replace on UUIDs was applied for the owner: "+owner); + in = reus; + } + } + + ReusableInputStream reusIs = new ReusableInputStream(in); + + //END DEBUG + logger.debug("Response return Content-Type: "+httpUtils.getLastContentType()); + return Response + .ok(reusIs) + //.header(ConstantsResolver.CONTENT_DISPOSITION,"attachment; filename = \""+fileName+"\"") + .header(ConstantsResolver.CONTENT_TYPE, httpUtils.getLastContentType()).build(); + + //int bytes = IOUtils.copy(reusIs, out); + //logger.trace("POST - RETURN : "+IOUtils.toString(reusIs)); + +// if(bytes==0) +// logger.warn("ResponseBody is empty, returning empty resp"); + }catch(Exception e){ + logger.error("Error on copy the response to send to client: ", e); + ExceptionManager.throwInternalErrorException(req, "Error on copy the response!", GeonetworkResolver.class, help); + }finally{ + IOUtils.closeQuietly(in); + } + + } catch (IllegalArgumentException e){ + logger.error("IllegalArgumentException:", e); + ExceptionManager.throwBadRequestException(req, "Illegal argument to carry out the request!", GeonetworkResolver.class, help); + + } catch (Exception e) { + logger.error("Exception:", e); + String error = "Sorry, an error occurred on resolving geonetwork request with scope "+scope+". Please, contact support!"; + ExceptionManager.throwInternalErrorException(req, error, GeonetworkResolver.class, help); + } + + //An error occurred + try { + + throw new InternalServerException(req, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR, "Error during perform POST operation to: "+gnCSWlURL, GeonetworkResolver.class, new URI(help)); + } + catch (URISyntaxException e) { + //silent + return null; + } + + } + + /** + * Purge remain from query string. + * + * @param remain_value the scope + * @param queryString the query string + * @return the string + */ + private static String purgeRemainFromQueryString(String remain_value, String queryString){ +// SCOPE is: /gcube/devsec/devVRE +// [INFO ] 2016-04-05 15:01:42,808 org.gcube.datatransfer.resolver.gis.geonetwork.GeonetworkResolver - +// Query String is: scope=/gcube/devsec/devVRE&version=2.0.2&request=GetCapabilities&service=CSW + int start = queryString.indexOf(PATH_PARAM_REMAINING+"="); + + if(start>=0){ + int end = queryString.indexOf("&", start); + + if(end==-1 && queryString.length()==(PATH_PARAM_REMAINING+"="+remain_value).length()){ //SCOPE IS THE UNIQUE PARAMETER INTO QUETY STRING + logger.debug("Scope is the unique parameter, returning empty query string"); + return ""; + }else if(end=0){ + int end = queryString.indexOf("&", start); + + if(end==-1 && queryString.length()==(PATH_PARAM_SCOPE+"="+scope_value).length()){ //SCOPE IS THE UNIQUE PARAMETER INTO QUETY STRING + logger.debug("Scope is the unique parameter, returning empty query string"); + return ""; + }else if(end(); + logger.info("Reset of GeonetworkInstance cache perfomed!"); + } + + /** + * Gets the geonetwork instance for scope. + * + * @param scope the scope + * @return the geonetwork instance for scope + * @throws Exception the exception + */ + protected GeonetworkInstance getGeonetworkInstanceForScope(String scope) throws Exception{ + + if(cacheGNInstances==null) + purgeCacheGeonetworkInstances(); + + logger.info("Attempt to get geonetwork instance from GeonetworkInstance cache for scope: "+scope); + GeonetworkInstance geoInstance = cacheGNInstances.get(scope); + + if(geoInstance==null){ + logger.info("Cache having null GeonetworkInstance for scope "+scope+", reading by Geonetwork library..."); + try { + geoInstance = discoveryGeonetworkInstance(scope); + cacheGNInstances.put(scope, geoInstance); + logger.info("Updated GeonetworkInstance Cache adding couple: Scope "+scope+" - GeonetworkInstance "+geoInstance); + } catch (Exception e) { + logger.error("An error occurred on reading GeonetworkInstance for scope "+scope, e); + throw new Exception("Sorry, An error occurred on reading GeonetworkInstance for scope "+scope); + } + }else + logger.info("GeonetworkInstance cache for scope: "+scope+" is not null using it: "+geoInstance); + + return geoInstance; + } + +} diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/GisResolver.java b/src/main/java/org/gcube/datatransfer/resolver/services/GisResolver.java deleted file mode 100644 index 6247c7e..0000000 --- a/src/main/java/org/gcube/datatransfer/resolver/services/GisResolver.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.gcube.datatransfer.resolver.services; - -import java.net.URI; -import java.net.URISyntaxException; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response.Status; - -import org.gcube.datatransfer.resolver.Constants; -import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters.MODE; -import org.gcube.datatransfer.resolver.GeonetworkRequestFilterParameters.VISIBILITY; -import org.gcube.datatransfer.resolver.services.exceptions.BadRequestException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Path(Constants.SERVLET_GEONETWORK) -public class GisResolver { - - private static Logger logger = LoggerFactory.getLogger(GisResolver.class); - - private String help = "https://wiki.gcube-system.org/gcube/URI_Resolver#GIS_Resolver"; - - @GET - public void submitGet(@Context HttpServletRequest req, @PathParam("mode") MODE mode, @PathParam("scope") String scope, @PathParam("visibility") VISIBILITY visibility, @PathParam("owner") String owner) { - -// MODE mode = null; -// String theScope = null; -// VISIBILITY visibility = null; -// String owner = null; - - - //Checking mandatory parameter id - if(mode==null){ - logger.error("Path Parameter 'mode' not found"); - try { - throw new BadRequestException(req, Status.NOT_ACCEPTABLE, "Missing mandatory path parameter 'mode'", StorageHubResolver.class, new URI(help)); - } - catch (URISyntaxException e) { - //silent - } - } - - if(scope==null || scope.isEmpty()){ - logger.error("Path Parameter 'scope' not found"); - try { - throw new BadRequestException(req, Status.NOT_ACCEPTABLE, "Missing mandatory path parameter 'scope'", StorageHubResolver.class, new URI(help)); - } - catch (URISyntaxException e) { - //silent - } - } - - - if(visibility==null){ - logger.error("Path Parameter 'visibility' not found"); - try { - throw new BadRequestException(req, Status.NOT_ACCEPTABLE, "Missing mandatory path parameter 'visibility'", StorageHubResolver.class, new URI(help)); - } - catch (URISyntaxException e) { - //silent - } - } - - if(visibility==null){ - logger.error("Path Parameter 'visibility' not found"); - try { - throw new BadRequestException(req, Status.NOT_ACCEPTABLE, "Missing mandatory path parameter 'visibility'", StorageHubResolver.class, new URI(help)); - } - catch (URISyntaxException e) { - //silent - } - } - - - - - } - - @POST - public void submitPost(){ - - } - -} diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/SMPIDResolver.java b/src/main/java/org/gcube/datatransfer/resolver/services/SMPIDResolver.java index 347014b..0977495 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/SMPIDResolver.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/SMPIDResolver.java @@ -43,7 +43,7 @@ public class SMPIDResolver { */ @GET @Path("id") - public Response getSMPID(@Context HttpServletRequest httpRequest, @QueryParam(SMP_ID) @Nullable String smpId, @QueryParam(ConstantsResolver.FILE_NAME) String fileName, @QueryParam(ConstantsResolver.CONTENT_TYPE) String contentType, @QueryParam(ConstantsResolver.VALIDATION) Boolean validation){ + public Response getSMPID(@Context HttpServletRequest httpRequest, @QueryParam(SMP_ID) @Nullable String smpId, @QueryParam(ConstantsResolver.QUERY_PARAM_FILE_NAME) String fileName, @QueryParam(ConstantsResolver.QUERY_PARAM_CONTENT_TYPE) String contentType, @QueryParam(ConstantsResolver.QUERY_PARAM_VALIDATION) Boolean validation){ logger.info("resolve smp-id called"); //Checking mandatory parameter smpId diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/SMPResolver.java b/src/main/java/org/gcube/datatransfer/resolver/services/SMPResolver.java index 778122d..13db014 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/SMPResolver.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/SMPResolver.java @@ -44,7 +44,7 @@ public class SMPResolver { */ @GET @Path("smp") - public Response getSMPURI(@Context HttpServletRequest httpRequest, @QueryParam(SMP_URI) @Nullable String smpURI, @QueryParam(ConstantsResolver.FILE_NAME) String fileName, @QueryParam(ConstantsResolver.CONTENT_TYPE) String contentType, @QueryParam(ConstantsResolver.VALIDATION) Boolean validation){ + public Response getSMPURI(@Context HttpServletRequest httpRequest, @QueryParam(SMP_URI) @Nullable String smpURI, @QueryParam(ConstantsResolver.QUERY_PARAM_FILE_NAME) String fileName, @QueryParam(ConstantsResolver.QUERY_PARAM_CONTENT_TYPE) String contentType, @QueryParam(ConstantsResolver.QUERY_PARAM_VALIDATION) Boolean validation){ logger.info("resolve smp-uri called"); //Checking mandatory parameter smpURI diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/StorageIDResolver.java b/src/main/java/org/gcube/datatransfer/resolver/services/StorageIDResolver.java index c83d348..9550628 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/StorageIDResolver.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/StorageIDResolver.java @@ -63,7 +63,7 @@ public class StorageIDResolver { @GET @Path("{storage-id:(?!index)[^/?$]*}") //@Path("{storage-id}") - public Response getStorageId(@Context HttpServletRequest httpRequest, @PathParam(STORAGE_ID) String storageId, @QueryParam(ConstantsResolver.FILE_NAME) String fileName, @QueryParam(ConstantsResolver.CONTENT_TYPE) String contentType, @QueryParam(ConstantsResolver.VALIDATION) Boolean validation) { + public Response getStorageId(@Context HttpServletRequest httpRequest, @PathParam(STORAGE_ID) String storageId, @QueryParam(ConstantsResolver.QUERY_PARAM_FILE_NAME) String fileName, @QueryParam(ConstantsResolver.QUERY_PARAM_CONTENT_TYPE) String contentType, @QueryParam(ConstantsResolver.QUERY_PARAM_VALIDATION) Boolean validation) { logger.info("resolve Storage-Id called"); //Checking mandatory parameter storageId if(storageId==null || storageId.isEmpty()){ diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/error/ExceptionManager.java b/src/main/java/org/gcube/datatransfer/resolver/services/error/ExceptionManager.java index c62818b..5912403 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/error/ExceptionManager.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/error/ExceptionManager.java @@ -84,6 +84,39 @@ public class ExceptionManager { } + /** + * Throw unauthorized exception. + * + * @param httpRequest the http request + * @param errorMessage the error message + * @param thrownBy the thrown by + * @param helpURI the help uri + */ + public static void throwUnauthorizedException(HttpServletRequest httpRequest, String errorMessage, Class thrownBy, String helpURI){ + + URI theURI = checkURI(helpURI); + throw new WrongParameterException(httpRequest, Status.UNAUTHORIZED, errorMessage, thrownBy, theURI); + + } + + + /** + * Throw forbidden exception. + * + * @param httpRequest the http request + * @param errorMessage the error message + * @param thrownBy the thrown by + * @param helpURI the help uri + */ + public static void throwForbiddenException(HttpServletRequest httpRequest, String errorMessage, Class thrownBy, String helpURI){ + + URI theURI = checkURI(helpURI); + throw new WrongParameterException(httpRequest, Status.FORBIDDEN, errorMessage, thrownBy, theURI); + + } + + + /** * Check uri. * diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/BadParameterException.java b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/BadParameterException.java index 95ae6ae..736579d 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/BadParameterException.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/BadParameterException.java @@ -26,11 +26,11 @@ import org.gcube.datatransfer.resolver.services.error.ExceptionReport; */ public class BadParameterException extends WebApplicationException { - /** + + /** * */ - private static final long serialVersionUID = -7600028435121268528L; - + private static final long serialVersionUID = 6838352737725193114L; /** * Instantiates a new bad parameter exception. diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/BadRequestException.java b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/BadRequestException.java index 3692c98..87b6190 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/BadRequestException.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/BadRequestException.java @@ -25,11 +25,12 @@ import org.gcube.datatransfer.resolver.services.error.ExceptionReport; */ public class BadRequestException extends WebApplicationException { - /** + + + /** * */ - private static final long serialVersionUID = -7600028435121268528L; - + private static final long serialVersionUID = -6095255435634429757L; /** * Instantiates a new bad parameter exception. diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/ForbiddenRequestException.java b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/ForbiddenRequestException.java new file mode 100644 index 0000000..818a71a --- /dev/null +++ b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/ForbiddenRequestException.java @@ -0,0 +1,65 @@ +/** + * + */ +package org.gcube.datatransfer.resolver.services.exceptions; + + +import java.net.URI; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; +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; +; + + +/** + * The Class ForbiddenRequestException. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Oct 23, 2018 + */ +public class ForbiddenRequestException extends WebApplicationException { + + + + + /** + * + */ + private static final long serialVersionUID = -7693811244686509390L; + + /** + * Instantiates a new forbidden request exception. + * + * @param request the request + * @param httpReturnStatus the http return status + * @param message the message + * @param thrownBySource the thrown by source + * @param help the help + */ + public ForbiddenRequestException(HttpServletRequest request, Status httpReturnStatus, String message, Class thrownBySource, URI help) { + + super(Response.status(httpReturnStatus).entity( + ExceptionReport.builder(). + request(Util.getFullURL(request)). + method(request.getMethod()). + success(false). + help(help). + error( + ErrorReport.builder(). + httpErrorCode(Status.FORBIDDEN.getStatusCode()). + name(Status.FORBIDDEN.name()) + .message(message). + thrownBy(thrownBySource.getName()).build()) + .build()) + .type(MediaType.APPLICATION_XML).build()); + + } + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/NotAuthorizedRequestException.java b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/NotAuthorizedRequestException.java new file mode 100644 index 0000000..95f6b4c --- /dev/null +++ b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/NotAuthorizedRequestException.java @@ -0,0 +1,63 @@ +/** + * + */ +package org.gcube.datatransfer.resolver.services.exceptions; + + +import java.net.URI; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; +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; +; + +/** + * The Class NotAuthorizedRequestException. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Oct 23, 2018 + */ +public class NotAuthorizedRequestException extends WebApplicationException { + + + + /** + * + */ + private static final long serialVersionUID = 7305531473428888453L; + + /** + * Instantiates a new not authorized request exception. + * + * @param request the request + * @param httpReturnStatus the http return status + * @param message the message + * @param thrownBySource the thrown by source + * @param help the help + */ + public NotAuthorizedRequestException(HttpServletRequest request, Status httpReturnStatus, String message, Class thrownBySource, URI help) { + + super(Response.status(httpReturnStatus).entity( + ExceptionReport.builder(). + request(Util.getFullURL(request)). + method(request.getMethod()). + success(false). + help(help). + error( + ErrorReport.builder(). + httpErrorCode(Status.UNAUTHORIZED.getStatusCode()). + name(Status.UNAUTHORIZED.name()) + .message(message). + thrownBy(thrownBySource.getName()).build()) + .build()) + .type(MediaType.APPLICATION_XML).build()); + + } + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/WrongParameterException.java b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/WrongParameterException.java index a987c26..7b12e47 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/WrongParameterException.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/exceptions/WrongParameterException.java @@ -26,11 +26,11 @@ import org.gcube.datatransfer.resolver.services.error.ExceptionReport; */ public class WrongParameterException extends WebApplicationException { - /** + + /** * */ - private static final long serialVersionUID = -7600028435121268528L; - + private static final long serialVersionUID = 6528328881336941898L; /** * Instantiates a new wrong parameter exception.