Merge remote-tracking branch 'dspace/master' into w2p-65257_Collection-item-template-crud

This commit is contained in:
Peter Nijs
2019-11-26 10:14:52 +01:00
214 changed files with 3127 additions and 2105 deletions

View File

@@ -13,6 +13,12 @@ import java.lang.reflect.Method;
import java.util.List; import java.util.List;
import java.util.TreeMap; import java.util.TreeMap;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import org.dspace.scripts.DSpaceRunnable;
import org.dspace.scripts.factory.ScriptServiceFactory;
import org.dspace.scripts.handler.DSpaceRunnableHandler;
import org.dspace.scripts.handler.impl.CommandLineDSpaceRunnableHandler;
import org.dspace.servicemanager.DSpaceKernelImpl; import org.dspace.servicemanager.DSpaceKernelImpl;
import org.dspace.servicemanager.DSpaceKernelInit; import org.dspace.servicemanager.DSpaceKernelInit;
import org.dspace.services.RequestService; import org.dspace.services.RequestService;
@@ -27,6 +33,9 @@ import org.jdom.input.SAXBuilder;
* @author Mark Diggory * @author Mark Diggory
*/ */
public class ScriptLauncher { public class ScriptLauncher {
private static final Logger log = Logger.getLogger(ScriptLauncher.class);
/** /**
* The service manager kernel * The service manager kernel
*/ */
@@ -76,8 +85,9 @@ public class ScriptLauncher {
} }
// Look up command in the configuration, and execute. // Look up command in the configuration, and execute.
int status;
status = runOneCommand(commandConfigs, args); CommandLineDSpaceRunnableHandler commandLineDSpaceRunnableHandler = new CommandLineDSpaceRunnableHandler();
int status = handleScript(args, commandConfigs, commandLineDSpaceRunnableHandler, kernelImpl);
// Destroy the service kernel if it is still alive // Destroy the service kernel if it is still alive
if (kernelImpl != null) { if (kernelImpl != null) {
@@ -86,6 +96,50 @@ public class ScriptLauncher {
} }
System.exit(status); System.exit(status);
}
/**
* This method will take the arguments from a commandline input and it'll find the script that the first argument
* refers to and it'll execute this script.
* It can return a 1 or a 0 depending on whether the script failed or passed respectively
* @param args The arguments for the script and the script as first one in the array
* @param commandConfigs The Document
* @param dSpaceRunnableHandler The DSpaceRunnableHandler for this execution
* @param kernelImpl The relevant DSpaceKernelImpl
* @return A 1 or 0 depending on whether the script failed or passed respectively
*/
public static int handleScript(String[] args, Document commandConfigs,
DSpaceRunnableHandler dSpaceRunnableHandler,
DSpaceKernelImpl kernelImpl) {
int status;
DSpaceRunnable script = ScriptServiceFactory.getInstance().getScriptService().getScriptForName(args[0]);
if (script != null) {
status = executeScript(args, dSpaceRunnableHandler, script);
} else {
status = runOneCommand(commandConfigs, args, kernelImpl);
}
return status;
}
/**
* This method will simply execute the script
* @param args The arguments of the script with the script name as first place in the array
* @param dSpaceRunnableHandler The relevant DSpaceRunnableHandler
* @param script The script to be executed
* @return A 1 or 0 depending on whether the script failed or passed respectively
*/
private static int executeScript(String[] args, DSpaceRunnableHandler dSpaceRunnableHandler,
DSpaceRunnable script) {
try {
script.initialize(args, dSpaceRunnableHandler);
script.run();
return 0;
} catch (ParseException e) {
script.printHelp();
e.printStackTrace();
return 1;
}
} }
protected static int runOneCommand(Document commandConfigs, String[] args) { protected static int runOneCommand(Document commandConfigs, String[] args) {
@@ -98,7 +152,7 @@ public class ScriptLauncher {
* @param commandConfigs Document * @param commandConfigs Document
* @param args the command line arguments given * @param args the command line arguments given
*/ */
public static int runOneCommand(Document commandConfigs, String[] args, DSpaceKernelImpl kernelImpl) { protected static int runOneCommand(Document commandConfigs, String[] args, DSpaceKernelImpl kernelImpl) {
String request = args[0]; String request = args[0];
Element root = commandConfigs.getRootElement(); Element root = commandConfigs.getRootElement();
List<Element> commands = root.getChildren("command"); List<Element> commands = root.getChildren("command");

View File

@@ -1,34 +0,0 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.content.factory;
import org.dspace.scripts.service.ProcessService;
import org.dspace.services.factory.DSpaceServicesFactory;
/**
* Abstract factory to get services for the Process workload, use ProcessServiceFactory.getInstance() to retrieve an
* implementation
*
*/
public abstract class ProcessServiceFactory {
/**
* This method will return an instance of the ProcessService
* @return An instance of the ProcessService
*/
public abstract ProcessService getProcessService();
/**
* Use this method to retrieve an implementation of the ProcessServiceFactory to use to retrieve the different beans
* @return An implementation of the ProcessServiceFactory
*/
public static ProcessServiceFactory getInstance() {
return DSpaceServicesFactory.getInstance().getServiceManager()
.getServiceByName("processServiceFactory", ProcessServiceFactory.class);
}
}

View File

@@ -0,0 +1,39 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.scripts;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.dspace.core.Context;
import org.dspace.scripts.service.ScriptService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* The implementation for the {@link ScriptService}
*/
public class ScriptServiceImpl implements ScriptService {
@Autowired
private List<DSpaceRunnable> dSpaceRunnables;
@Override
public DSpaceRunnable getScriptForName(String name) {
return dSpaceRunnables.stream()
.filter(dSpaceRunnable -> StringUtils.equalsIgnoreCase(dSpaceRunnable.getName(), name))
.findFirst()
.orElse(null);
}
@Override
public List<DSpaceRunnable> getDSpaceRunnables(Context context) {
return dSpaceRunnables.stream().filter(
dSpaceRunnable -> dSpaceRunnable.isAllowedToExecute(context)).collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,41 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.scripts.factory;
import org.dspace.scripts.service.ProcessService;
import org.dspace.scripts.service.ScriptService;
import org.dspace.services.factory.DSpaceServicesFactory;
/**
* Abstract factory to get services for the Script workload, use ScriptServiceFactory.getInstance() to retrieve an
* implementation
*
*/
public abstract class ScriptServiceFactory {
/**
* This method will return an instance of the ScriptService
* @return An instance of the ScriptService
*/
public abstract ScriptService getScriptService();
/**
* This method will return an instance of the ProcessService
* @return An instance of the ProcessService
*/
public abstract ProcessService getProcessService();
/**
* Use this method to retrieve an implementation of the ScriptServiceFactory to use to retrieve the different beans
* @return An implementation of the ScriptServiceFactory
*/
public static ScriptServiceFactory getInstance() {
return DSpaceServicesFactory.getInstance().getServiceManager()
.getServiceByName("scriptServiceFactory", ScriptServiceFactory.class);
}
}

View File

@@ -5,20 +5,29 @@
* *
* http://www.dspace.org/license/ * http://www.dspace.org/license/
*/ */
package org.dspace.content.factory.impl; package org.dspace.scripts.factory.impl;
import org.dspace.content.factory.ProcessServiceFactory; import org.dspace.scripts.factory.ScriptServiceFactory;
import org.dspace.scripts.service.ProcessService; import org.dspace.scripts.service.ProcessService;
import org.dspace.scripts.service.ScriptService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
/** /**
* The implementation for the {@link ProcessServiceFactory} * The implementation for the {@link ScriptServiceFactory}
*/ */
public class ProcessServiceFactoryImpl extends ProcessServiceFactory { public class ScriptServiceFactoryImpl extends ScriptServiceFactory {
@Autowired(required = true)
private ScriptService scriptService;
@Autowired(required = true) @Autowired(required = true)
private ProcessService processService; private ProcessService processService;
@Override
public ScriptService getScriptService() {
return scriptService;
}
@Override @Override
public ProcessService getProcessService() { public ProcessService getProcessService() {
return processService; return processService;

View File

@@ -0,0 +1,33 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.scripts.service;
import java.util.List;
import org.dspace.core.Context;
import org.dspace.scripts.DSpaceRunnable;
/**
* This service will deal with logic to handle DSpaceRunnable objects
*/
public interface ScriptService {
/**
* This method will return the DSpaceRunnable that has the name that's equal to the name given in the parameters
* @param name The name that the script has to match
* @return The matching DSpaceRunnable script
*/
DSpaceRunnable getScriptForName(String name);
/**
* This method will return a list of DSpaceRunnable objects for which the given Context is authorized to use them
* @param context The relevant DSpace context
* @return The list of accessible DSpaceRunnable scripts for this context
*/
List<DSpaceRunnable> getDSpaceRunnables(Context context);
}

View File

@@ -11,6 +11,7 @@ import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.converter.EPersonConverter; import org.dspace.app.rest.converter.EPersonConverter;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.AuthenticationStatusRest; import org.dspace.app.rest.model.AuthenticationStatusRest;
@@ -18,6 +19,7 @@ import org.dspace.app.rest.model.AuthnRest;
import org.dspace.app.rest.model.EPersonRest; import org.dspace.app.rest.model.EPersonRest;
import org.dspace.app.rest.model.hateoas.AuthenticationStatusResource; import org.dspace.app.rest.model.hateoas.AuthenticationStatusResource;
import org.dspace.app.rest.model.hateoas.AuthnResource; import org.dspace.app.rest.model.hateoas.AuthnResource;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils; import org.dspace.app.rest.utils.Utils;
import org.dspace.core.Context; import org.dspace.core.Context;
@@ -49,6 +51,9 @@ public class AuthenticationRestController implements InitializingBean {
@Autowired @Autowired
DiscoverableEndpointsService discoverableEndpointsService; DiscoverableEndpointsService discoverableEndpointsService;
@Autowired
private ConverterService converter;
@Autowired @Autowired
private EPersonConverter ePersonConverter; private EPersonConverter ePersonConverter;
@@ -65,24 +70,24 @@ public class AuthenticationRestController implements InitializingBean {
} }
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
public AuthnResource authn() throws SQLException { public AuthnResource authn() {
AuthnResource authnResource = new AuthnResource(new AuthnRest(), utils); AuthnRest authnRest = new AuthnRest();
halLinkService.addLinks(authnResource); authnRest.setProjection(utils.obtainProjection());
return authnResource; return converter.toResource(authnRest);
} }
@RequestMapping(value = "/status", method = RequestMethod.GET) @RequestMapping(value = "/status", method = RequestMethod.GET)
public AuthenticationStatusResource status(HttpServletRequest request) throws SQLException { public AuthenticationStatusResource status(HttpServletRequest request) throws SQLException {
Context context = ContextUtil.obtainContext(request); Context context = ContextUtil.obtainContext(request);
EPersonRest ePersonRest = null; EPersonRest ePersonRest = null;
Projection projection = utils.obtainProjection();
if (context.getCurrentUser() != null) { if (context.getCurrentUser() != null) {
ePersonRest = ePersonConverter.fromModelWithGroups(context, context.getCurrentUser()); ePersonRest = ePersonConverter.fromModelWithGroups(context, context.getCurrentUser(), projection);
} }
AuthenticationStatusResource authenticationStatusResource = new AuthenticationStatusResource( AuthenticationStatusRest authenticationStatusRest = new AuthenticationStatusRest(ePersonRest);
new AuthenticationStatusRest(ePersonRest), utils); authenticationStatusRest.setProjection(projection);
AuthenticationStatusResource authenticationStatusResource = converter.toResource(authenticationStatusRest);
halLinkService.addLinks(authenticationStatusResource);
return authenticationStatusResource; return authenticationStatusResource;
} }

View File

@@ -17,7 +17,7 @@ import java.util.UUID;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.dspace.app.rest.converter.DSpaceObjectConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.exception.UnprocessableEntityException; import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.BitstreamRest; import org.dspace.app.rest.model.BitstreamRest;
@@ -63,7 +63,7 @@ public class BitstreamBundleController {
private BitstreamService bitstreamService; private BitstreamService bitstreamService;
@Autowired @Autowired
DSpaceObjectConverter<Bundle, BundleRest> dsoConverter; ConverterService converter;
@Autowired @Autowired
HalLinkService halLinkService; HalLinkService halLinkService;
@@ -106,8 +106,8 @@ public class BitstreamBundleController {
return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT); return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT);
} }
BundleResource bundleResource = new BundleResource(dsoConverter.fromModel(bundles.get(0)), utils); BundleResource bundleResource = converter.toResource(
halLinkService.addLinks(bundleResource); converter.toRest(bundles.get(0), utils.obtainProjection()));
return ControllerUtils.toResponseEntity(HttpStatus.OK, null, bundleResource); return ControllerUtils.toResponseEntity(HttpStatus.OK, null, bundleResource);
} }
@@ -126,7 +126,7 @@ public class BitstreamBundleController {
@RequestMapping(method = RequestMethod.PUT, consumes = {"text/uri-list"}) @RequestMapping(method = RequestMethod.PUT, consumes = {"text/uri-list"})
@PreAuthorize("hasPermission(#uuid, 'BITSTREAM','WRITE')") @PreAuthorize("hasPermission(#uuid, 'BITSTREAM','WRITE')")
@PostAuthorize("returnObject != null") @PostAuthorize("returnObject != null")
public BundleResource move(@PathVariable UUID uuid, HttpServletResponse response, public BundleRest move(@PathVariable UUID uuid, HttpServletResponse response,
HttpServletRequest request) HttpServletRequest request)
throws SQLException, IOException, AuthorizeException { throws SQLException, IOException, AuthorizeException {
Context context = ContextUtil.obtainContext(request); Context context = ContextUtil.obtainContext(request);
@@ -143,17 +143,11 @@ public class BitstreamBundleController {
throw new ResourceNotFoundException("Bitstream with id: " + uuid + " not found"); throw new ResourceNotFoundException("Bitstream with id: " + uuid + " not found");
} }
Bundle targetBundle = bitstreamRestRepository.performBitstreamMove(context, bitstream, (Bundle) dsoList.get(0)); BundleRest bundleRest = bitstreamRestRepository.performBitstreamMove(context, bitstream,
(Bundle) dsoList.get(0));
if (targetBundle == null) {
return null;
}
BundleResource bundleResource = new BundleResource(dsoConverter.fromModel(targetBundle), utils);
halLinkService.addLinks(bundleResource);
context.commit(); context.commit();
return bundleResource; return bundleRest;
} }
} }

View File

@@ -23,21 +23,17 @@ import javax.ws.rs.core.Response;
import org.apache.catalina.connector.ClientAbortException; import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.converter.BitstreamConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.converter.DSpaceObjectConverter;
import org.dspace.app.rest.exception.DSpaceBadRequestException; import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.BitstreamRest; import org.dspace.app.rest.model.BitstreamRest;
import org.dspace.app.rest.model.BundleRest;
import org.dspace.app.rest.model.hateoas.BitstreamResource; import org.dspace.app.rest.model.hateoas.BitstreamResource;
import org.dspace.app.rest.repository.BitstreamRestRepository; import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.MultipartFileSender; import org.dspace.app.rest.utils.MultipartFileSender;
import org.dspace.app.rest.utils.Utils; import org.dspace.app.rest.utils.Utils;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat; import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.core.Context; import org.dspace.core.Context;
@@ -86,12 +82,6 @@ public class BitstreamRestController {
@Autowired @Autowired
BitstreamFormatService bitstreamFormatService; BitstreamFormatService bitstreamFormatService;
@Autowired
BitstreamRestRepository bitstreamRestRepository;
@Autowired
DSpaceObjectConverter<Bundle, BundleRest> dsoConverter;
@Autowired @Autowired
private EventService eventService; private EventService eventService;
@@ -102,14 +92,11 @@ public class BitstreamRestController {
private ConfigurationService configurationService; private ConfigurationService configurationService;
@Autowired @Autowired
BitstreamConverter converter; ConverterService converter;
@Autowired @Autowired
Utils utils; Utils utils;
@Autowired
HalLinkService halLinkService;
@PreAuthorize("hasPermission(#uuid, 'BITSTREAM', 'READ')") @PreAuthorize("hasPermission(#uuid, 'BITSTREAM', 'READ')")
@RequestMapping( method = {RequestMethod.GET, RequestMethod.HEAD}, value = "content") @RequestMapping( method = {RequestMethod.GET, RequestMethod.HEAD}, value = "content")
public void retrieve(@PathVariable UUID uuid, HttpServletResponse response, public void retrieve(@PathVariable UUID uuid, HttpServletResponse response,
@@ -253,7 +240,7 @@ public class BitstreamRestController {
context.commit(); context.commit();
return (BitstreamResource) utils.getResourceRepository(BitstreamRest.CATEGORY, BitstreamRest.NAME) BitstreamRest bitstreamRest = converter.toRest(context.reloadEntity(bitstream), Projection.DEFAULT);
.wrapResource(converter.fromModel(context.reloadEntity(bitstream))); return converter.toResource(bitstreamRest);
} }
} }

View File

@@ -17,7 +17,7 @@ import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.converter.BitstreamConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.exception.UnprocessableEntityException; import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.model.BitstreamRest; import org.dspace.app.rest.model.BitstreamRest;
import org.dspace.app.rest.model.BundleRest; import org.dspace.app.rest.model.BundleRest;
@@ -25,7 +25,6 @@ import org.dspace.app.rest.model.hateoas.BitstreamResource;
import org.dspace.app.rest.repository.BundleRestRepository; import org.dspace.app.rest.repository.BundleRestRepository;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils; import org.dspace.app.rest.utils.Utils;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle; import org.dspace.content.Bundle;
import org.dspace.content.service.BundleService; import org.dspace.content.service.BundleService;
import org.dspace.core.Context; import org.dspace.core.Context;
@@ -72,10 +71,10 @@ public class BundleUploadBitstreamController {
private BundleService bundleService; private BundleService bundleService;
@Autowired @Autowired
private BitstreamConverter bitstreamConverter; private BundleRestRepository bundleRestRepository;
@Autowired @Autowired
private BundleRestRepository bundleRestRepository; private ConverterService converter;
/** /**
* Method to upload a Bitstream to a Bundle with the given UUID in the URL. This will create a Bitstream with the * Method to upload a Bitstream to a Bundle with the given UUID in the URL. This will create a Bitstream with the
@@ -92,7 +91,6 @@ public class BundleUploadBitstreamController {
Context context = ContextUtil.obtainContext(request); Context context = ContextUtil.obtainContext(request);
Bundle bundle = null; Bundle bundle = null;
Bitstream bitstream = null;
try { try {
bundle = bundleService.find(context, uuid); bundle = bundleService.find(context, uuid);
} catch (SQLException e) { } catch (SQLException e) {
@@ -110,10 +108,10 @@ public class BundleUploadBitstreamController {
throw new UnprocessableEntityException("The InputStream from the file couldn't be read", e); throw new UnprocessableEntityException("The InputStream from the file couldn't be read", e);
} }
bitstream = bundleRestRepository.uploadBitstream(context, bundle, uploadfile.getOriginalFilename(), BitstreamRest bitstreamRest = bundleRestRepository.uploadBitstream(
fileInputStream, properties); context, bundle, uploadfile.getOriginalFilename(), fileInputStream, properties);
BitstreamResource bitstreamResource = converter.toResource(bitstreamRest);
BitstreamResource bitstreamResource = new BitstreamResource(bitstreamConverter.fromModel(bitstream), utils);
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, bitstreamResource); return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, bitstreamResource);
} }
} }

View File

@@ -12,6 +12,7 @@ import java.util.UUID;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.converter.HarvestedCollectionConverter; import org.dspace.app.rest.converter.HarvestedCollectionConverter;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.HarvestedCollectionRest; import org.dspace.app.rest.model.HarvestedCollectionRest;
@@ -48,6 +49,9 @@ public class CollectionHarvestSettingsController {
@Autowired @Autowired
CollectionService collectionService; CollectionService collectionService;
@Autowired
ConverterService converter;
@Autowired @Autowired
HarvestedCollectionService harvestedCollectionService; HarvestedCollectionService harvestedCollectionService;
@@ -80,9 +84,7 @@ public class CollectionHarvestSettingsController {
} }
HarvestedCollectionRest harvestedCollectionRest = harvestedCollectionRestRepository.findOne(collection); HarvestedCollectionRest harvestedCollectionRest = harvestedCollectionRestRepository.findOne(collection);
HarvestedCollectionResource resource = new HarvestedCollectionResource(harvestedCollectionRest); HarvestedCollectionResource resource = converter.toResource(harvestedCollectionRest);
halLinkService.addLinks(resource);
return resource; return resource;
} }
@@ -114,8 +116,7 @@ public class CollectionHarvestSettingsController {
// Return a harvestedCollectionResource only if a new harvestedCollection was created // Return a harvestedCollectionResource only if a new harvestedCollection was created
if (harvestedCollectionRest != null) { if (harvestedCollectionRest != null) {
harvestedCollectionResource = new HarvestedCollectionResource(harvestedCollectionRest); harvestedCollectionResource = converter.toResource(harvestedCollectionRest);
halLinkService.addLinks(harvestedCollectionResource);
} }
context.commit(); context.commit();

View File

@@ -14,6 +14,7 @@ import java.util.Objects;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.FacetConfigurationRest; import org.dspace.app.rest.model.FacetConfigurationRest;
import org.dspace.app.rest.model.FacetResultsRest; import org.dspace.app.rest.model.FacetResultsRest;
@@ -61,6 +62,9 @@ public class DiscoveryRestController implements InitializingBean {
@Autowired @Autowired
private HalLinkService halLinkService; private HalLinkService halLinkService;
@Autowired
private ConverterService converter;
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
discoverableEndpointsService discoverableEndpointsService
@@ -74,8 +78,7 @@ public class DiscoveryRestController implements InitializingBean {
throws Exception { throws Exception {
SearchSupportRest searchSupportRest = discoveryRestRepository.getSearchSupport(); SearchSupportRest searchSupportRest = discoveryRestRepository.getSearchSupport();
SearchSupportResource searchSupportResource = new SearchSupportResource(searchSupportRest); SearchSupportResource searchSupportResource = converter.toResource(searchSupportRest);
halLinkService.addLinks(searchSupportResource);
return searchSupportResource; return searchSupportResource;
} }
@@ -91,9 +94,7 @@ public class DiscoveryRestController implements InitializingBean {
SearchConfigurationRest searchConfigurationRest = discoveryRestRepository SearchConfigurationRest searchConfigurationRest = discoveryRestRepository
.getSearchConfiguration(dsoScope, configuration); .getSearchConfiguration(dsoScope, configuration);
SearchConfigurationResource searchConfigurationResource = new SearchConfigurationResource( SearchConfigurationResource searchConfigurationResource = converter.toResource(searchConfigurationRest);
searchConfigurationRest);
halLinkService.addLinks(searchConfigurationResource);
return searchConfigurationResource; return searchConfigurationResource;
} }
@@ -142,9 +143,8 @@ public class DiscoveryRestController implements InitializingBean {
} }
//Get the Search results in JSON format //Get the Search results in JSON format
SearchResultsRest searchResultsRest = null; SearchResultsRest searchResultsRest = discoveryRestRepository
searchResultsRest = discoveryRestRepository .getSearchObjects(query, dsoType, dsoScope, configuration, searchFilters, page, utils.obtainProjection());
.getSearchObjects(query, dsoType, dsoScope, configuration, searchFilters, page);
//Convert the Search JSON results to paginated HAL resources //Convert the Search JSON results to paginated HAL resources
SearchResultsResource searchResultsResource = new SearchResultsResource(searchResultsRest, utils, page); SearchResultsResource searchResultsResource = new SearchResultsResource(searchResultsRest, utils, page);
@@ -164,7 +164,7 @@ public class DiscoveryRestController implements InitializingBean {
FacetConfigurationRest facetConfigurationRest = discoveryRestRepository FacetConfigurationRest facetConfigurationRest = discoveryRestRepository
.getFacetsConfiguration(dsoScope, configuration); .getFacetsConfiguration(dsoScope, configuration);
FacetConfigurationResource facetConfigurationResource = new FacetConfigurationResource(facetConfigurationRest); FacetConfigurationResource facetConfigurationResource = converter.toResource(facetConfigurationRest);
halLinkService.addLinks(facetConfigurationResource, pageable); halLinkService.addLinks(facetConfigurationResource, pageable);
return facetConfigurationResource; return facetConfigurationResource;
@@ -192,7 +192,7 @@ public class DiscoveryRestController implements InitializingBean {
FacetResultsRest facetResultsRest = discoveryRestRepository FacetResultsRest facetResultsRest = discoveryRestRepository
.getFacetObjects(facetName, prefix, query, dsoType, dsoScope, configuration, searchFilters, page); .getFacetObjects(facetName, prefix, query, dsoType, dsoScope, configuration, searchFilters, page);
FacetResultsResource facetResultsResource = new FacetResultsResource(facetResultsRest); FacetResultsResource facetResultsResource = converter.toResource(facetResultsRest);
halLinkService.addLinks(facetResultsResource, page); halLinkService.addLinks(facetResultsResource, page);
return facetResultsResource; return facetResultsResource;

View File

@@ -12,12 +12,12 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.HarvesterMetadataRest; import org.dspace.app.rest.model.HarvesterMetadataRest;
import org.dspace.app.rest.model.hateoas.HarvesterMetadataResource; import org.dspace.app.rest.model.hateoas.HarvesterMetadataResource;
import org.dspace.app.rest.utils.Utils; import org.dspace.app.rest.utils.Utils;
import org.dspace.harvest.OAIHarvester; import org.dspace.harvest.OAIHarvester;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
@@ -38,6 +38,9 @@ public class HarvesterMetadataController {
@Autowired @Autowired
private HalLinkService halLinkService; private HalLinkService halLinkService;
@Autowired
private ConverterService converter;
/** /**
* GET endpoint that returns all available metadata formats * GET endpoint that returns all available metadata formats
* @param request The request object * @param request The request object
@@ -46,15 +49,14 @@ public class HarvesterMetadataController {
*/ */
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
public HarvesterMetadataResource get(HttpServletRequest request, public HarvesterMetadataResource get(HttpServletRequest request,
HttpServletResponse response) { HttpServletResponse response) {
List<Map<String,String>> configs = OAIHarvester.getAvailableMetadataFormats(); List<Map<String,String>> configs = OAIHarvester.getAvailableMetadataFormats();
HarvesterMetadataRest data = new HarvesterMetadataRest(); HarvesterMetadataRest data = new HarvesterMetadataRest();
data.setProjection(utils.obtainProjection());
data.setConfigs(configs); data.setConfigs(configs);
HarvesterMetadataResource resource = new HarvesterMetadataResource(data, utils); HarvesterMetadataResource resource = converter.toResource(data);
halLinkService.addLinks(resource);
return resource; return resource;
} }

View File

@@ -13,15 +13,15 @@ import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.atteo.evo.inflector.English; import org.atteo.evo.inflector.English;
import org.dspace.app.rest.converter.GenericDSpaceObjectConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.model.DSpaceObjectRest; import org.dspace.app.rest.model.DSpaceObjectRest;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.identifier.IdentifierNotFoundException; import org.dspace.identifier.IdentifierNotFoundException;
@@ -53,7 +53,10 @@ public class IdentifierRestController implements InitializingBean {
Logger.getLogger(IdentifierRestController.class); Logger.getLogger(IdentifierRestController.class);
@Autowired @Autowired
private GenericDSpaceObjectConverter converter; private ConverterService converter;
@Autowired
private Utils utils;
@Autowired @Autowired
private DiscoverableEndpointsService discoverableEndpointsService; private DiscoverableEndpointsService discoverableEndpointsService;
@@ -84,7 +87,7 @@ public class IdentifierRestController implements InitializingBean {
try { try {
dso = identifierService.resolve(context, id); dso = identifierService.resolve(context, id);
if (dso != null) { if (dso != null) {
DSpaceObjectRest dsor = converter.convert(dso); DSpaceObjectRest dsor = converter.toRest(dso, utils.obtainProjection());
URI link = linkTo(dsor.getController(), dsor.getCategory(), URI link = linkTo(dsor.getController(), dsor.getCategory(),
English.plural(dsor.getType())) English.plural(dsor.getType()))
.slash(dsor.getId()).toUri(); .slash(dsor.getId()).toUri();

View File

@@ -16,12 +16,13 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.dspace.app.rest.converter.BundleConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.converter.MetadataConverter; import org.dspace.app.rest.converter.MetadataConverter;
import org.dspace.app.rest.exception.UnprocessableEntityException; import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.model.BundleRest; import org.dspace.app.rest.model.BundleRest;
import org.dspace.app.rest.model.ItemRest; import org.dspace.app.rest.model.ItemRest;
import org.dspace.app.rest.model.hateoas.BundleResource; import org.dspace.app.rest.model.hateoas.BundleResource;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.repository.ItemRestRepository; import org.dspace.app.rest.repository.ItemRestRepository;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils; import org.dspace.app.rest.utils.Utils;
@@ -63,19 +64,18 @@ import org.springframework.web.bind.annotation.RestController;
+ "/" + BundleRest.PLURAL_NAME) + "/" + BundleRest.PLURAL_NAME)
public class ItemAddBundleController { public class ItemAddBundleController {
@Autowired
ConverterService converter;
@Autowired @Autowired
ItemService itemService; ItemService itemService;
@Autowired @Autowired
ItemRestRepository itemRestRepository; ItemRestRepository itemRestRepository;
@Autowired
BundleConverter converter;
@Autowired @Autowired
MetadataConverter metadataConverter; MetadataConverter metadataConverter;
@Autowired @Autowired
Utils utils; Utils utils;
@@ -107,10 +107,8 @@ public class ItemAddBundleController {
} }
Bundle bundle = itemRestRepository.addBundleToItem(context, item, bundleRest); Bundle bundle = itemRestRepository.addBundleToItem(context, item, bundleRest);
BundleResource bundleResource = converter.toResource(converter.toRest(bundle, Projection.DEFAULT));
BundleResource bundleResource = new BundleResource(converter.convert(bundle), utils);
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, bundleResource); return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, bundleResource);
} }
} }

View File

@@ -17,10 +17,11 @@ import java.util.UUID;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.dspace.app.rest.converter.CollectionConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.exception.DSpaceBadRequestException; import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.exception.UnprocessableEntityException; import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.model.CollectionRest; import org.dspace.app.rest.model.CollectionRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils; import org.dspace.app.rest.utils.Utils;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
@@ -59,7 +60,7 @@ public class ItemOwningCollectionUpdateRestController {
AuthorizeService authorizeService; AuthorizeService authorizeService;
@Autowired @Autowired
CollectionConverter converter; ConverterService converter;
@Autowired @Autowired
Utils utils; Utils utils;
@@ -96,7 +97,7 @@ public class ItemOwningCollectionUpdateRestController {
if (targetCollection == null) { if (targetCollection == null) {
return null; return null;
} }
return converter.fromModel(targetCollection); return converter.toRest(targetCollection, Projection.DEFAULT);
} }

View File

@@ -19,7 +19,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.app.rest.converter.CollectionConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.exception.MethodNotAllowedException; import org.dspace.app.rest.exception.MethodNotAllowedException;
import org.dspace.app.rest.exception.UnprocessableEntityException; import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
@@ -56,7 +56,7 @@ public class MappedCollectionRestController {
private ItemService itemService; private ItemService itemService;
@Autowired @Autowired
private CollectionConverter collectionConverter; private ConverterService converter;
@Autowired @Autowired
private CollectionService collectionService; private CollectionService collectionService;
@@ -99,18 +99,16 @@ public class MappedCollectionRestController {
List<CollectionRest> mappingCollectionRest = new LinkedList<>(); List<CollectionRest> mappingCollectionRest = new LinkedList<>();
for (Collection collection : collections) { for (Collection collection : collections) {
if (collection.getID() != owningCollectionUuid) { if (collection.getID() != owningCollectionUuid) {
mappingCollectionRest.add(collectionConverter.fromModel(collection)); mappingCollectionRest.add(converter.toRest(collection, utils.obtainProjection()));
} }
} }
MappedCollectionRestWrapper mappingCollectionRestWrapper = new MappedCollectionRestWrapper(); MappedCollectionRestWrapper mappingCollectionRestWrapper = new MappedCollectionRestWrapper();
mappingCollectionRestWrapper.setProjection(utils.obtainProjection());
mappingCollectionRestWrapper.setMappedCollectionRestList(mappingCollectionRest); mappingCollectionRestWrapper.setMappedCollectionRestList(mappingCollectionRest);
mappingCollectionRestWrapper.setItem(item); mappingCollectionRestWrapper.setItem(item);
MappedCollectionResourceWrapper mappingCollectionResourceWrapper = new MappedCollectionResourceWrapper( MappedCollectionResourceWrapper mappingCollectionResourceWrapper =
mappingCollectionRestWrapper, utils, pageable); converter.toResource(mappingCollectionRestWrapper);
halLinkService.addLinks(mappingCollectionResourceWrapper);
return mappingCollectionResourceWrapper; return mappingCollectionResourceWrapper;

View File

@@ -17,7 +17,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.app.rest.converter.ItemConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.ItemRest; import org.dspace.app.rest.model.ItemRest;
import org.dspace.app.rest.model.MappedItemRestWrapper; import org.dspace.app.rest.model.MappedItemRestWrapper;
@@ -54,7 +54,7 @@ public class MappedItemRestController {
private ItemService itemService; private ItemService itemService;
@Autowired @Autowired
private ItemConverter itemConverter; private ConverterService converter;
@Autowired @Autowired
Utils utils; Utils utils;
@@ -96,11 +96,12 @@ public class MappedItemRestController {
while (itemIterator.hasNext()) { while (itemIterator.hasNext()) {
Item item = itemIterator.next(); Item item = itemIterator.next();
if (item.getOwningCollection().getID() != uuid) { if (item.getOwningCollection().getID() != uuid) {
mappedItemRestList.add(itemConverter.fromModel(item)); mappedItemRestList.add(converter.toRest(item, utils.obtainProjection()));
} }
} }
MappedItemRestWrapper mappedItemRestWrapper = new MappedItemRestWrapper(); MappedItemRestWrapper mappedItemRestWrapper = new MappedItemRestWrapper();
mappedItemRestWrapper.setProjection(utils.obtainProjection());
mappedItemRestWrapper.setMappedItemRestList(mappedItemRestList); mappedItemRestWrapper.setMappedItemRestList(mappedItemRestList);
mappedItemRestWrapper.setCollectionUuid(uuid); mappedItemRestWrapper.setCollectionUuid(uuid);
MappedItemResourceWrapper mappedItemResourceWrapper = MappedItemResourceWrapper mappedItemResourceWrapper =

View File

@@ -13,11 +13,12 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.dspace.app.rest.converter.RelationshipTypeConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.RelationshipTypeRest; import org.dspace.app.rest.model.RelationshipTypeRest;
import org.dspace.app.rest.model.RelationshipTypeRestWrapper; import org.dspace.app.rest.model.RelationshipTypeRestWrapper;
import org.dspace.app.rest.model.hateoas.RelationshipTypeResourceWrapper; import org.dspace.app.rest.model.hateoas.RelationshipTypeResourceWrapper;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils; import org.dspace.app.rest.utils.Utils;
import org.dspace.content.EntityType; import org.dspace.content.EntityType;
@@ -48,7 +49,7 @@ public class RelationshipTypeRestController {
private EntityTypeService entityTypeService; private EntityTypeService entityTypeService;
@Autowired @Autowired
private RelationshipTypeConverter relationshipTypeConverter; private ConverterService converter;
@Autowired @Autowired
private Utils utils; private Utils utils;
@@ -67,7 +68,8 @@ public class RelationshipTypeRestController {
* @throws SQLException If something goes wrong * @throws SQLException If something goes wrong
*/ */
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
public RelationshipTypeResourceWrapper retrieve(@PathVariable Integer id, HttpServletResponse response, public RelationshipTypeResourceWrapper retrieve(@PathVariable Integer id,
HttpServletResponse response,
HttpServletRequest request) throws SQLException { HttpServletRequest request) throws SQLException {
Context context = ContextUtil.obtainContext(request); Context context = ContextUtil.obtainContext(request);
EntityType entityType = entityTypeService.find(context, id); EntityType entityType = entityTypeService.find(context, id);
@@ -75,19 +77,19 @@ public class RelationshipTypeRestController {
List<RelationshipTypeRest> relationshipTypeRests = new LinkedList<>(); List<RelationshipTypeRest> relationshipTypeRests = new LinkedList<>();
Projection projection = utils.obtainProjection();
for (RelationshipType relationshipType : list) { for (RelationshipType relationshipType : list) {
relationshipTypeRests.add(relationshipTypeConverter.fromModel(relationshipType)); relationshipTypeRests.add(converter.toRest(relationshipType, projection));
} }
RelationshipTypeRestWrapper relationshipTypeRestWrapper = new RelationshipTypeRestWrapper(); RelationshipTypeRestWrapper relationshipTypeRestWrapper = new RelationshipTypeRestWrapper();
relationshipTypeRestWrapper.setProjection(projection);
relationshipTypeRestWrapper.setEntityTypeId(id); relationshipTypeRestWrapper.setEntityTypeId(id);
relationshipTypeRestWrapper.setEntityTypeLabel(entityType.getLabel()); relationshipTypeRestWrapper.setEntityTypeLabel(entityType.getLabel());
relationshipTypeRestWrapper.setRelationshipTypeRestList(relationshipTypeRests); relationshipTypeRestWrapper.setRelationshipTypeRestList(relationshipTypeRests);
RelationshipTypeResourceWrapper relationshipTypeResourceWrapper = new RelationshipTypeResourceWrapper( RelationshipTypeResourceWrapper relationshipTypeResourceWrapper =
relationshipTypeRestWrapper, utils); converter.toResource(relationshipTypeRestWrapper);
halLinkService.addLinks(relationshipTypeResourceWrapper);
return relationshipTypeResourceWrapper; return relationshipTypeResourceWrapper;
} }
} }

View File

@@ -22,17 +22,16 @@ import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.atteo.evo.inflector.English; import org.atteo.evo.inflector.English;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.converter.JsonPatchConverter; import org.dspace.app.rest.converter.JsonPatchConverter;
import org.dspace.app.rest.exception.DSpaceBadRequestException; import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.exception.PaginationException; import org.dspace.app.rest.exception.PaginationException;
@@ -67,7 +66,6 @@ import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.Link; import org.springframework.hateoas.Link;
import org.springframework.hateoas.PagedResources; import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.ResourceSupport;
import org.springframework.hateoas.Resources; import org.springframework.hateoas.Resources;
import org.springframework.hateoas.UriTemplate; import org.springframework.hateoas.UriTemplate;
@@ -115,6 +113,9 @@ public class RestResourceController implements InitializingBean {
@Autowired @Autowired
HalLinkService linkService; HalLinkService linkService;
@Autowired
ConverterService converter;
@Override @Override
public void afterPropertiesSet() { public void afterPropertiesSet() {
List<Link> links = new ArrayList<Link>(); List<Link> links = new ArrayList<Link>();
@@ -137,22 +138,20 @@ public class RestResourceController implements InitializingBean {
* *
* Note that the regular expression in the request mapping accept a number as identifier; * Note that the regular expression in the request mapping accept a number as identifier;
* *
* Please see {@link RestResourceController#findOne(String, String, String, String)} for findOne with string as * Please see {@link RestResourceController#findOne(String, String, String)} for findOne with string as
* identifier * identifier
* and see {@link RestResourceController#findOne(String, String, UUID, String)} for uuid as identifier * and see {@link RestResourceController#findOne(String, String, UUID)} for uuid as identifier
* *
* @param apiCategory * @param apiCategory
* @param model * @param model
* @param id * @param id
* @param projection
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_DIGIT) @RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_DIGIT)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public DSpaceResource<RestAddressableModel> findOne(@PathVariable String apiCategory, @PathVariable String model, public DSpaceResource<RestAddressableModel> findOne(@PathVariable String apiCategory, @PathVariable String model,
@PathVariable Integer id, @PathVariable Integer id) {
@RequestParam(required = false) String projection) { return findOneInternal(apiCategory, model, id);
return findOneInternal(apiCategory, model, id, projection);
} }
/** /**
@@ -171,22 +170,20 @@ public class RestResourceController implements InitializingBean {
* </pre> * </pre>
* *
* *
* Please see {@link RestResourceController#findOne(String, String, Integer, String)} for findOne with number as * Please see {@link RestResourceController#findOne(String, String, Integer)} for findOne with number as
* identifier * identifier
* and see {@link RestResourceController#findOne(String, String, UUID, String)} for uuid as identifier * and see {@link RestResourceController#findOne(String, String, UUID)} for uuid as identifier
* *
* @param apiCategory * @param apiCategory
* @param model * @param model
* @param id * @param id
* @param projection
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_STRING_VERSION_STRONG) @RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_STRING_VERSION_STRONG)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public DSpaceResource<RestAddressableModel> findOne(@PathVariable String apiCategory, @PathVariable String model, public DSpaceResource<RestAddressableModel> findOne(@PathVariable String apiCategory, @PathVariable String model,
@PathVariable String id, @PathVariable String id) {
@RequestParam(required = false) String projection) { return findOneInternal(apiCategory, model, id);
return findOneInternal(apiCategory, model, id, projection);
} }
/** /**
@@ -194,22 +191,20 @@ public class RestResourceController implements InitializingBean {
* *
* Note that the regular expression in the request mapping accept a UUID as identifier; * Note that the regular expression in the request mapping accept a UUID as identifier;
* *
* Please see {@link RestResourceController#findOne(String, String, Integer, String)} for findOne with number as * Please see {@link RestResourceController#findOne(String, String, Integer)} for findOne with number as
* identifier * identifier
* and see {@link RestResourceController#findOne(String, String, String, String)} for string as identifier * and see {@link RestResourceController#findOne(String, String, String)} for string as identifier
* *
* @param apiCategory * @param apiCategory
* @param model * @param model
* @param uuid * @param uuid
* @param projection
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_UUID) @RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_UUID)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public DSpaceResource<RestAddressableModel> findOne(@PathVariable String apiCategory, @PathVariable String model, public DSpaceResource<RestAddressableModel> findOne(@PathVariable String apiCategory, @PathVariable String model,
@PathVariable UUID uuid, @PathVariable UUID uuid) {
@RequestParam(required = false) String projection) { return findOneInternal(apiCategory, model, uuid);
return findOneInternal(apiCategory, model, uuid, projection);
} }
/** /**
@@ -218,13 +213,10 @@ public class RestResourceController implements InitializingBean {
* @param apiCategory * @param apiCategory
* @param model * @param model
* @param id * @param id
* @param projection
* @return * @return
*/ */
private <ID extends Serializable> DSpaceResource<RestAddressableModel> findOneInternal(String apiCategory, private <ID extends Serializable> DSpaceResource<RestAddressableModel> findOneInternal(String apiCategory,
String model, ID id, String model, ID id) {
String projection) {
checkModelPluralForm(apiCategory, model);
DSpaceRestRepository<RestAddressableModel, ID> repository = utils.getResourceRepository(apiCategory, model); DSpaceRestRepository<RestAddressableModel, ID> repository = utils.getResourceRepository(apiCategory, model);
RestAddressableModel modelObject = null; RestAddressableModel modelObject = null;
try { try {
@@ -235,9 +227,7 @@ public class RestResourceController implements InitializingBean {
if (modelObject == null) { if (modelObject == null) {
throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found"); throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found");
} }
DSpaceResource result = repository.wrapResource(modelObject); return converter.toResource(modelObject);
linkService.addLinks(result);
return result;
} }
/** /**
@@ -252,7 +242,6 @@ public class RestResourceController implements InitializingBean {
* @param rel * @param rel
* @param page * @param page
* @param assembler * @param assembler
* @param projection
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_DIGIT + "/{rel}") @RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_DIGIT + "/{rel}")
@@ -260,9 +249,8 @@ public class RestResourceController implements InitializingBean {
@PathVariable String apiCategory, @PathVariable String apiCategory,
@PathVariable String model, @PathVariable Integer id, @PathVariable String rel, @PathVariable String model, @PathVariable Integer id, @PathVariable String rel,
Pageable page, Pageable page,
PagedResourcesAssembler assembler, PagedResourcesAssembler assembler) {
@RequestParam(required = false) String projection) { return findRelInternal(request, response, apiCategory, model, id, rel, page, assembler);
return findRelInternal(request, response, apiCategory, model, id, rel, page, assembler, projection);
} }
/** /**
@@ -278,7 +266,6 @@ public class RestResourceController implements InitializingBean {
* @param rel * @param rel
* @param page * @param page
* @param assembler * @param assembler
* @param projection
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_STRING_VERSION_STRONG + @RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_STRING_VERSION_STRONG +
@@ -287,9 +274,8 @@ public class RestResourceController implements InitializingBean {
@PathVariable String apiCategory, @PathVariable String apiCategory,
@PathVariable String model, @PathVariable String id, @PathVariable String rel, @PathVariable String model, @PathVariable String id, @PathVariable String rel,
Pageable page, Pageable page,
PagedResourcesAssembler assembler, PagedResourcesAssembler assembler) {
@RequestParam(required = false) String projection) { return findRelInternal(request, response, apiCategory, model, id, rel, page, assembler);
return findRelInternal(request, response, apiCategory, model, id, rel, page, assembler, projection);
} }
/** /**
@@ -304,7 +290,6 @@ public class RestResourceController implements InitializingBean {
* @param rel * @param rel
* @param page * @param page
* @param assembler * @param assembler
* @param projection
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_UUID + "/{rel}") @RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_UUID + "/{rel}")
@@ -312,9 +297,8 @@ public class RestResourceController implements InitializingBean {
@PathVariable String apiCategory, @PathVariable String apiCategory,
@PathVariable String model, @PathVariable UUID uuid, @PathVariable String rel, @PathVariable String model, @PathVariable UUID uuid, @PathVariable String rel,
Pageable page, Pageable page,
PagedResourcesAssembler assembler, PagedResourcesAssembler assembler) {
@RequestParam(required = false) String projection) { return findRelInternal(request, response, apiCategory, model, uuid, rel, page, assembler);
return findRelInternal(request, response, apiCategory, model, uuid, rel, page, assembler, projection);
} }
/** /**
@@ -347,7 +331,6 @@ public class RestResourceController implements InitializingBean {
* @param relid * @param relid
* @param page * @param page
* @param assembler * @param assembler
* @param projection
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_STRING_VERSION_STRONG + @RequestMapping(method = RequestMethod.GET, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_STRING_VERSION_STRONG +
@@ -356,9 +339,8 @@ public class RestResourceController implements InitializingBean {
@PathVariable String apiCategory, @PathVariable String apiCategory,
@PathVariable String model, @PathVariable String id, @PathVariable String rel, @PathVariable String model, @PathVariable String id, @PathVariable String rel,
@PathVariable String relid, @PathVariable String relid,
Pageable page, PagedResourcesAssembler assembler, Pageable page, PagedResourcesAssembler assembler) throws Throwable {
@RequestParam(required = false) String projection) throws Throwable { return findRelEntryInternal(request, response, apiCategory, model, id, rel, relid, page, assembler);
return findRelEntryInternal(request, response, apiCategory, model, id, rel, relid, page, assembler, projection);
} }
@@ -443,8 +425,7 @@ public class RestResourceController implements InitializingBean {
if (modelObject == null) { if (modelObject == null) {
return ControllerUtils.toEmptyResponse(HttpStatus.CREATED); return ControllerUtils.toEmptyResponse(HttpStatus.CREATED);
} }
DSpaceResource result = repository.wrapResource(modelObject); DSpaceResource result = converter.toResource(modelObject);
linkService.addLinks(result);
//TODO manage HTTPHeader //TODO manage HTTPHeader
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result); return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result);
} }
@@ -476,8 +457,7 @@ public class RestResourceController implements InitializingBean {
if (modelObject == null) { if (modelObject == null) {
return ControllerUtils.toEmptyResponse(HttpStatus.CREATED); return ControllerUtils.toEmptyResponse(HttpStatus.CREATED);
} }
DSpaceResource result = repository.wrapResource(modelObject); DSpaceResource result = converter.toResource(modelObject);
linkService.addLinks(result);
//TODO manage HTTPHeader //TODO manage HTTPHeader
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result); return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result);
} }
@@ -515,8 +495,7 @@ public class RestResourceController implements InitializingBean {
} }
if (modelObject != null) { if (modelObject != null) {
DSpaceResource result = repository.wrapResource(modelObject); DSpaceResource result = converter.toResource(modelObject);
linkService.addLinks(result);
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result); return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result);
} else { } else {
return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT); return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT);
@@ -607,8 +586,7 @@ public class RestResourceController implements InitializingBean {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return ControllerUtils.toEmptyResponse(HttpStatus.INTERNAL_SERVER_ERROR); return ControllerUtils.toEmptyResponse(HttpStatus.INTERNAL_SERVER_ERROR);
} }
DSpaceResource result = repository.wrapResource(modelObject); DSpaceResource result = converter.toResource(modelObject);
linkService.addLinks(result);
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result); return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result);
} }
@@ -645,8 +623,7 @@ public class RestResourceController implements InitializingBean {
List<DSpaceResource> resources = new ArrayList<>(); List<DSpaceResource> resources = new ArrayList<>();
for (T modelObject : content) { for (T modelObject : content) {
DSpaceResource result = repository.wrapResource(modelObject); DSpaceResource result = converter.toResource(modelObject);
linkService.addLinks(result);
resources.add(result); resources.add(result);
} }
return ControllerUtils.toResponseEntity(HttpStatus.OK, null, Resources.wrap(resources)); return ControllerUtils.toResponseEntity(HttpStatus.OK, null, Resources.wrap(resources));
@@ -725,8 +702,7 @@ public class RestResourceController implements InitializingBean {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
throw e; throw e;
} }
DSpaceResource result = repository.wrapResource(modelObject); DSpaceResource result = converter.toResource(modelObject);
linkService.addLinks(result);
//TODO manage HTTPHeader //TODO manage HTTPHeader
return ControllerUtils.toResponseEntity(HttpStatus.OK, null, result); return ControllerUtils.toResponseEntity(HttpStatus.OK, null, result);
@@ -743,7 +719,6 @@ public class RestResourceController implements InitializingBean {
* @param relid * @param relid
* @param page * @param page
* @param assembler * @param assembler
* @param projection
* @return * @return
*/ */
private <ID extends Serializable> ResourceSupport findRelEntryInternal(HttpServletRequest request, private <ID extends Serializable> ResourceSupport findRelEntryInternal(HttpServletRequest request,
@@ -751,26 +726,24 @@ public class RestResourceController implements InitializingBean {
String apiCategory, String model, String apiCategory, String model,
String id, String rel, String relid, String id, String rel, String relid,
Pageable page, Pageable page,
PagedResourcesAssembler assembler, PagedResourcesAssembler assembler)
String projection) throws Throwable { throws Throwable {
checkModelPluralForm(apiCategory, model); checkModelPluralForm(apiCategory, model);
DSpaceRestRepository<RestAddressableModel, ID> repository = utils.getResourceRepository(apiCategory, model); DSpaceRestRepository<RestAddressableModel, ID> repository = utils.getResourceRepository(apiCategory, model);
Class<RestAddressableModel> domainClass = repository.getDomainClass(); Class<RestAddressableModel> domainClass = repository.getDomainClass();
LinkRest linkRest = utils.getLinkRest(rel, domainClass); LinkRest linkRest = utils.getClassLevelLinkRest(rel, domainClass);
if (linkRest != null) { if (linkRest != null) {
LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model, linkRest.name()); LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model, linkRest.name());
Method linkMethod = repositoryUtils.getLinkMethod("getResource", linkRepository); Method linkMethod = utils.requireMethod(linkRepository.getClass(), "getResource");
try { try {
Object object = linkMethod.invoke(linkRepository, request, id, relid, page, projection); Object object = linkMethod.invoke(linkRepository, request, id, relid, page, utils.obtainProjection());
Link link = linkTo(this.getClass(), apiCategory, model).slash(id).slash(rel).slash(relid).withSelfRel(); Link link = linkTo(this.getClass(), apiCategory, model).slash(id).slash(rel).slash(relid).withSelfRel();
List result = new ArrayList(); List result = new ArrayList();
result.add(object); result.add(object);
PageImpl<RestAddressableModel> pageResult = new PageImpl(result, page, 1); PageImpl<RestAddressableModel> pageResult = new PageImpl(result, page, 1);
Page<HALResource> halResources = pageResult.map(linkRepository::wrapResource); Page<HALResource> halResources = pageResult.map(restObject -> converter.toResource(restObject));
halResources.forEach(linkService::addLinks);
return assembler.toResource(halResources, link); return assembler.toResource(halResources, link);
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
// This catch has been made to resolve the issue that caused AuthorizeDenied exceptions for the methods // This catch has been made to resolve the issue that caused AuthorizeDenied exceptions for the methods
@@ -797,63 +770,52 @@ public class RestResourceController implements InitializingBean {
* @param apiCategory * @param apiCategory
* @param model * @param model
* @param uuid * @param uuid
* @param rel
* @param page * @param page
* @param assembler * @param assembler
* @param projection
* @return * @return
*/ */
private <ID extends Serializable> ResourceSupport findRelInternal(HttpServletRequest request, private <ID extends Serializable> ResourceSupport findRelInternal(HttpServletRequest request,
HttpServletResponse response, String apiCategory, HttpServletResponse response, String apiCategory,
String model, ID uuid, String subpath, String model, ID uuid, String subpath,
Pageable page, PagedResourcesAssembler assembler, Pageable page,
String projection) { PagedResourcesAssembler assembler) {
checkModelPluralForm(apiCategory, model); checkModelPluralForm(apiCategory, model);
DSpaceRestRepository<RestAddressableModel, ID> repository = utils.getResourceRepository(apiCategory, model); DSpaceRestRepository<RestAddressableModel, ID> repository = utils.getResourceRepository(apiCategory, model);
Class<RestAddressableModel> domainClass = repository.getDomainClass(); Class<RestAddressableModel> domainClass = repository.getDomainClass();
LinkRest linkRest = utils.getLinkRest(subpath, domainClass); LinkRest linkRest = utils.getClassLevelLinkRest(subpath, domainClass);
PagedResources<? extends HALResource> result; PagedResources<? extends HALResource> result;
if (linkRest != null) { if (linkRest != null) {
LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model, linkRest.name()); LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model, linkRest.name());
Method linkMethod = repositoryUtils.getLinkMethod(linkRest.method(), linkRepository); Method linkMethod = utils.requireMethod(linkRepository.getClass(), linkRest.method());
try {
if (Page.class.isAssignableFrom(linkMethod.getReturnType())) {
Page<? extends RestModel> pageResult = (Page<? extends RestAddressableModel>) linkMethod
.invoke(linkRepository, request, uuid, page, utils.obtainProjection(true));
if (linkMethod == null) { Link link = null;
// TODO custom exception String querystring = request.getQueryString();
throw new RuntimeException( if (querystring != null && querystring.length() > 0) {
"Method for relation " + subpath + " not found: " + linkRest.name() + ":" + linkRest.method()); link = linkTo(this.getClass(), apiCategory, model).slash(uuid)
} else { .slash(subpath + '?' + querystring).withSelfRel();
try {
if (Page.class.isAssignableFrom(linkMethod.getReturnType())) {
Page<? extends RestModel> pageResult = (Page<? extends RestAddressableModel>) linkMethod
.invoke(linkRepository, request, uuid, page, projection);
Link link = null;
String querystring = request.getQueryString();
if (querystring != null && querystring.length() > 0) {
link = linkTo(this.getClass(), apiCategory, model).slash(uuid)
.slash(subpath + '?' + querystring).withSelfRel();
} else {
link = linkTo(this.getClass(), apiCategory, model).slash(uuid).slash(subpath).withSelfRel();
}
Page<HALResource> halResources = pageResult.map(linkRepository::wrapResource);
halResources.forEach(linkService::addLinks);
return assembler.toResource(halResources, link);
} else { } else {
RestModel object = (RestModel) linkMethod.invoke(linkRepository, request, uuid, page, link = linkTo(this.getClass(), apiCategory, model).slash(uuid).slash(subpath).withSelfRel();
projection);
Link link = linkTo(this.getClass(), apiCategory, model).slash(uuid).slash(subpath)
.withSelfRel();
HALResource tmpresult = linkRepository.wrapResource(object);
tmpresult.add(link);
return tmpresult;
} }
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e.getMessage(), e); Page<HALResource> halResources = pageResult.map(object -> converter.toResource(object));
return assembler.toResource(halResources, link);
} else {
RestModel object = (RestModel) linkMethod.invoke(linkRepository, request, uuid, page,
utils.obtainProjection());
Link link = linkTo(this.getClass(), apiCategory, model).slash(uuid).slash(subpath)
.withSelfRel();
HALResource tmpresult = converter.toResource(object);
tmpresult.add(link);
return tmpresult;
} }
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e.getMessage(), e);
} }
} }
RestAddressableModel modelObject = repository.findOne(uuid); RestAddressableModel modelObject = repository.findOne(uuid);
@@ -862,8 +824,7 @@ public class RestResourceController implements InitializingBean {
throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + uuid + " not found"); throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + uuid + " not found");
} }
DSpaceResource resource = repository.wrapResource(modelObject, subpath); DSpaceResource resource = converter.toResource(modelObject);
linkService.addLinks(resource);
String rel = null; String rel = null;
@@ -904,16 +865,7 @@ public class RestResourceController implements InitializingBean {
.getResourceRepository(fullList.get(0).getCategory(), fullList.get(0).getType()); .getResourceRepository(fullList.get(0).getCategory(), fullList.get(0).getType());
PageImpl<RestAddressableModel> pageResult = new PageImpl(fullList.subList(start, end), page, PageImpl<RestAddressableModel> pageResult = new PageImpl(fullList.subList(start, end), page,
fullList.size()); fullList.size());
result = assembler.toResource(pageResult.map(resourceRepository::wrapResource)); return assembler.toResource(pageResult.map(converter::toResource));
for (Resource subObj : result) {
if (subObj.getContent() instanceof HALResource) {
linkService.addLinks((HALResource) subObj.getContent());
}
}
return result;
} else { } else {
if (resource.getEmbeddedResources().get(rel) == null) { if (resource.getEmbeddedResources().get(rel) == null) {
response.setStatus(HttpServletResponse.SC_NO_CONTENT); response.setStatus(HttpServletResponse.SC_NO_CONTENT);
@@ -930,7 +882,6 @@ public class RestResourceController implements InitializingBean {
* @param model * @param model
* @param page * @param page
* @param assembler * @param assembler
* @param projection
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
@@ -939,18 +890,15 @@ public class RestResourceController implements InitializingBean {
@PathVariable String model, @PathVariable String model,
Pageable page, Pageable page,
PagedResourcesAssembler assembler, PagedResourcesAssembler assembler,
@RequestParam(required = false)
String projection,
HttpServletResponse response) { HttpServletResponse response) {
DSpaceRestRepository<T, ?> repository = utils.getResourceRepository(apiCategory, model); DSpaceRestRepository<T, ?> repository = utils.getResourceRepository(apiCategory, model);
Link link = linkTo(methodOn(this.getClass(), apiCategory, model).findAll(apiCategory, model, Link link = linkTo(methodOn(this.getClass(), apiCategory, model).findAll(apiCategory, model,
page, assembler, projection, response)) page, assembler, response))
.withSelfRel(); .withSelfRel();
Page<DSpaceResource<T>> resources; Page<DSpaceResource<T>> resources;
try { try {
resources = repository.findAll(page).map(repository::wrapResource); resources = repository.findAll(page).map(converter::toResource);
resources.forEach(linkService::addLinks);
} catch (PaginationException pe) { } catch (PaginationException pe) {
resources = new PageImpl<DSpaceResource<T>>(new ArrayList<DSpaceResource<T>>(), page, pe.getTotal()); resources = new PageImpl<DSpaceResource<T>>(new ArrayList<DSpaceResource<T>>(), page, pe.getTotal());
} catch (RepositoryMethodNotImplementedException mne) { } catch (RepositoryMethodNotImplementedException mne) {
@@ -1029,18 +977,15 @@ public class RestResourceController implements InitializingBean {
if (searchResult == null) { if (searchResult == null) {
resources = new PageImpl(new ArrayList(), pageable, 0); resources = new PageImpl(new ArrayList(), pageable, 0);
} else { } else {
resources = ((Page<T>) searchResult).map(repository::wrapResource); resources = ((Page<T>) searchResult).map(converter::toResource);
} }
resources.forEach(linkService::addLinks);
result = assembler.toResource(resources, link); result = assembler.toResource(resources, link);
} else { } else {
if (searchResult == null) { if (searchResult == null) {
response.setStatus(HttpServletResponse.SC_NO_CONTENT); response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return null; return null;
} }
DSpaceResource<T> dsResource = repository.wrapResource((T) searchResult); return converter.toResource((T) searchResult);
linkService.addLinks(dsResource);
result = dsResource;
} }
return result; return result;
} }
@@ -1189,9 +1134,7 @@ public class RestResourceController implements InitializingBean {
if (modelObject == null) { if (modelObject == null) {
throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found"); throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found");
} }
DSpaceResource result = repository.wrapResource(modelObject); return converter.toResource(modelObject);
linkService.addLinks(result);
return result;
} }
/** /**
@@ -1214,9 +1157,6 @@ public class RestResourceController implements InitializingBean {
if (modelObject == null) { if (modelObject == null) {
throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found"); throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found");
} }
DSpaceResource result = repository.wrapResource(modelObject); return converter.toResource(modelObject);
linkService.addLinks(result);
return result;
} }
} }

View File

@@ -9,8 +9,8 @@ package org.dspace.app.rest;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.RootRest;
import org.dspace.app.rest.model.hateoas.RootResource; import org.dspace.app.rest.model.hateoas.RootResource;
import org.dspace.app.rest.repository.RootRestRepository; import org.dspace.app.rest.repository.RootRestRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -39,13 +39,11 @@ public class RootRestResourceController {
@Autowired @Autowired
RootRestRepository rootRestRepository; RootRestRepository rootRestRepository;
@Autowired
ConverterService converter;
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
public RootResource listDefinedEndpoint(HttpServletRequest request) { public RootResource listDefinedEndpoint(HttpServletRequest request) {
return converter.toResource(rootRestRepository.getRoot());
RootRest rootRest = rootRestRepository.getRoot();
RootResource rootResource = new RootResource(rootRest);
halLinkService.addLinks(rootResource);
return rootResource;
} }
} }

View File

@@ -9,12 +9,11 @@ package org.dspace.app.rest;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.model.ProcessRest; import org.dspace.app.rest.model.ProcessRest;
import org.dspace.app.rest.model.ScriptRest; import org.dspace.app.rest.model.ScriptRest;
import org.dspace.app.rest.model.hateoas.ProcessResource; import org.dspace.app.rest.model.hateoas.ProcessResource;
import org.dspace.app.rest.repository.ScriptRestRepository; import org.dspace.app.rest.repository.ScriptRestRepository;
import org.dspace.app.rest.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.ControllerUtils; import org.springframework.data.rest.webmvc.ControllerUtils;
import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.ResourceSupport;
@@ -35,15 +34,12 @@ public class ScriptProcessesController {
private static final Logger log = LogManager.getLogger(); private static final Logger log = LogManager.getLogger();
@Autowired
private ConverterService converter;
@Autowired @Autowired
private ScriptRestRepository scriptRestRepository; private ScriptRestRepository scriptRestRepository;
@Autowired
private HalLinkService halLinkService;
@Autowired
private Utils utils;
/** /**
* This method can be called by sending a POST request to the system/scripts/{name}/processes endpoint * This method can be called by sending a POST request to the system/scripts/{name}/processes endpoint
* This will start a process for the script that matches the given name * This will start a process for the script that matches the given name
@@ -59,8 +55,7 @@ public class ScriptProcessesController {
log.trace("Starting Process for Script with name: " + scriptName); log.trace("Starting Process for Script with name: " + scriptName);
} }
ProcessRest processRest = scriptRestRepository.startProcess(scriptName); ProcessRest processRest = scriptRestRepository.startProcess(scriptName);
ProcessResource processResource = new ProcessResource(processRest, utils, null); ProcessResource processResource = converter.toResource(processRest);
halLinkService.addLinks(processResource);
return ControllerUtils.toResponseEntity(HttpStatus.ACCEPTED, null, processResource); return ControllerUtils.toResponseEntity(HttpStatus.ACCEPTED, null, processResource);
} }

View File

@@ -10,6 +10,7 @@ package org.dspace.app.rest;
import java.util.Arrays; import java.util.Arrays;
import java.util.UUID; import java.util.UUID;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.exception.RepositoryMethodNotImplementedException; import org.dspace.app.rest.exception.RepositoryMethodNotImplementedException;
import org.dspace.app.rest.link.HalLinkService; import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.RestAddressableModel; import org.dspace.app.rest.model.RestAddressableModel;
@@ -47,6 +48,9 @@ public class StatisticsRestController implements InitializingBean {
@Autowired @Autowired
private HalLinkService halLinkService; private HalLinkService halLinkService;
@Autowired
private ConverterService converter;
@Autowired @Autowired
private StatisticsRestRepository statisticsRestRepository; private StatisticsRestRepository statisticsRestRepository;
@@ -65,12 +69,10 @@ public class StatisticsRestController implements InitializingBean {
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
public StatisticsSupportResource getStatisticsSupport() throws Exception { public StatisticsSupportResource getStatisticsSupport() throws Exception {
StatisticsSupportRest statisticsSupportRest = statisticsRestRepository.getStatisticsSupport(); StatisticsSupportRest statisticsSupportRest = statisticsRestRepository.getStatisticsSupport();
StatisticsSupportResource statisticsSupportResource = new StatisticsSupportResource(statisticsSupportRest); return converter.toResource(statisticsSupportRest);
halLinkService.addLinks(statisticsSupportResource);
return statisticsSupportResource;
} }
@RequestMapping(method = RequestMethod.GET, value = "/viewevents/{uuid}") @RequestMapping(method = RequestMethod.GET, value = "/viewevents/{uuid}")
public PagedResources<ViewEventResource> getViewEvent(@PathVariable(name = "uuid") UUID uuid) throws Exception { public PagedResources<ViewEventResource> getViewEvent(@PathVariable(name = "uuid") UUID uuid) throws Exception {
throw new RepositoryMethodNotImplementedException("No implementation found; Method not allowed!", ""); throw new RepositoryMethodNotImplementedException("No implementation found; Method not allowed!", "");
@@ -93,13 +95,13 @@ public class StatisticsRestController implements InitializingBean {
@RequestMapping(method = RequestMethod.POST, value = "/viewevents") @RequestMapping(method = RequestMethod.POST, value = "/viewevents")
public ResponseEntity<ResourceSupport> postViewEvent() throws Exception { public ResponseEntity<ResourceSupport> postViewEvent() throws Exception {
ViewEventResource result = new ViewEventResource(viewEventRestRepository.createViewEvent(), utils); ViewEventResource result = converter.toResource(viewEventRestRepository.createViewEvent());
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result); return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result);
} }
@RequestMapping(method = RequestMethod.POST, value = "/searchevents") @RequestMapping(method = RequestMethod.POST, value = "/searchevents")
public ResponseEntity<ResourceSupport> postSearchEvent() throws Exception { public ResponseEntity<ResourceSupport> postSearchEvent() throws Exception {
SearchEventResource result = new SearchEventResource(searchEventRestRepository.createSearchEvent(), utils); SearchEventResource result = converter.toResource(searchEventRestRepository.createSearchEvent());
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result); return ControllerUtils.toResponseEntity(HttpStatus.CREATED, null, result);
} }

View File

@@ -14,14 +14,14 @@ import java.net.URI;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import java.util.UUID; import java.util.UUID;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.app.rest.converter.GenericDSpaceObjectConverter; import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.model.DSpaceObjectRest; import org.dspace.app.rest.model.DSpaceObjectRest;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.DSpaceObjectService; import org.dspace.content.service.DSpaceObjectService;
@@ -57,6 +57,9 @@ public class UUIDLookupRestController implements InitializingBean {
@Autowired @Autowired
private ContentServiceFactory contentServiceFactory; private ContentServiceFactory contentServiceFactory;
@Autowired
private Utils utils;
private static final Logger log = private static final Logger log =
Logger.getLogger(UUIDLookupRestController.class); Logger.getLogger(UUIDLookupRestController.class);
@@ -64,7 +67,7 @@ public class UUIDLookupRestController implements InitializingBean {
private DiscoverableEndpointsService discoverableEndpointsService; private DiscoverableEndpointsService discoverableEndpointsService;
@Autowired @Autowired
private GenericDSpaceObjectConverter converter; private ConverterService converter;
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
@@ -92,7 +95,7 @@ public class UUIDLookupRestController implements InitializingBean {
.getDSpaceObjectServices()) { .getDSpaceObjectServices()) {
DSpaceObject dso = dSpaceObjectService.find(context, uuid); DSpaceObject dso = dSpaceObjectService.find(context, uuid);
if (dso != null) { if (dso != null) {
DSpaceObjectRest dsor = converter.convert(dso); DSpaceObjectRest dsor = converter.toRest(dso, utils.obtainProjection());
URI link = linkTo(dsor.getController(), dsor.getCategory(), dsor.getTypePlural()) URI link = linkTo(dsor.getController(), dsor.getCategory(), dsor.getTypePlural())
.slash(dsor.getId()).toUri(); .slash(dsor.getId()).toUri();
response.setStatus(HttpServletResponse.SC_FOUND); response.setStatus(HttpServletResponse.SC_FOUND);

View File

@@ -17,6 +17,7 @@ import org.dspace.app.rest.model.AInprogressSubmissionRest;
import org.dspace.app.rest.model.ErrorRest; import org.dspace.app.rest.model.ErrorRest;
import org.dspace.app.rest.model.SubmissionDefinitionRest; import org.dspace.app.rest.model.SubmissionDefinitionRest;
import org.dspace.app.rest.model.SubmissionSectionRest; import org.dspace.app.rest.model.SubmissionSectionRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.submit.AbstractRestProcessingStep; import org.dspace.app.rest.submit.AbstractRestProcessingStep;
import org.dspace.app.rest.submit.SubmissionService; import org.dspace.app.rest.submit.SubmissionService;
import org.dspace.app.util.SubmissionConfigReader; import org.dspace.app.util.SubmissionConfigReader;
@@ -47,22 +48,13 @@ public abstract class AInprogressItemConverter<T extends InProgressSubmission<ID
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(AInprogressItemConverter.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(AInprogressItemConverter.class);
@Autowired @Autowired
private EPersonConverter epersonConverter; private ConverterService converter;
@Autowired
private ItemConverter itemConverter;
@Autowired
private CollectionConverter collectionConverter;
protected SubmissionConfigReader submissionConfigReader;
@Autowired
private SubmissionDefinitionConverter submissionDefinitionConverter;
@Autowired @Autowired
private SubmissionSectionConverter submissionSectionConverter; private SubmissionSectionConverter submissionSectionConverter;
protected SubmissionConfigReader submissionConfigReader;
@Autowired @Autowired
SubmissionService submissionService; SubmissionService submissionService;
@@ -70,7 +62,7 @@ public abstract class AInprogressItemConverter<T extends InProgressSubmission<ID
submissionConfigReader = new SubmissionConfigReader(); submissionConfigReader = new SubmissionConfigReader();
} }
protected void fillFromModel(T obj, R witem) { protected void fillFromModel(T obj, R witem, Projection projection) {
Collection collection = obj.getCollection(); Collection collection = obj.getCollection();
Item item = obj.getItem(); Item item = obj.getItem();
EPerson submitter = null; EPerson submitter = null;
@@ -81,17 +73,17 @@ public abstract class AInprogressItemConverter<T extends InProgressSubmission<ID
} }
witem.setId(obj.getID()); witem.setId(obj.getID());
witem.setCollection(collection != null ? collectionConverter.convert(collection) : null); witem.setCollection(collection != null ? converter.toRest(collection, projection) : null);
witem.setItem(itemConverter.convert(item)); witem.setItem(converter.toRest(item, projection));
witem.setSubmitter(epersonConverter.convert(submitter)); witem.setSubmitter(converter.toRest(submitter, projection));
// 1. retrieve the submission definition // 1. retrieve the submission definition
// 2. iterate over the submission section to allow to plugin additional // 2. iterate over the submission section to allow to plugin additional
// info // info
if (collection != null) { if (collection != null) {
SubmissionDefinitionRest def = submissionDefinitionConverter SubmissionDefinitionRest def = converter.toRest(
.convert(submissionConfigReader.getSubmissionConfigByCollection(collection.getHandle())); submissionConfigReader.getSubmissionConfigByCollection(collection.getHandle()), projection);
witem.setSubmissionDefinition(def); witem.setSubmissionDefinition(def);
for (SubmissionSectionRest sections : def.getPanels()) { for (SubmissionSectionRest sections : def.getPanels()) {
SubmissionStepConfig stepConfig = submissionSectionConverter.toModel(sections); SubmissionStepConfig stepConfig = submissionSectionConverter.toModel(sections);
@@ -150,4 +142,4 @@ public abstract class AInprogressItemConverter<T extends InProgressSubmission<ID
} }
} }
} }

View File

@@ -7,8 +7,8 @@
*/ */
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.apache.commons.lang3.NotImplementedException;
import org.dspace.app.rest.model.AuthorityEntryRest; import org.dspace.app.rest.model.AuthorityEntryRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.AuthorityUtils; import org.dspace.app.rest.utils.AuthorityUtils;
import org.dspace.content.authority.Choice; import org.dspace.content.authority.Choice;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -17,7 +17,7 @@ import org.springframework.stereotype.Component;
* This is the converter from/to the Choice in the DSpace API data * This is the converter from/to the Choice in the DSpace API data
* model and the REST data model. * model and the REST data model.
* *
* TODO please do not use this convert but use the wrapper {@link AuthorityUtils#convertEntry(Choice, String)}} * TODO please do not use this convert but use the wrapper {@link AuthorityUtils#convertEntry(Choice, String, String)}
* *
* @author Luigi Andrea Pascarelli (luigiandrea.pascarelli at 4science.it) * @author Luigi Andrea Pascarelli (luigiandrea.pascarelli at 4science.it)
*/ */
@@ -25,8 +25,9 @@ import org.springframework.stereotype.Component;
public class AuthorityEntryRestConverter implements DSpaceConverter<Choice, AuthorityEntryRest> { public class AuthorityEntryRestConverter implements DSpaceConverter<Choice, AuthorityEntryRest> {
@Override @Override
public AuthorityEntryRest fromModel(Choice choice) { public AuthorityEntryRest convert(Choice choice, Projection projection) {
AuthorityEntryRest entry = new AuthorityEntryRest(); AuthorityEntryRest entry = new AuthorityEntryRest();
entry.setProjection(projection);
entry.setValue(choice.value); entry.setValue(choice.value);
entry.setDisplay(choice.label); entry.setDisplay(choice.label);
entry.setId(choice.authority); entry.setId(choice.authority);
@@ -35,7 +36,7 @@ public class AuthorityEntryRestConverter implements DSpaceConverter<Choice, Auth
} }
@Override @Override
public Choice toModel(AuthorityEntryRest obj) { public Class<Choice> getModelClass() {
throw new NotImplementedException("Method not implemented"); return Choice.class;
} }
} }

View File

@@ -7,8 +7,8 @@
*/ */
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.apache.commons.lang3.NotImplementedException;
import org.dspace.app.rest.model.AuthorityRest; import org.dspace.app.rest.model.AuthorityRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.AuthorityUtils; import org.dspace.app.rest.utils.AuthorityUtils;
import org.dspace.content.authority.ChoiceAuthority; import org.dspace.content.authority.ChoiceAuthority;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -18,7 +18,7 @@ import org.springframework.stereotype.Component;
* model and the REST data model * model and the REST data model
* *
* TODO please do not use this convert but use the wrapper * TODO please do not use this convert but use the wrapper
* {@link AuthorityUtils#convertAuthority(ChoiceAuthority, String)} * {@link AuthorityUtils#convertAuthority(ChoiceAuthority, String, String)}
* *
* @author Luigi Andrea Pascarelli (luigiandrea.pascarelli at 4science.it) * @author Luigi Andrea Pascarelli (luigiandrea.pascarelli at 4science.it)
*/ */
@@ -26,8 +26,9 @@ import org.springframework.stereotype.Component;
public class AuthorityRestConverter implements DSpaceConverter<ChoiceAuthority, AuthorityRest> { public class AuthorityRestConverter implements DSpaceConverter<ChoiceAuthority, AuthorityRest> {
@Override @Override
public AuthorityRest fromModel(ChoiceAuthority step) { public AuthorityRest convert(ChoiceAuthority step, Projection projection) {
AuthorityRest authorityRest = new AuthorityRest(); AuthorityRest authorityRest = new AuthorityRest();
authorityRest.setProjection(projection);
authorityRest.setHierarchical(step.isHierarchical()); authorityRest.setHierarchical(step.isHierarchical());
authorityRest.setScrollable(step.isScrollable()); authorityRest.setScrollable(step.isScrollable());
authorityRest.setIdentifier(step.hasIdentifier()); authorityRest.setIdentifier(step.hasIdentifier());
@@ -35,7 +36,7 @@ public class AuthorityRestConverter implements DSpaceConverter<ChoiceAuthority,
} }
@Override @Override
public ChoiceAuthority toModel(AuthorityRest obj) { public Class<ChoiceAuthority> getModelClass() {
throw new NotImplementedException("Method not implemented"); return ChoiceAuthority.class;
} }
} }

View File

@@ -10,9 +10,9 @@ package org.dspace.app.rest.converter;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.dspace.app.rest.model.BitstreamFormatRest;
import org.dspace.app.rest.model.BitstreamRest; import org.dspace.app.rest.model.BitstreamRest;
import org.dspace.app.rest.model.CheckSumRest; import org.dspace.app.rest.model.CheckSumRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.Bundle; import org.dspace.content.Bundle;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -25,19 +25,14 @@ import org.springframework.stereotype.Component;
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@Component @Component
public class BitstreamConverter public class BitstreamConverter extends DSpaceObjectConverter<Bitstream, BitstreamRest> {
extends DSpaceObjectConverter<org.dspace.content.Bitstream, org.dspace.app.rest.model.BitstreamRest> {
@Autowired(required = true) @Autowired
BitstreamFormatConverter bfConverter; ConverterService converter;
@Override @Override
public org.dspace.content.Bitstream toModel(org.dspace.app.rest.model.BitstreamRest obj) { public BitstreamRest convert(org.dspace.content.Bitstream obj, Projection projection) {
return super.toModel(obj); BitstreamRest b = super.convert(obj, projection);
}
@Override
public BitstreamRest fromModel(org.dspace.content.Bitstream obj) {
BitstreamRest b = super.fromModel(obj);
b.setSequenceId(obj.getSequenceID()); b.setSequenceId(obj.getSequenceID());
List<Bundle> bundles = null; List<Bundle> bundles = null;
try { try {
@@ -53,14 +48,11 @@ public class BitstreamConverter
checksum.setCheckSumAlgorithm(obj.getChecksumAlgorithm()); checksum.setCheckSumAlgorithm(obj.getChecksumAlgorithm());
checksum.setValue(obj.getChecksum()); checksum.setValue(obj.getChecksum());
b.setCheckSum(checksum); b.setCheckSum(checksum);
BitstreamFormatRest format = null;
try { try {
format = bfConverter.fromModel(obj.getFormat(null)); b.setFormat(converter.toRest(obj.getFormat(null), projection));
} catch (Exception e) { } catch (SQLException e) {
// TODO Auto-generated catch block throw new RuntimeException(e);
e.printStackTrace();
} }
b.setFormat(format);
b.setSizeBytes(obj.getSizeBytes()); b.setSizeBytes(obj.getSizeBytes());
return b; return b;
} }
@@ -71,7 +63,7 @@ public class BitstreamConverter
} }
@Override @Override
protected Class<Bitstream> getModelClass() { public Class<Bitstream> getModelClass() {
return Bitstream.class; return Bitstream.class;
} }
} }

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.BitstreamFormatRest; import org.dspace.app.rest.model.BitstreamFormatRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.BitstreamFormat; import org.dspace.content.BitstreamFormat;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -26,8 +27,9 @@ public class BitstreamFormatConverter implements DSpaceConverter<BitstreamFormat
BitstreamFormatService bitstreamFormatService; BitstreamFormatService bitstreamFormatService;
@Override @Override
public BitstreamFormatRest fromModel(BitstreamFormat obj) { public BitstreamFormatRest convert(BitstreamFormat obj, Projection projection) {
BitstreamFormatRest bf = new BitstreamFormatRest(); BitstreamFormatRest bf = new BitstreamFormatRest();
bf.setProjection(projection);
bf.setId(obj.getID()); bf.setId(obj.getID());
bf.setShortDescription(obj.getShortDescription()); bf.setShortDescription(obj.getShortDescription());
bf.setDescription(obj.getDescription()); bf.setDescription(obj.getDescription());
@@ -43,8 +45,7 @@ public class BitstreamFormatConverter implements DSpaceConverter<BitstreamFormat
} }
@Override @Override
public BitstreamFormat toModel(BitstreamFormatRest obj) { public Class<BitstreamFormat> getModelClass() {
// TODO Auto-generated method stub return BitstreamFormat.class;
return null;
} }
} }

View File

@@ -11,6 +11,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.dspace.app.rest.model.BrowseIndexRest; import org.dspace.app.rest.model.BrowseIndexRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.browse.BrowseIndex; import org.dspace.browse.BrowseIndex;
import org.dspace.sort.SortException; import org.dspace.sort.SortException;
import org.dspace.sort.SortOption; import org.dspace.sort.SortOption;
@@ -24,9 +25,11 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
public class BrowseIndexConverter implements DSpaceConverter<BrowseIndex, BrowseIndexRest> { public class BrowseIndexConverter implements DSpaceConverter<BrowseIndex, BrowseIndexRest> {
@Override @Override
public BrowseIndexRest fromModel(BrowseIndex obj) { public BrowseIndexRest convert(BrowseIndex obj, Projection projection) {
BrowseIndexRest bir = new BrowseIndexRest(); BrowseIndexRest bir = new BrowseIndexRest();
bir.setProjection(projection);
bir.setId(obj.getName()); bir.setId(obj.getName());
bir.setOrder(obj.getDefaultOrder()); bir.setOrder(obj.getDefaultOrder());
bir.setMetadataBrowse(obj.isMetadataIndex()); bir.setMetadataBrowse(obj.isMetadataIndex());
@@ -53,7 +56,7 @@ public class BrowseIndexConverter implements DSpaceConverter<BrowseIndex, Browse
} }
@Override @Override
public BrowseIndex toModel(BrowseIndexRest obj) { public Class<BrowseIndex> getModelClass() {
return null; return BrowseIndex.class;
} }
} }

View File

@@ -11,43 +11,38 @@ import java.util.stream.Collectors;
import org.dspace.app.rest.model.BitstreamRest; import org.dspace.app.rest.model.BitstreamRest;
import org.dspace.app.rest.model.BundleRest; import org.dspace.app.rest.model.BundleRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.Bundle; import org.dspace.content.Bundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class BundleConverter public class BundleConverter
extends DSpaceObjectConverter<org.dspace.content.Bundle, org.dspace.app.rest.model.BundleRest> { extends DSpaceObjectConverter<Bundle, BundleRest> {
@Autowired @Override
BitstreamConverter bitstreamConverter; public BundleRest convert(Bundle bundle, Projection projection) {
BundleRest bundleRest = super.convert(bundle, projection);
bundleRest.setBitstreams(bundle.getBitstreams()
.stream()
.map(x -> (BitstreamRest) converter.toRest(x, projection))
.collect(Collectors.toList()));
if (bundle.getPrimaryBitstream() != null) {
BitstreamRest primaryBitstreamRest = converter.toRest(bundle.getPrimaryBitstream(), projection);
bundleRest.setPrimaryBitstream(primaryBitstreamRest);
}
return bundleRest;
}
@Override
protected BundleRest newInstance() { protected BundleRest newInstance() {
return new BundleRest(); return new BundleRest();
} }
protected Class<Bundle> getModelClass() { @Override
public Class<Bundle> getModelClass() {
return Bundle.class; return Bundle.class;
} }
public BundleRest fromModel(Bundle obj) {
BundleRest bundle = (BundleRest) super.fromModel(obj);
bundle.setBitstreams(obj.getBitstreams()
.stream()
.map(x -> bitstreamConverter.fromModel(x))
.collect(Collectors.toList()));
if (obj.getPrimaryBitstream() != null) {
BitstreamRest primaryBitstreamRest = bitstreamConverter.fromModel(obj.getPrimaryBitstream());
bundle.setPrimaryBitstream(primaryBitstreamRest);
}
return bundle;
}
public Bundle toModel(BundleRest obj) {
return null;
}
} }

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.ClaimedTaskRest; import org.dspace.app.rest.model.ClaimedTaskRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.discovery.IndexableObject; import org.dspace.discovery.IndexableObject;
import org.dspace.xmlworkflow.storedcomponents.ClaimedTask; import org.dspace.xmlworkflow.storedcomponents.ClaimedTask;
import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem; import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
@@ -22,30 +23,27 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
public class ClaimedTaskConverter public class ClaimedTaskConverter
implements IndexableObjectConverter<ClaimedTask, org.dspace.app.rest.model.ClaimedTaskRest> { implements IndexableObjectConverter<ClaimedTask, ClaimedTaskRest> {
@Autowired @Autowired
private WorkflowItemConverter workflowItemConverter; private ConverterService converter;
@Autowired
private EPersonConverter epersonConverter;
@Override @Override
public ClaimedTaskRest fromModel(ClaimedTask obj) { public ClaimedTaskRest convert(ClaimedTask obj, Projection projection) {
ClaimedTaskRest taskRest = new ClaimedTaskRest(); ClaimedTaskRest taskRest = new ClaimedTaskRest();
taskRest.setProjection(projection);
XmlWorkflowItem witem = obj.getWorkflowItem(); XmlWorkflowItem witem = obj.getWorkflowItem();
taskRest.setId(obj.getID()); taskRest.setId(obj.getID());
taskRest.setWorkflowitem(workflowItemConverter.convert(witem)); taskRest.setWorkflowitem(converter.toRest(witem, projection));
taskRest.setAction(obj.getActionID()); taskRest.setAction(obj.getActionID());
taskRest.setStep(obj.getStepID()); taskRest.setStep(obj.getStepID());
taskRest.setOwner(epersonConverter.convert(obj.getOwner())); taskRest.setOwner(converter.toRest(obj.getOwner(), projection));
return taskRest; return taskRest;
} }
@Override @Override
public ClaimedTask toModel(ClaimedTaskRest obj) { public Class<ClaimedTask> getModelClass() {
return null; return ClaimedTask.class;
} }
@Override @Override
@@ -53,4 +51,4 @@ public class ClaimedTaskConverter
return object instanceof ClaimedTask; return object instanceof ClaimedTask;
} }
} }

View File

@@ -16,6 +16,7 @@ import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.model.CollectionRest; import org.dspace.app.rest.model.CollectionRest;
import org.dspace.app.rest.model.ResourcePolicyRest; import org.dspace.app.rest.model.ResourcePolicyRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.authorize.ResourcePolicy; import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.service.AuthorizeService; import org.dspace.authorize.service.AuthorizeService;
@@ -44,35 +45,28 @@ public class CollectionConverter
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(CollectionConverter.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(CollectionConverter.class);
@Autowired @Autowired
private BitstreamConverter bitstreamConverter; private ConverterService converter;
@Autowired @Autowired
private CollectionService collectionService; private CollectionService collectionService;
@Autowired @Autowired
private RequestService requestService; private RequestService requestService;
@Autowired @Autowired
private AuthorizeService authorizeService; private AuthorizeService authorizeService;
@Autowired
private ResourcePolicyConverter resourcePolicyConverter;
@Override @Override
public org.dspace.content.Collection toModel(org.dspace.app.rest.model.CollectionRest obj) { public CollectionRest convert(org.dspace.content.Collection obj, Projection projection) {
return (org.dspace.content.Collection) super.toModel(obj); CollectionRest col = super.convert(obj, projection);
}
@Override
public CollectionRest fromModel(org.dspace.content.Collection obj) {
CollectionRest col = (CollectionRest) super.fromModel(obj);
Bitstream logo = obj.getLogo(); Bitstream logo = obj.getLogo();
if (logo != null) { if (logo != null) {
col.setLogo(bitstreamConverter.convert(logo)); col.setLogo(converter.toRest(logo, projection));
} }
col.setDefaultAccessConditions(getDefaultBitstreamPoliciesForCollection(obj.getID())); col.setDefaultAccessConditions(getDefaultBitstreamPoliciesForCollection(obj.getID(), projection));
return col; return col;
} }
private List<ResourcePolicyRest> getDefaultBitstreamPoliciesForCollection(UUID uuid) { private List<ResourcePolicyRest> getDefaultBitstreamPoliciesForCollection(UUID uuid, Projection projection) {
Context context = null; Context context = null;
Request currentRequest = requestService.getCurrentRequest(); Request currentRequest = requestService.getCurrentRequest();
@@ -95,7 +89,7 @@ public class CollectionConverter
List<ResourcePolicyRest> results = new ArrayList<ResourcePolicyRest>(); List<ResourcePolicyRest> results = new ArrayList<ResourcePolicyRest>();
for (ResourcePolicy pp : defaultCollectionPolicies) { for (ResourcePolicy pp : defaultCollectionPolicies) {
ResourcePolicyRest accessCondition = resourcePolicyConverter.convert(pp); ResourcePolicyRest accessCondition = converter.toRest(pp, projection);
if (accessCondition != null) { if (accessCondition != null) {
results.add(accessCondition); results.add(accessCondition);
} }
@@ -109,7 +103,7 @@ public class CollectionConverter
} }
@Override @Override
protected Class<org.dspace.content.Collection> getModelClass() { public Class<org.dspace.content.Collection> getModelClass() {
return org.dspace.content.Collection.class; return org.dspace.content.Collection.class;
} }

View File

@@ -12,6 +12,7 @@ import java.util.List;
import org.dspace.app.rest.model.CollectionRest; import org.dspace.app.rest.model.CollectionRest;
import org.dspace.app.rest.model.CommunityRest; import org.dspace.app.rest.model.CommunityRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Community; import org.dspace.content.Community;
@@ -31,38 +32,29 @@ public class CommunityConverter
implements IndexableObjectConverter<Community, CommunityRest> { implements IndexableObjectConverter<Community, CommunityRest> {
@Autowired @Autowired
private BitstreamConverter bitstreamConverter; private ConverterService converter;
@Autowired
private CollectionConverter collectionConverter;
@Override @Override
public org.dspace.content.Community toModel(org.dspace.app.rest.model.CommunityRest obj) { public CommunityRest convert(org.dspace.content.Community obj, Projection projection) {
return (org.dspace.content.Community) super.toModel(obj); CommunityRest com = super.convert(obj, projection);
}
@Override
public CommunityRest fromModel(org.dspace.content.Community obj) {
CommunityRest com = (CommunityRest) super.fromModel(obj);
Bitstream logo = obj.getLogo(); Bitstream logo = obj.getLogo();
if (logo != null) { if (logo != null) {
com.setLogo(bitstreamConverter.convert(logo)); com.setLogo(converter.toRest(logo, projection));
} }
List<Collection> collections = obj.getCollections(); List<Collection> collections = obj.getCollections();
List<CollectionRest> collectionsRest = new ArrayList<CollectionRest>(); List<CollectionRest> collectionsRest = new ArrayList<>();
if (collections != null) { if (collections != null) {
for (Collection col : collections) { for (Collection col : collections) {
CollectionRest colrest = collectionConverter.fromModel(col); collectionsRest.add(converter.toRest(col, projection));
collectionsRest.add(colrest);
} }
} }
com.setCollections(collectionsRest); com.setCollections(collectionsRest);
List<Community> subCommunities = obj.getSubcommunities(); List<Community> subCommunities = obj.getSubcommunities();
List<CommunityRest> communityRest = new ArrayList<CommunityRest>(); List<CommunityRest> communityRest = new ArrayList<>();
if (subCommunities != null) { if (subCommunities != null) {
for (Community scom : subCommunities) { for (Community scom : subCommunities) {
CommunityRest scomrest = this.fromModel(scom); CommunityRest scomrest = this.convert(scom, projection);
communityRest.add(scomrest); communityRest.add(scomrest);
} }
} }
@@ -77,7 +69,7 @@ public class CommunityConverter
} }
@Override @Override
protected Class<org.dspace.content.Community> getModelClass() { public Class<org.dspace.content.Community> getModelClass() {
return org.dspace.content.Community.class; return org.dspace.content.Community.class;
} }

View File

@@ -0,0 +1,303 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.converter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.annotation.PostConstruct;
import org.apache.log4j.Logger;
import org.dspace.app.rest.link.HalLinkFactory;
import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.RestAddressableModel;
import org.dspace.app.rest.model.RestModel;
import org.dspace.app.rest.model.hateoas.HALResource;
import org.dspace.app.rest.projection.DefaultProjection;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
* Converts domain objects from the DSpace service layer to rest objects, and from rest objects to resource
* objects, applying {@link Projection}s where applicable.
*/
@Service
public class ConverterService {
private static final Logger log = Logger.getLogger(ConverterService.class);
private final Map<String, Projection> projectionMap = new HashMap<>();
private final Map<Class, DSpaceConverter> converterMap = new HashMap<>();
private final Map<Class<? extends RestModel>, Constructor> resourceConstructors = new HashMap<>();
@Autowired
private Utils utils;
@Autowired
private HalLinkService halLinkService;
@Autowired
private List<DSpaceConverter> converters;
@Autowired
private List<Projection> projections;
/**
* Converts the given model object to a rest object, using the appropriate {@link DSpaceConverter} and
* the given projection.
* <p>
* The projection's {@link Projection#transformModel(Object)} method will be automatically applied
* before conversion. If the rest object is a {@link RestModel}, the projection's
* {@link Projection#transformRest(RestModel)} method will be automatically called after conversion.
* </p>
*
* @param modelObject the model object, which may be a JPA entity any other class for which a converter exists.
* @param projection the projection to use.
* @param <M> the type of model object. A converter {@link Component} must exist that takes this as input.
* @param <R> the inferred return type.
* @return the converted object. If it's a {@link RestAddressableModel}, its
* {@link RestAddressableModel#getProjection()} will be set to the given projection.
* @throws IllegalArgumentException if there is no compatible converter.
* @throws ClassCastException if the converter's return type is not compatible with the inferred return type.
*/
public <M, R> R toRest(M modelObject, Projection projection) {
M transformedModel = projection.transformModel(modelObject);
DSpaceConverter<M, R> converter = requireConverter(modelObject.getClass());
R restObject = converter.convert(transformedModel, projection);
if (restObject instanceof RestModel) {
return (R) projection.transformRest((RestModel) restObject);
}
return restObject;
}
/**
* Converts a list of model objects to a page of rest objects using the given {@link Projection}.
*
* @param modelObjects the list of model objects.
* @param pageable the pageable.
* @param total the total number of items.
* @param projection the projection to use.
* @param <M> the model object class.
* @param <R> the rest object class.
* @return the page.
* @throws IllegalArgumentException if there is no compatible converter.
* @throws ClassCastException if the converter's return type is not compatible with the inferred return type.
*/
public <M, R> Page<R> toRestPage(List<M> modelObjects, Pageable pageable, long total, Projection projection) {
return new PageImpl<>(modelObjects, pageable, total).map((object) -> toRest(object, projection));
}
/**
* Converts a list of model objects to a page of rest objects using the given {@link Projection}.
*
* @param modelObjects the page of model objects.
* @param projection the projection to use.
* @param <M> the model object class.
* @param <R> the rest object class.
* @return the page.
* @throws IllegalArgumentException if there is no compatible converter.
* @throws ClassCastException if the converter's return type is not compatible with the inferred return type.
*/
public <M, R> Page<R> toRestPage(Page<M> modelObjects, Projection projection) {
return modelObjects.map((object) -> toRest(object, projection));
}
/**
* Gets the converter supporting the given class as input.
*
* @param sourceClass the desired converter's input type.
* @param <M> the converter's input type.
* @param <R> the converter's output type.
* @return the converter.
* @throws IllegalArgumentException if there is no such converter.
*/
<M, R> DSpaceConverter<M, R> getConverter(Class<M> sourceClass) {
return (DSpaceConverter<M, R>) requireConverter(sourceClass);
}
/**
* Converts the given rest object to a {@link HALResource} object.
* <p>
* If the rest object is a {@link RestAddressableModel}, the projection returned by
* {@link RestAddressableModel#getProjection()} will be used to determine which optional
* embeds and links will be added, and {@link Projection#transformResource(HALResource)}
* will be automatically called before returning the final, fully converted resource.
* </p><p>
* In all cases, the {@link HalLinkService} will be used immediately after the resource is constructed,
* to ensure all {@link HalLinkFactory}s have had a chance to add links as needed.
* </p>
*
* @param restObject the input rest object.
* @param <T> the return type, a subclass of {@link HALResource}.
* @return the fully converted resource, with all automatic links and embeds applied.
* @throws IllegalArgumentException if there is no compatible resource constructor.
* @throws ClassCastException if the resource type is not compatible with the inferred return type.
*/
public <T extends HALResource> T toResource(RestModel restObject) {
T halResource = getResource(restObject);
if (restObject instanceof RestAddressableModel) {
utils.embedOrLinkClassLevelRels(halResource);
halLinkService.addLinks(halResource);
Projection projection = ((RestAddressableModel) restObject).getProjection();
return projection.transformResource(halResource);
} else {
halLinkService.addLinks(halResource);
}
return halResource;
}
/**
* Gets the projection with the given name, or the default (no-op) projection if null is given.
*
* @param projectionName the projection name, or {@code null}.
* @return the projection with the given name, or {@link DefaultProjection} if {@code null} is given.
* @throws IllegalArgumentException if a name is provided and such a projection cannot be found.
*/
public Projection getProjection(@Nullable String projectionName) {
return projectionName == null ? Projection.DEFAULT : requireProjection(projectionName);
}
/**
* Creates and returns an instance of the appropriate {@link HALResource} subclass for the given rest object.
* <p>
* <b>Note:</b> Only two forms of constructor are supported for resources that can be created with this method:
* A one-argument constructor taking the wrapped {@link RestModel}, and a two-argument constructor also taking
* a {@link Utils} instance. If both are found in a candidate resource's constructor, the two-argument form
* will be used.
* </p>
*
* @param restObject the rest object to wrap.
* @param <T> the return type, a subclass of {@link HALResource}.
* @return a new resource instance of the appropriate type.
*/
private <T extends HALResource> T getResource(RestModel restObject) {
Constructor constructor = resourceConstructors.get(restObject.getClass());
if (constructor == null) {
throw new IllegalArgumentException("No constructor found to get resource class from " + restObject);
}
try {
if (constructor.getParameterCount() == 2) {
return (T) constructor.newInstance(restObject, utils);
} else {
return (T) constructor.newInstance(restObject);
}
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
}
throw new RuntimeException(e);
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
* Gets the projection with the given name or throws an {@link IllegalArgumentException}.
*
* @param projectionName the projection name.
* @return the projection.
* @throws IllegalArgumentException if not found.
*/
private Projection requireProjection(String projectionName) {
if (!projectionMap.containsKey(projectionName)) {
throw new IllegalArgumentException("No such projection: " + projectionName);
}
return projectionMap.get(projectionName);
}
/**
* Gets the converter that supports the given source/input class or throws an {@link IllegalArgumentException}.
*
* @param sourceClass the source/input class.
* @return the converter.
* @throws IllegalArgumentException if not found.
*/
private DSpaceConverter requireConverter(Class sourceClass) {
if (converterMap.containsKey(sourceClass)) {
return converterMap.get(sourceClass);
}
for (Class converterSourceClass : converterMap.keySet()) {
if (converterSourceClass.isAssignableFrom(sourceClass)) {
return converterMap.get(converterSourceClass);
}
}
throw new IllegalArgumentException("No converter found to get rest class from " + sourceClass);
}
/**
* Populates maps of injected components and constructors to be used by this service's public methods.
*/
@PostConstruct
private void initialize() {
// put all available projections in a map keyed by name
for (Projection projection : projections) {
projectionMap.put(projection.getName(), projection);
}
projectionMap.put(Projection.DEFAULT.getName(), Projection.DEFAULT);
// put all available converters in a map keyed by model (input) class
for (DSpaceConverter converter : converters) {
converterMap.put(converter.getModelClass(), converter);
}
// scan all resource classes and look for compatible rest classes (by naming convention),
// creating a map of resource constructors keyed by rest class, for later use.
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(Resource.class));
Set<BeanDefinition> beanDefinitions = provider.findCandidateComponents(
HALResource.class.getPackage().getName().replaceAll("\\.", "/"));
for (BeanDefinition beanDefinition : beanDefinitions) {
String resourceClassName = beanDefinition.getBeanClassName();
String resourceClassSimpleName = resourceClassName.substring(resourceClassName.lastIndexOf(".") + 1);
String restClassSimpleName = resourceClassSimpleName
.replaceAll("ResourceWrapper$", "RestWrapper")
.replaceAll("Resource$", "Rest");
String restClassName = RestModel.class.getPackage().getName() + "." + restClassSimpleName;
try {
Class<? extends RestModel> restClass =
(Class<? extends RestModel>) Class.forName(restClassName);
Class<HALResource<? extends RestModel>> resourceClass =
(Class<HALResource<? extends RestModel>>) Class.forName(resourceClassName);
Constructor compatibleConstructor = null;
for (Constructor constructor : resourceClass.getDeclaredConstructors()) {
if (constructor.getParameterCount() == 2 && constructor.getParameterTypes()[1] == Utils.class) {
compatibleConstructor = constructor;
break; // found preferred constructor
} else if (constructor.getParameterCount() == 1) {
compatibleConstructor = constructor;
}
}
if (compatibleConstructor != null) {
resourceConstructors.put(restClass, compatibleConstructor);
} else {
log.warn("Skipping registration of resource class " + resourceClassName
+ "; compatible constructor not found");
}
} catch (ClassNotFoundException e) {
log.warn("Skipping registration of resource class " + resourceClassName
+ "; rest class not found: " + restClassName);
}
}
}
}

View File

@@ -7,15 +7,11 @@
*/ */
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.springframework.core.convert.converter.Converter; import org.dspace.app.rest.projection.Projection;
public interface DSpaceConverter<M, R> extends Converter<M, R> { public interface DSpaceConverter<M, R> {
@Override
public default R convert(M source) {
return fromModel(source);
}
public abstract R fromModel(M obj); R convert(M modelObject, Projection projection);
public abstract M toModel(R obj); Class<M> getModelClass();
} }

View File

@@ -7,6 +7,8 @@
*/ */
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.MetadataValueList;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -21,32 +23,22 @@ import org.springframework.beans.factory.annotation.Autowired;
public abstract class DSpaceObjectConverter<M extends DSpaceObject, R extends org.dspace.app.rest.model public abstract class DSpaceObjectConverter<M extends DSpaceObject, R extends org.dspace.app.rest.model
.DSpaceObjectRest> implements DSpaceConverter<M, R> { .DSpaceObjectRest> implements DSpaceConverter<M, R> {
@Autowired(required = true) @Autowired
private MetadataConverter metadataConverter; ConverterService converter;
@Override @Override
public R fromModel(M obj) { public R convert(M obj, Projection projection) {
R resource = newInstance(); R resource = newInstance();
resource.setProjection(projection);
resource.setHandle(obj.getHandle()); resource.setHandle(obj.getHandle());
if (obj.getID() != null) { if (obj.getID() != null) {
resource.setUuid(obj.getID().toString()); resource.setUuid(obj.getID().toString());
} }
resource.setName(obj.getName()); resource.setName(obj.getName());
resource.setMetadata(metadataConverter.convert(obj.getMetadata())); MetadataValueList metadataValues = new MetadataValueList(obj.getMetadata());
resource.setMetadata(converter.toRest(metadataValues, projection));
return resource; return resource;
} }
@Override
public M toModel(R obj) {
return null;
}
public boolean supportsModel(DSpaceObject object) {
return object != null && object.getClass().equals(getModelClass());
}
protected abstract R newInstance(); protected abstract R newInstance();
}
protected abstract Class<M> getModelClass();
}

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.ParameterValueRest; import org.dspace.app.rest.model.ParameterValueRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.scripts.DSpaceCommandLineParameter; import org.dspace.scripts.DSpaceCommandLineParameter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -20,7 +21,7 @@ public class DSpaceRunnableParameterConverter
implements DSpaceConverter<DSpaceCommandLineParameter, ParameterValueRest> { implements DSpaceConverter<DSpaceCommandLineParameter, ParameterValueRest> {
@Override @Override
public ParameterValueRest fromModel(DSpaceCommandLineParameter dSpaceCommandLineParameter) { public ParameterValueRest convert(DSpaceCommandLineParameter dSpaceCommandLineParameter, Projection projection) {
ParameterValueRest parameterValueRest = new ParameterValueRest(); ParameterValueRest parameterValueRest = new ParameterValueRest();
parameterValueRest.setName(dSpaceCommandLineParameter.getName()); parameterValueRest.setName(dSpaceCommandLineParameter.getName());
parameterValueRest.setValue(dSpaceCommandLineParameter.getValue()); parameterValueRest.setValue(dSpaceCommandLineParameter.getValue());
@@ -28,6 +29,10 @@ public class DSpaceRunnableParameterConverter
} }
@Override @Override
public Class<DSpaceCommandLineParameter> getModelClass() {
return DSpaceCommandLineParameter.class;
}
public DSpaceCommandLineParameter toModel(ParameterValueRest parameterValueRest) { public DSpaceCommandLineParameter toModel(ParameterValueRest parameterValueRest) {
return new DSpaceCommandLineParameter(parameterValueRest.getName(), parameterValueRest.getValue()); return new DSpaceCommandLineParameter(parameterValueRest.getName(), parameterValueRest.getValue());
} }

View File

@@ -12,6 +12,7 @@ import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.dspace.app.rest.model.SearchConfigurationRest; import org.dspace.app.rest.model.SearchConfigurationRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.discovery.configuration.DiscoveryConfiguration; import org.dspace.discovery.configuration.DiscoveryConfiguration;
import org.dspace.discovery.configuration.DiscoverySearchFilter; import org.dspace.discovery.configuration.DiscoverySearchFilter;
import org.dspace.discovery.configuration.DiscoverySearchFilterFacet; import org.dspace.discovery.configuration.DiscoverySearchFilterFacet;
@@ -24,9 +25,13 @@ import org.springframework.stereotype.Component;
* to the convert method. * to the convert method.
*/ */
@Component @Component
public class DiscoverConfigurationConverter { public class DiscoverConfigurationConverter
public SearchConfigurationRest convert(DiscoveryConfiguration configuration) { implements DSpaceConverter<DiscoveryConfiguration, SearchConfigurationRest> {
@Override
public SearchConfigurationRest convert(DiscoveryConfiguration configuration, Projection projection) {
SearchConfigurationRest searchConfigurationRest = new SearchConfigurationRest(); SearchConfigurationRest searchConfigurationRest = new SearchConfigurationRest();
searchConfigurationRest.setProjection(projection);
if (configuration != null) { if (configuration != null) {
addSearchFilters(searchConfigurationRest, addSearchFilters(searchConfigurationRest,
configuration.getSearchFilters(), configuration.getSidebarFacets()); configuration.getSearchFilters(), configuration.getSidebarFacets());
@@ -36,6 +41,11 @@ public class DiscoverConfigurationConverter {
return searchConfigurationRest; return searchConfigurationRest;
} }
@Override
public Class<DiscoveryConfiguration> getModelClass() {
return DiscoveryConfiguration.class;
}
private void setDefaultSortOption(DiscoveryConfiguration configuration, private void setDefaultSortOption(DiscoveryConfiguration configuration,
SearchConfigurationRest searchConfigurationRest) { SearchConfigurationRest searchConfigurationRest) {
String defaultSort = configuration.getSearchSortConfiguration().SCORE; String defaultSort = configuration.getSearchSortConfiguration().SCORE;

View File

@@ -15,6 +15,7 @@ import org.dspace.app.rest.model.SearchFacetEntryRest;
import org.dspace.app.rest.model.SearchFacetValueRest; import org.dspace.app.rest.model.SearchFacetValueRest;
import org.dspace.app.rest.model.SearchResultsRest; import org.dspace.app.rest.model.SearchResultsRest;
import org.dspace.app.rest.parameter.SearchFilter; import org.dspace.app.rest.parameter.SearchFilter;
import org.dspace.app.rest.projection.Projection;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.discovery.DiscoverResult; import org.dspace.discovery.DiscoverResult;
import org.dspace.discovery.configuration.DiscoveryConfiguration; import org.dspace.discovery.configuration.DiscoveryConfiguration;
@@ -36,19 +37,20 @@ public class DiscoverFacetResultsConverter {
public FacetResultsRest convert(Context context, String facetName, String prefix, String query, String dsoType, public FacetResultsRest convert(Context context, String facetName, String prefix, String query, String dsoType,
String dsoScope, List<SearchFilter> searchFilters, DiscoverResult searchResult, String dsoScope, List<SearchFilter> searchFilters, DiscoverResult searchResult,
DiscoveryConfiguration configuration, Pageable page) { DiscoveryConfiguration configuration, Pageable page, Projection projection) {
FacetResultsRest facetResultsRest = new FacetResultsRest(); FacetResultsRest facetResultsRest = new FacetResultsRest();
facetResultsRest.setProjection(projection);
setRequestInformation(context, facetName, prefix, query, dsoType, dsoScope, searchFilters, searchResult, setRequestInformation(context, facetName, prefix, query, dsoType, dsoScope, searchFilters, searchResult,
configuration, facetResultsRest, page); configuration, facetResultsRest, page, projection);
addToFacetResultList(facetName, searchResult, facetResultsRest, configuration, page); addToFacetResultList(facetName, searchResult, facetResultsRest, configuration, page, projection);
return facetResultsRest; return facetResultsRest;
} }
private void addToFacetResultList(String facetName, DiscoverResult searchResult, FacetResultsRest facetResultsRest, private void addToFacetResultList(String facetName, DiscoverResult searchResult, FacetResultsRest facetResultsRest,
DiscoveryConfiguration configuration, Pageable page) { DiscoveryConfiguration configuration, Pageable page, Projection projection) {
DiscoverySearchFilterFacet field = configuration.getSidebarFacet(facetName); DiscoverySearchFilterFacet field = configuration.getSidebarFacet(facetName);
List<DiscoverResult.FacetResult> facetValues = searchResult.getFacetResult(field); List<DiscoverResult.FacetResult> facetValues = searchResult.getFacetResult(field);
@@ -59,26 +61,27 @@ public class DiscoverFacetResultsConverter {
//We requested one facet value more as the page size. We must make sure to not return the extra value. //We requested one facet value more as the page size. We must make sure to not return the extra value.
break; break;
} }
SearchFacetValueRest searchFacetValueRest = buildSearchFacetValueRestFromFacetResult(value); SearchFacetValueRest searchFacetValueRest = buildSearchFacetValueRestFromFacetResult(value, projection);
facetResultsRest.addToFacetResultList(searchFacetValueRest); facetResultsRest.addToFacetResultList(searchFacetValueRest);
valueCount++; valueCount++;
} }
} }
private SearchFacetValueRest buildSearchFacetValueRestFromFacetResult(DiscoverResult.FacetResult value) { private SearchFacetValueRest buildSearchFacetValueRestFromFacetResult(DiscoverResult.FacetResult value,
return facetValueConverter.convert(value); Projection projection) {
return facetValueConverter.convert(value, projection);
} }
private void setRequestInformation(Context context, String facetName, String prefix, String query, String dsoType, private void setRequestInformation(Context context, String facetName, String prefix, String query, String dsoType,
String dsoScope, List<SearchFilter> searchFilters, DiscoverResult searchResult, String dsoScope, List<SearchFilter> searchFilters, DiscoverResult searchResult,
DiscoveryConfiguration configuration, FacetResultsRest facetResultsRest, DiscoveryConfiguration configuration, FacetResultsRest facetResultsRest,
Pageable page) { Pageable page, Projection projection) {
facetResultsRest.setQuery(query); facetResultsRest.setQuery(query);
facetResultsRest.setPrefix(prefix); facetResultsRest.setPrefix(prefix);
facetResultsRest.setScope(dsoScope); facetResultsRest.setScope(dsoScope);
facetResultsRest.setDsoType(dsoType); facetResultsRest.setDsoType(dsoType);
facetResultsRest.setFacetEntry(convertFacetEntry(facetName, searchResult, configuration, page)); facetResultsRest.setFacetEntry(convertFacetEntry(facetName, searchResult, configuration, page, projection));
facetResultsRest.setSort(SearchResultsRest.Sorting.fromPage(page)); facetResultsRest.setSort(SearchResultsRest.Sorting.fromPage(page));
@@ -91,10 +94,12 @@ public class DiscoverFacetResultsConverter {
} }
private SearchFacetEntryRest convertFacetEntry(final String facetName, final DiscoverResult searchResult, private SearchFacetEntryRest convertFacetEntry(final String facetName, final DiscoverResult searchResult,
final DiscoveryConfiguration configuration, final Pageable page) { final DiscoveryConfiguration configuration, final Pageable page,
final Projection projection) {
DiscoverySearchFilterFacet field = configuration.getSidebarFacet(facetName); DiscoverySearchFilterFacet field = configuration.getSidebarFacet(facetName);
SearchFacetEntryRest facetEntryRest = new SearchFacetEntryRest(facetName); SearchFacetEntryRest facetEntryRest = new SearchFacetEntryRest(facetName);
facetEntryRest.setProjection(projection);
List<DiscoverResult.FacetResult> facetResults = searchResult.getFacetResult(field); List<DiscoverResult.FacetResult> facetResults = searchResult.getFacetResult(field);
if (!facetResults.isEmpty()) { if (!facetResults.isEmpty()) {

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.SearchFacetValueRest; import org.dspace.app.rest.model.SearchFacetValueRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.discovery.DiscoverResult; import org.dspace.discovery.DiscoverResult;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -17,8 +18,9 @@ import org.springframework.stereotype.Component;
@Component @Component
public class DiscoverFacetValueConverter { public class DiscoverFacetValueConverter {
public SearchFacetValueRest convert(final DiscoverResult.FacetResult value) { public SearchFacetValueRest convert(final DiscoverResult.FacetResult value, final Projection projection) {
SearchFacetValueRest valueRest = new SearchFacetValueRest(); SearchFacetValueRest valueRest = new SearchFacetValueRest();
valueRest.setProjection(projection);
valueRest.setLabel(value.getDisplayedValue()); valueRest.setLabel(value.getDisplayedValue());
valueRest.setFilterValue(value.getAsFilterQuery()); valueRest.setFilterValue(value.getAsFilterQuery());
valueRest.setFilterType(value.getFilterType()); valueRest.setFilterType(value.getFilterType());

View File

@@ -16,6 +16,7 @@ import org.dspace.app.rest.model.SearchFacetEntryRest;
import org.dspace.app.rest.model.SearchFacetValueRest; import org.dspace.app.rest.model.SearchFacetValueRest;
import org.dspace.app.rest.model.SearchResultsRest; import org.dspace.app.rest.model.SearchResultsRest;
import org.dspace.app.rest.parameter.SearchFilter; import org.dspace.app.rest.parameter.SearchFilter;
import org.dspace.app.rest.projection.Projection;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.discovery.DiscoverQuery; import org.dspace.discovery.DiscoverQuery;
import org.dspace.discovery.DiscoverResult; import org.dspace.discovery.DiscoverResult;
@@ -39,13 +40,15 @@ public class DiscoverFacetsConverter {
public SearchResultsRest convert(Context context, String query, String dsoType, String configurationName, public SearchResultsRest convert(Context context, String query, String dsoType, String configurationName,
String dsoScope, List<SearchFilter> searchFilters, final Pageable page, String dsoScope, List<SearchFilter> searchFilters, final Pageable page,
DiscoveryConfiguration configuration, DiscoverResult searchResult) { DiscoveryConfiguration configuration, DiscoverResult searchResult,
Projection projection) {
SearchResultsRest searchResultsRest = new SearchResultsRest(); SearchResultsRest searchResultsRest = new SearchResultsRest();
searchResultsRest.setProjection(projection);
setRequestInformation(context, query, dsoType, configurationName, dsoScope, searchFilters, page, setRequestInformation(context, query, dsoType, configurationName, dsoScope, searchFilters, page,
searchResultsRest); searchResultsRest);
addFacetValues(context, searchResult, searchResultsRest, configuration); addFacetValues(context, searchResult, searchResultsRest, configuration, projection);
return searchResultsRest; return searchResultsRest;
} }
@@ -64,13 +67,14 @@ public class DiscoverFacetsConverter {
* The DiscoveryConfiguration applied to the query * The DiscoveryConfiguration applied to the query
*/ */
public void addFacetValues(Context context, final DiscoverResult searchResult, final SearchResultsRest resultsRest, public void addFacetValues(Context context, final DiscoverResult searchResult, final SearchResultsRest resultsRest,
final DiscoveryConfiguration configuration) { final DiscoveryConfiguration configuration, final Projection projection) {
List<DiscoverySearchFilterFacet> facets = configuration.getSidebarFacets(); List<DiscoverySearchFilterFacet> facets = configuration.getSidebarFacets();
for (DiscoverySearchFilterFacet field : CollectionUtils.emptyIfNull(facets)) { for (DiscoverySearchFilterFacet field : CollectionUtils.emptyIfNull(facets)) {
List<DiscoverResult.FacetResult> facetValues = searchResult.getFacetResult(field); List<DiscoverResult.FacetResult> facetValues = searchResult.getFacetResult(field);
SearchFacetEntryRest facetEntry = new SearchFacetEntryRest(field.getIndexFieldName()); SearchFacetEntryRest facetEntry = new SearchFacetEntryRest(field.getIndexFieldName());
facetEntry.setProjection(projection);
int valueCount = 0; int valueCount = 0;
facetEntry.setHasMore(false); facetEntry.setHasMore(false);
facetEntry.setFacetLimit(field.getFacetLimit()); facetEntry.setFacetLimit(field.getFacetLimit());
@@ -84,7 +88,7 @@ public class DiscoverFacetsConverter {
// are // are
// more results available. // more results available.
if (valueCount < field.getFacetLimit()) { if (valueCount < field.getFacetLimit()) {
SearchFacetValueRest valueRest = facetValueConverter.convert(value); SearchFacetValueRest valueRest = facetValueConverter.convert(value, projection);
facetEntry.addValue(valueRest); facetEntry.addValue(valueRest);
} else { } else {

View File

@@ -18,6 +18,7 @@ import org.dspace.app.rest.model.RestAddressableModel;
import org.dspace.app.rest.model.SearchResultEntryRest; import org.dspace.app.rest.model.SearchResultEntryRest;
import org.dspace.app.rest.model.SearchResultsRest; import org.dspace.app.rest.model.SearchResultsRest;
import org.dspace.app.rest.parameter.SearchFilter; import org.dspace.app.rest.parameter.SearchFilter;
import org.dspace.app.rest.projection.Projection;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.discovery.DiscoverResult; import org.dspace.discovery.DiscoverResult;
import org.dspace.discovery.IndexableObject; import org.dspace.discovery.IndexableObject;
@@ -45,15 +46,17 @@ public class DiscoverResultConverter {
public SearchResultsRest convert(final Context context, final String query, final String dsoType, public SearchResultsRest convert(final Context context, final String query, final String dsoType,
final String configurationName, final String scope, final String configurationName, final String scope,
final List<SearchFilter> searchFilters, final Pageable page, final List<SearchFilter> searchFilters, final Pageable page,
final DiscoverResult searchResult, final DiscoveryConfiguration configuration) { final DiscoverResult searchResult, final DiscoveryConfiguration configuration,
final Projection projection) {
SearchResultsRest resultsRest = new SearchResultsRest(); SearchResultsRest resultsRest = new SearchResultsRest();
resultsRest.setProjection(projection);
setRequestInformation(context, query, dsoType, configurationName, scope, searchFilters, page, resultsRest); setRequestInformation(context, query, dsoType, configurationName, scope, searchFilters, page, resultsRest);
addSearchResults(searchResult, resultsRest); addSearchResults(searchResult, resultsRest, projection);
addFacetValues(context, searchResult, resultsRest, configuration); addFacetValues(context, searchResult, resultsRest, configuration, projection);
resultsRest.setTotalNumberOfResults(searchResult.getTotalSearchResults()); resultsRest.setTotalNumberOfResults(searchResult.getTotalSearchResults());
@@ -61,16 +64,18 @@ public class DiscoverResultConverter {
} }
private void addFacetValues(Context context, final DiscoverResult searchResult, final SearchResultsRest resultsRest, private void addFacetValues(Context context, final DiscoverResult searchResult, final SearchResultsRest resultsRest,
final DiscoveryConfiguration configuration) { final DiscoveryConfiguration configuration, final Projection projection) {
facetConverter.addFacetValues(context, searchResult, resultsRest, configuration); facetConverter.addFacetValues(context, searchResult, resultsRest, configuration, projection);
} }
private void addSearchResults(final DiscoverResult searchResult, final SearchResultsRest resultsRest) { private void addSearchResults(final DiscoverResult searchResult, final SearchResultsRest resultsRest,
final Projection projection) {
for (IndexableObject dspaceObject : CollectionUtils.emptyIfNull(searchResult.getIndexableObjects())) { for (IndexableObject dspaceObject : CollectionUtils.emptyIfNull(searchResult.getIndexableObjects())) {
SearchResultEntryRest resultEntry = new SearchResultEntryRest(); SearchResultEntryRest resultEntry = new SearchResultEntryRest();
resultEntry.setProjection(projection);
//Convert the DSpace Object to its REST model //Convert the DSpace Object to its REST model
resultEntry.setIndexableObject(convertDSpaceObject(dspaceObject)); resultEntry.setIndexableObject(convertDSpaceObject(dspaceObject, projection));
//Add hit highlighting for this DSO if present //Add hit highlighting for this DSO if present
DiscoverResult.IndexableObjectHighlightResult highlightedResults = searchResult DiscoverResult.IndexableObjectHighlightResult highlightedResults = searchResult
@@ -86,10 +91,10 @@ public class DiscoverResultConverter {
} }
} }
private RestAddressableModel convertDSpaceObject(final IndexableObject dspaceObject) { private RestAddressableModel convertDSpaceObject(final IndexableObject dspaceObject, final Projection projection) {
for (IndexableObjectConverter<IndexableObject, RestAddressableModel> converter : converters) { for (IndexableObjectConverter<IndexableObject, RestAddressableModel> converter : converters) {
if (converter.supportsModel(dspaceObject)) { if (converter.supportsModel(dspaceObject)) {
return converter.convert(dspaceObject); return converter.convert(dspaceObject, projection);
} }
} }
return null; return null;

View File

@@ -14,6 +14,7 @@ import java.util.List;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.model.EPersonRest; import org.dspace.app.rest.model.EPersonRest;
import org.dspace.app.rest.model.GroupRest; import org.dspace.app.rest.model.GroupRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group; import org.dspace.eperson.Group;
@@ -30,17 +31,17 @@ import org.springframework.stereotype.Component;
@Component @Component
public class EPersonConverter extends DSpaceObjectConverter<EPerson, org.dspace.app.rest.model.EPersonRest> { public class EPersonConverter extends DSpaceObjectConverter<EPerson, org.dspace.app.rest.model.EPersonRest> {
@Autowired(required = true) @Autowired
private GroupConverter epersonGroupConverter; private ConverterService converter;
@Autowired(required = true) @Autowired
private GroupService groupService; private GroupService groupService;
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(EPersonConverter.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(EPersonConverter.class);
@Override @Override
public EPersonRest fromModel(EPerson obj) { public EPersonRest convert(EPerson obj, Projection projection) {
EPersonRest eperson = super.fromModel(obj); EPersonRest eperson = super.convert(obj, projection);
eperson.setLastActive(obj.getLastActive()); eperson.setLastActive(obj.getLastActive());
eperson.setNetid(obj.getNetid()); eperson.setNetid(obj.getNetid());
eperson.setCanLogIn(obj.canLogIn()); eperson.setCanLogIn(obj.canLogIn());
@@ -51,31 +52,26 @@ public class EPersonConverter extends DSpaceObjectConverter<EPerson, org.dspace.
return eperson; return eperson;
} }
public EPersonRest fromModelWithGroups(Context context, EPerson ePerson) throws SQLException { public EPersonRest fromModelWithGroups(Context context, EPerson ePerson, Projection projection)
EPersonRest eperson = fromModel(ePerson); throws SQLException {
EPersonRest eperson = convert(ePerson, projection);
List<GroupRest> groups = new ArrayList<GroupRest>(); List<GroupRest> groups = new ArrayList<>();
for (Group g : groupService.allMemberGroups(context, ePerson)) { for (Group g : groupService.allMemberGroups(context, ePerson)) {
groups.add(epersonGroupConverter.convert(g)); groups.add(converter.toRest(g, projection));
} }
eperson.setGroups(groups); eperson.setGroups(groups);
return eperson; return eperson;
} }
@Override
public EPerson toModel(EPersonRest obj) {
// TODO Auto-generated method stub
return null;
}
@Override @Override
protected EPersonRest newInstance() { protected EPersonRest newInstance() {
return new EPersonRest(); return new EPersonRest();
} }
@Override @Override
protected Class<EPerson> getModelClass() { public Class<EPerson> getModelClass() {
return EPerson.class; return EPerson.class;
} }

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.EntityTypeRest; import org.dspace.app.rest.model.EntityTypeRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.EntityType; import org.dspace.content.EntityType;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -18,29 +19,17 @@ import org.springframework.stereotype.Component;
@Component @Component
public class EntityTypeConverter implements DSpaceConverter<org.dspace.content.EntityType, EntityTypeRest> { public class EntityTypeConverter implements DSpaceConverter<org.dspace.content.EntityType, EntityTypeRest> {
/** @Override
* This method converts the EntityType model object that is passed along in the params to the public EntityTypeRest convert(EntityType obj, Projection projection) {
* REST representation of this object
* @param obj The EntityType model object to be converted
* @return The EntityType REST object that is made from the model object
*/
public EntityTypeRest fromModel(EntityType obj) {
EntityTypeRest entityTypeRest = new EntityTypeRest(); EntityTypeRest entityTypeRest = new EntityTypeRest();
entityTypeRest.setProjection(projection);
entityTypeRest.setId(obj.getID()); entityTypeRest.setId(obj.getID());
entityTypeRest.setLabel(obj.getLabel()); entityTypeRest.setLabel(obj.getLabel());
return entityTypeRest; return entityTypeRest;
} }
/** @Override
* This method converts the EntityType REST object that is passed along in the params to the model public Class<EntityType> getModelClass() {
* representation of this object return EntityType.class;
* @param obj The EntityType REST object to be converted
* @return The EntityType model object that is made from the REST object
*/
public EntityType toModel(EntityTypeRest obj) {
EntityType entityType = new EntityType();
entityType.setId(obj.getId());
entityType.setLabel(obj.getLabel());
return entityType;
} }
} }

View File

@@ -1,61 +0,0 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.converter;
import java.util.List;
import org.apache.log4j.Logger;
import org.dspace.app.rest.model.DSpaceObjectRest;
import org.dspace.content.DSpaceObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* This is the converter from/to an unknown DSpaceObject in the DSpace API data model and the
* REST data model
*
* @author Andrea Bollini (andrea.bollini at 4science.it)
*/
@Component
public class GenericDSpaceObjectConverter
extends DSpaceObjectConverter<org.dspace.content.DSpaceObject, org.dspace.app.rest.model.DSpaceObjectRest> {
@Autowired
private List<DSpaceObjectConverter> converters;
private static final Logger log = Logger.getLogger(GenericDSpaceObjectConverter.class);
/**
* Convert a DSpaceObject in its REST representation using a suitable converter
*/
@Override
public DSpaceObjectRest fromModel(org.dspace.content.DSpaceObject dspaceObject) {
for (DSpaceObjectConverter converter : converters) {
if (converter.supportsModel(dspaceObject)) {
return converter.fromModel(dspaceObject);
}
}
return null;
}
@Override
public org.dspace.content.DSpaceObject toModel(DSpaceObjectRest obj) {
return null;
}
@Override
protected DSpaceObjectRest newInstance() {
return null;
}
@Override
protected Class<DSpaceObject> getModelClass() {
return DSpaceObject.class;
}
}

View File

@@ -12,6 +12,7 @@ import java.util.List;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.model.GroupRest; import org.dspace.app.rest.model.GroupRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.eperson.Group; import org.dspace.eperson.Group;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -27,31 +28,25 @@ public class GroupConverter extends DSpaceObjectConverter<Group, org.dspace.app.
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(GroupConverter.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(GroupConverter.class);
@Override @Override
public GroupRest fromModel(Group obj) { public GroupRest convert(Group obj, Projection projection) {
GroupRest epersongroup = super.fromModel(obj); GroupRest epersongroup = super.convert(obj, projection);
epersongroup.setPermanent(obj.isPermanent()); epersongroup.setPermanent(obj.isPermanent());
List<GroupRest> groups = new ArrayList<GroupRest>(); List<GroupRest> groups = new ArrayList<GroupRest>();
for (Group g : obj.getMemberGroups()) { for (Group g : obj.getMemberGroups()) {
groups.add(convert(g)); groups.add(convert(g, projection));
} }
epersongroup.setGroups(groups); epersongroup.setGroups(groups);
return epersongroup; return epersongroup;
} }
@Override
public Group toModel(GroupRest obj) {
// TODO Auto-generated method stub
return null;
}
@Override @Override
protected GroupRest newInstance() { protected GroupRest newInstance() {
return new GroupRest(); return new GroupRest();
} }
@Override @Override
protected Class<Group> getModelClass() { public Class<Group> getModelClass() {
return Group.class; return Group.class;
} }

View File

@@ -14,11 +14,11 @@ import org.dspace.app.rest.model.HarvestStatusEnum;
import org.dspace.app.rest.model.HarvestTypeEnum; import org.dspace.app.rest.model.HarvestTypeEnum;
import org.dspace.app.rest.model.HarvestedCollectionRest; import org.dspace.app.rest.model.HarvestedCollectionRest;
import org.dspace.app.rest.model.HarvesterMetadataRest; import org.dspace.app.rest.model.HarvesterMetadataRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.harvest.HarvestedCollection; import org.dspace.harvest.HarvestedCollection;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/** /**
* This is the converter from/to the HarvestedCollection in the DSpace API data model and the REST data model * This is the converter from/to the HarvestedCollection in the DSpace API data model and the REST data model
@@ -29,18 +29,19 @@ import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class HarvestedCollectionConverter implements DSpaceConverter<HarvestedCollection, HarvestedCollectionRest> { public class HarvestedCollectionConverter implements DSpaceConverter<HarvestedCollection, HarvestedCollectionRest> {
@Autowired @Autowired
private CollectionConverter collectionConverter; private ConverterService converter;
@Override @Override
public HarvestedCollectionRest fromModel(HarvestedCollection obj) { public HarvestedCollectionRest convert(HarvestedCollection obj, Projection projection) {
HarvestedCollectionRest harvestedCollectionRest = new HarvestedCollectionRest(); HarvestedCollectionRest harvestedCollectionRest = new HarvestedCollectionRest();
harvestedCollectionRest.setProjection(projection);
if (obj != null) { if (obj != null) {
HarvestTypeEnum harvestTypeEnum = HarvestTypeEnum.fromInt(obj.getHarvestType()); HarvestTypeEnum harvestTypeEnum = HarvestTypeEnum.fromInt(obj.getHarvestType());
HarvestStatusEnum harvestStatusEnum = HarvestStatusEnum.fromInt(obj.getHarvestStatus()); HarvestStatusEnum harvestStatusEnum = HarvestStatusEnum.fromInt(obj.getHarvestStatus());
harvestedCollectionRest.setId(obj.getID()); harvestedCollectionRest.setId(obj.getID());
harvestedCollectionRest.setCollection(collectionConverter.fromModel(obj.getCollection())); harvestedCollectionRest.setCollection(converter.toRest(obj.getCollection(), projection));
harvestedCollectionRest.setHarvestType(harvestTypeEnum); harvestedCollectionRest.setHarvestType(harvestTypeEnum);
harvestedCollectionRest.setHarvestStatus(harvestStatusEnum); harvestedCollectionRest.setHarvestStatus(harvestStatusEnum);
harvestedCollectionRest.setMetadataConfigId(obj.getHarvestMetadataConfig()); harvestedCollectionRest.setMetadataConfigId(obj.getHarvestMetadataConfig());
@@ -59,24 +60,25 @@ public class HarvestedCollectionConverter implements DSpaceConverter<HarvestedCo
public HarvestedCollectionRest fromModel(HarvestedCollection obj, public HarvestedCollectionRest fromModel(HarvestedCollection obj,
Collection collection, Collection collection,
List<Map<String,String>> metadata_configs) { List<Map<String,String>> metadata_configs,
HarvestedCollectionRest harvestedCollectionRest = this.fromModel(obj); Projection projection) {
HarvestedCollectionRest harvestedCollectionRest = this.convert(obj, projection);
// Add collectionRest to the empty HarvestedCollectionRest so that we can use its uuid later in the linkFactory // Add collectionRest to the empty HarvestedCollectionRest so that we can use its uuid later in the linkFactory
if (obj == null) { if (obj == null) {
harvestedCollectionRest.setCollection(collectionConverter.fromModel(collection)); harvestedCollectionRest.setCollection(converter.toRest(collection, projection));
} }
HarvesterMetadataRest harvesterMetadataRest = new HarvesterMetadataRest(); HarvesterMetadataRest harvesterMetadataRest = new HarvesterMetadataRest();
harvesterMetadataRest.setProjection(projection);
harvesterMetadataRest.setConfigs(metadata_configs); harvesterMetadataRest.setConfigs(metadata_configs);
harvestedCollectionRest.setMetadataConfigs(harvesterMetadataRest); harvestedCollectionRest.setMetadataConfigs(harvesterMetadataRest);
return harvestedCollectionRest; return harvestedCollectionRest;
} }
@Override @Override
public HarvestedCollection toModel(HarvestedCollectionRest obj) { public Class<HarvestedCollection> getModelClass() {
throw new NotImplementedException(); return HarvestedCollection.class;
} }
} }

View File

@@ -26,6 +26,5 @@ public interface IndexableObjectConverter<M extends IndexableObject,
* the IndexableObject to check * the IndexableObject to check
* @return true if the actual converter implementation is able to manage the supplied IndexableObject * @return true if the actual converter implementation is able to manage the supplied IndexableObject
*/ */
public boolean supportsModel(IndexableObject idxo); boolean supportsModel(IndexableObject idxo);
}
}

View File

@@ -7,26 +7,19 @@
*/ */
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.model.BundleRest;
import org.dspace.app.rest.model.ItemRest; import org.dspace.app.rest.model.ItemRest;
import org.dspace.app.rest.model.RelationshipRest; import org.dspace.app.rest.model.MetadataValueList;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.projection.Projection;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.Relationship;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.RelationshipService;
import org.dspace.core.Context;
import org.dspace.discovery.IndexableObject; import org.dspace.discovery.IndexableObject;
import org.dspace.services.RequestService;
import org.dspace.services.model.Request;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -38,98 +31,52 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
public class ItemConverter public class ItemConverter
extends DSpaceObjectConverter<org.dspace.content.Item, org.dspace.app.rest.model.ItemRest> extends DSpaceObjectConverter<Item, ItemRest>
implements IndexableObjectConverter<Item, ItemRest> { implements IndexableObjectConverter<Item, ItemRest> {
@Autowired(required = true)
private CollectionConverter collectionConverter;
@Autowired(required = true)
private BundleConverter bundleConverter;
@Autowired @Autowired
private RequestService requestService; private ConverterService converter;
@Autowired
private RelationshipService relationshipService;
@Autowired
private RelationshipConverter relationshipConverter;
@Autowired @Autowired
private ItemService itemService; private ItemService itemService;
@Autowired
private MetadataConverter metadataConverter;
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ItemConverter.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ItemConverter.class);
@Override @Override
public ItemRest fromModel(org.dspace.content.Item obj) { public ItemRest convert(Item obj, Projection projection) {
ItemRest item = super.fromModel(obj); ItemRest item = super.convert(obj, projection);
item.setInArchive(obj.isArchived()); item.setInArchive(obj.isArchived());
item.setDiscoverable(obj.isDiscoverable()); item.setDiscoverable(obj.isDiscoverable());
item.setWithdrawn(obj.isWithdrawn()); item.setWithdrawn(obj.isWithdrawn());
item.setLastModified(obj.getLastModified()); item.setLastModified(obj.getLastModified());
try { Collection owningCollection = obj.getOwningCollection();
Collection c = obj.getOwningCollection(); if (owningCollection != null) {
if (c != null) { item.setOwningCollection(converter.toRest(owningCollection, projection));
item.setOwningCollection(collectionConverter.fromModel(c));
}
} catch (Exception e) {
log.error("Error setting owning collection for item" + item.getHandle(), e);
} }
try { Collection templateItemOf = obj.getTemplateItemOf();
Collection c = obj.getTemplateItemOf(); if (templateItemOf != null) {
if (c != null) { item.setTemplateItemOf(converter.toRest(templateItemOf, projection));
item.setTemplateItemOf(collectionConverter.fromModel(c));
}
} catch (Exception e) {
log.error("Error setting template item of for item " + item.getHandle(), e);
} }
item.setBundles(obj.getBundles() item.setBundles(obj.getBundles()
.stream() .stream()
.map(x -> bundleConverter.fromModel(x)) .map(x -> (BundleRest) converter.toRest(x, projection))
.collect(Collectors.toList())); .collect(Collectors.toList()));
List<Relationship> relationships = new LinkedList<>(); List<MetadataValue> fullList = itemService.getMetadata(obj, Item.ANY, Item.ANY, Item.ANY, Item.ANY, true);
try { MetadataValueList metadataValues = new MetadataValueList(fullList);
Context context; item.setMetadata(converter.toRest(metadataValues, projection));
Request currentRequest = requestService.getCurrentRequest();
if (currentRequest != null) {
HttpServletRequest request = currentRequest.getHttpServletRequest();
context = ContextUtil.obtainContext(request);
} else {
context = new Context();
}
relationships = relationshipService.findByItem(context, obj);
} catch (SQLException e) {
log.error("Error retrieving relationships for item " + item.getHandle(), e);
}
List<RelationshipRest> relationshipRestList = new LinkedList<>();
for (Relationship relationship : relationships) {
RelationshipRest relationshipRest = relationshipConverter.fromModel(relationship);
relationshipRestList.add(relationshipRest);
}
item.setRelationships(relationshipRestList);
List<MetadataValue> fullList = new LinkedList<>();
fullList = itemService.getMetadata(obj, Item.ANY, Item.ANY, Item.ANY, Item.ANY, true);
item.setMetadata(metadataConverter.convert(fullList));
return item; return item;
} }
@Override
public org.dspace.content.Item toModel(ItemRest obj) {
// TODO Auto-generated method stub
return null;
}
@Override @Override
protected ItemRest newInstance() { protected ItemRest newInstance() {
return new ItemRest(); return new ItemRest();
} }
@Override @Override
protected Class<Item> getModelClass() { public Class<Item> getModelClass() {
return Item.class; return Item.class;
} }

View File

@@ -17,7 +17,9 @@ import java.util.TreeSet;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.dspace.app.rest.model.MetadataRest; import org.dspace.app.rest.model.MetadataRest;
import org.dspace.app.rest.model.MetadataValueList;
import org.dspace.app.rest.model.MetadataValueRest; import org.dspace.app.rest.model.MetadataValueRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.content.Item; import org.dspace.content.Item;
@@ -26,39 +28,33 @@ import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.DSpaceObjectService; import org.dspace.content.service.DSpaceObjectService;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
* Converter to translate between lists of domain {@link MetadataValue}s and {@link MetadataRest} representations. * Converter to translate between lists of domain {@link MetadataValue}s and {@link MetadataRest} representations.
*/ */
@Component @Component
public class MetadataConverter implements Converter<List<MetadataValue>, MetadataRest> { public class MetadataConverter implements DSpaceConverter<MetadataValueList, MetadataRest> {
@Autowired @Autowired
private ContentServiceFactory contentServiceFactory; private ContentServiceFactory contentServiceFactory;
@Autowired @Autowired
private MetadataValueConverter valueConverter; private ConverterService converter;
/**
* Gets a rest representation of the given list of domain metadata values.
*
* @param metadataValueList the domain values.
* @return the rest representation.
*/
@Override @Override
public MetadataRest convert(List<MetadataValue> metadataValueList) { public MetadataRest convert(MetadataValueList metadataValues,
Projection projection) {
// Convert each value to a DTO while retaining place order in a map of key -> SortedSet // Convert each value to a DTO while retaining place order in a map of key -> SortedSet
Map<String, SortedSet<MetadataValueRest>> mapOfSortedSets = new HashMap<>(); Map<String, SortedSet<MetadataValueRest>> mapOfSortedSets = new HashMap<>();
for (MetadataValue metadataValue : metadataValueList) { for (MetadataValue metadataValue : metadataValues) {
String key = metadataValue.getMetadataField().toString('.'); String key = metadataValue.getMetadataField().toString('.');
SortedSet<MetadataValueRest> set = mapOfSortedSets.get(key); SortedSet<MetadataValueRest> set = mapOfSortedSets.get(key);
if (set == null) { if (set == null) {
set = new TreeSet<>(Comparator.comparingInt(MetadataValueRest::getPlace)); set = new TreeSet<>(Comparator.comparingInt(MetadataValueRest::getPlace));
mapOfSortedSets.put(key, set); mapOfSortedSets.put(key, set);
} }
set.add(valueConverter.convert(metadataValue)); set.add(converter.toRest(metadataValue, projection));
} }
MetadataRest metadataRest = new MetadataRest(); MetadataRest metadataRest = new MetadataRest();
@@ -72,6 +68,11 @@ public class MetadataConverter implements Converter<List<MetadataValue>, Metadat
return metadataRest; return metadataRest;
} }
@Override
public Class<MetadataValueList> getModelClass() {
return MetadataValueList.class;
}
/** /**
* Sets a DSpace object's domain metadata values from a rest representation. * Sets a DSpace object's domain metadata values from a rest representation.
* *

View File

@@ -8,6 +8,8 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.MetadataFieldRest; import org.dspace.app.rest.model.MetadataFieldRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.MetadataField;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -18,24 +20,24 @@ import org.springframework.stereotype.Component;
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@Component @Component
public class MetadataFieldConverter implements DSpaceConverter<org.dspace.content.MetadataField, MetadataFieldRest> { public class MetadataFieldConverter implements DSpaceConverter<MetadataField, MetadataFieldRest> {
@Autowired(required = true) @Autowired
private MetadataSchemaConverter metadataSchemaConverter; private ConverterService converter;
@Override @Override
public MetadataFieldRest fromModel(org.dspace.content.MetadataField obj) { public MetadataFieldRest convert(MetadataField obj, Projection projection) {
MetadataFieldRest field = new MetadataFieldRest(); MetadataFieldRest field = new MetadataFieldRest();
field.setProjection(projection);
field.setId(obj.getID()); field.setId(obj.getID());
field.setElement(obj.getElement()); field.setElement(obj.getElement());
field.setQualifier(obj.getQualifier()); field.setQualifier(obj.getQualifier());
field.setScopeNote(obj.getScopeNote()); field.setScopeNote(obj.getScopeNote());
field.setSchema(metadataSchemaConverter.convert(obj.getMetadataSchema())); field.setSchema(converter.toRest(obj.getMetadataSchema(), projection));
return field; return field;
} }
@Override @Override
public org.dspace.content.MetadataField toModel(MetadataFieldRest obj) { public Class<MetadataField> getModelClass() {
// TODO Auto-generated method stub return MetadataField.class;
return null;
} }
} }

View File

@@ -8,6 +8,8 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.MetadataSchemaRest; import org.dspace.app.rest.model.MetadataSchemaRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.MetadataSchema;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
@@ -17,10 +19,11 @@ import org.springframework.stereotype.Component;
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@Component @Component
public class MetadataSchemaConverter implements DSpaceConverter<org.dspace.content.MetadataSchema, MetadataSchemaRest> { public class MetadataSchemaConverter implements DSpaceConverter<MetadataSchema, MetadataSchemaRest> {
@Override @Override
public MetadataSchemaRest fromModel(org.dspace.content.MetadataSchema obj) { public MetadataSchemaRest convert(MetadataSchema obj, Projection projection) {
MetadataSchemaRest schema = new MetadataSchemaRest(); MetadataSchemaRest schema = new MetadataSchemaRest();
schema.setProjection(projection);
schema.setId(obj.getID()); schema.setId(obj.getID());
schema.setNamespace(obj.getNamespace()); schema.setNamespace(obj.getNamespace());
schema.setPrefix(obj.getName()); schema.setPrefix(obj.getName());
@@ -28,8 +31,7 @@ public class MetadataSchemaConverter implements DSpaceConverter<org.dspace.conte
} }
@Override @Override
public org.dspace.content.MetadataSchema toModel(MetadataSchemaRest obj) { public Class<MetadataSchema> getModelClass() {
// TODO Auto-generated method stub return MetadataSchema.class;
return null;
} }
} }

View File

@@ -8,24 +8,18 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.MetadataValueRest; import org.dspace.app.rest.model.MetadataValueRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
* Converter to translate between domain {@link MetadataValue}s and {@link MetadataValueRest} representations. * Converter to translate between domain {@link MetadataValue}s and {@link MetadataValueRest} representations.
*/ */
@Component @Component
public class MetadataValueConverter implements Converter<MetadataValue, MetadataValueRest> { public class MetadataValueConverter implements DSpaceConverter<MetadataValue, MetadataValueRest> {
/**
* Gets a rest representation of the given domain metadata value.
*
* @param metadataValue the domain value.
* @return the rest representation.
*/
@Override @Override
public MetadataValueRest convert(MetadataValue metadataValue) { public MetadataValueRest convert(MetadataValue metadataValue, Projection projection) {
MetadataValueRest metadataValueRest = new MetadataValueRest(); MetadataValueRest metadataValueRest = new MetadataValueRest();
metadataValueRest.setValue(metadataValue.getValue()); metadataValueRest.setValue(metadataValue.getValue());
metadataValueRest.setLanguage(metadataValue.getLanguage()); metadataValueRest.setLanguage(metadataValue.getLanguage());
@@ -34,4 +28,9 @@ public class MetadataValueConverter implements Converter<MetadataValue, Metadata
metadataValueRest.setPlace(metadataValue.getPlace()); metadataValueRest.setPlace(metadataValue.getPlace());
return metadataValueRest; return metadataValueRest;
} }
@Override
public Class<MetadataValue> getModelClass() {
return MetadataValue.class;
}
} }

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.PoolTaskRest; import org.dspace.app.rest.model.PoolTaskRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.discovery.IndexableObject; import org.dspace.discovery.IndexableObject;
import org.dspace.xmlworkflow.storedcomponents.PoolTask; import org.dspace.xmlworkflow.storedcomponents.PoolTask;
import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem; import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
@@ -25,26 +26,21 @@ public class PoolTaskConverter
implements IndexableObjectConverter<PoolTask, org.dspace.app.rest.model.PoolTaskRest> { implements IndexableObjectConverter<PoolTask, org.dspace.app.rest.model.PoolTaskRest> {
@Autowired @Autowired
private WorkflowItemConverter workflowItemConverter; private ConverterService converter;
@Autowired
private EPersonConverter epersonConverter;
@Autowired
private GroupConverter groupConverter;
@Override @Override
public PoolTaskRest fromModel(PoolTask obj) { public PoolTaskRest convert(PoolTask obj, Projection projection) {
PoolTaskRest taskRest = new PoolTaskRest(); PoolTaskRest taskRest = new PoolTaskRest();
taskRest.setProjection(projection);
XmlWorkflowItem witem = obj.getWorkflowItem(); XmlWorkflowItem witem = obj.getWorkflowItem();
taskRest.setId(obj.getID()); taskRest.setId(obj.getID());
taskRest.setWorkflowitem(workflowItemConverter.convert(witem)); taskRest.setWorkflowitem(converter.toRest(witem, projection));
if (obj.getEperson() != null) { if (obj.getEperson() != null) {
taskRest.setEperson(epersonConverter.convert(obj.getEperson())); taskRest.setEperson(converter.toRest(obj.getEperson(), projection));
} }
if (obj.getGroup() != null) { if (obj.getGroup() != null) {
taskRest.setGroup(groupConverter.convert(obj.getGroup())); taskRest.setGroup(converter.toRest(obj.getGroup(), projection));
} }
taskRest.setAction(obj.getActionID()); taskRest.setAction(obj.getActionID());
taskRest.setStep(obj.getStepID()); taskRest.setStep(obj.getStepID());
@@ -52,8 +48,8 @@ public class PoolTaskConverter
} }
@Override @Override
public PoolTask toModel(PoolTaskRest obj) { public Class<PoolTask> getModelClass() {
return null; return PoolTask.class;
} }
@Override @Override
@@ -61,4 +57,4 @@ public class PoolTaskConverter
return object instanceof PoolTask; return object instanceof PoolTask;
} }
} }

View File

@@ -5,13 +5,13 @@
* *
* http://www.dspace.org/license/ * http://www.dspace.org/license/
*/ */
package org.dspace.app.rest.converter.processes; package org.dspace.app.rest.converter;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.dspace.app.rest.converter.DSpaceConverter; import org.dspace.app.rest.model.ParameterValueRest;
import org.dspace.app.rest.converter.DSpaceRunnableParameterConverter;
import org.dspace.app.rest.model.ProcessRest; import org.dspace.app.rest.model.ProcessRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.scripts.Process; import org.dspace.scripts.Process;
import org.dspace.scripts.service.ProcessService; import org.dspace.scripts.service.ProcessService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -24,14 +24,15 @@ import org.springframework.stereotype.Component;
public class ProcessConverter implements DSpaceConverter<Process, ProcessRest> { public class ProcessConverter implements DSpaceConverter<Process, ProcessRest> {
@Autowired @Autowired
private ProcessService processService; private ConverterService converter;
@Autowired @Autowired
private DSpaceRunnableParameterConverter dSpaceRunnableParameterConverter; private ProcessService processService;
@Override @Override
public ProcessRest fromModel(Process process) { public ProcessRest convert(Process process, Projection projection) {
ProcessRest processRest = new ProcessRest(); ProcessRest processRest = new ProcessRest();
processRest.setProjection(projection);
processRest.setId(process.getID()); processRest.setId(process.getID());
processRest.setScriptName(process.getName()); processRest.setScriptName(process.getName());
processRest.setProcessId(process.getID()); processRest.setProcessId(process.getID());
@@ -39,14 +40,13 @@ public class ProcessConverter implements DSpaceConverter<Process, ProcessRest> {
processRest.setProcessStatus(process.getProcessStatus()); processRest.setProcessStatus(process.getProcessStatus());
processRest.setStartTime(process.getStartTime()); processRest.setStartTime(process.getStartTime());
processRest.setEndTime(process.getFinishedTime()); processRest.setEndTime(process.getFinishedTime());
processRest.setParameterRestList( processRest.setParameterRestList(processService.getParameters(process).stream()
processService.getParameters(process).stream().map(x -> dSpaceRunnableParameterConverter.fromModel(x)) .map(x -> (ParameterValueRest) converter.toRest(x, projection)).collect(Collectors.toList()));
.collect(Collectors.toList()));
return processRest; return processRest;
} }
@Override @Override
public Process toModel(ProcessRest obj) { public Class<Process> getModelClass() {
return null; return Process.class;
} }
} }

View File

@@ -8,10 +8,10 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.RelationshipRest; import org.dspace.app.rest.model.RelationshipRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.Relationship; import org.dspace.content.Relationship;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/** /**
* This converter is responsible for transforming the model representation of an Relationship to the REST * This converter is responsible for transforming the model representation of an Relationship to the REST
@@ -21,20 +21,15 @@ import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class RelationshipConverter implements DSpaceConverter<Relationship, RelationshipRest> { public class RelationshipConverter implements DSpaceConverter<Relationship, RelationshipRest> {
@Autowired @Autowired
private RelationshipTypeConverter relationshipTypeConverter; private ConverterService converter;
@Override
/** public RelationshipRest convert(Relationship obj, Projection projection) {
* This method converts the Relationship model object that is passed along in the params to the
* REST representation of this object
* @param obj The Relationship model object to be converted
* @return The Relationship REST object that is made from the model object
*/
public RelationshipRest fromModel(Relationship obj) {
RelationshipRest relationshipRest = new RelationshipRest(); RelationshipRest relationshipRest = new RelationshipRest();
relationshipRest.setProjection(projection);
relationshipRest.setId(obj.getID()); relationshipRest.setId(obj.getID());
relationshipRest.setLeftId(obj.getLeftItem().getID()); relationshipRest.setLeftId(obj.getLeftItem().getID());
relationshipRest.setRelationshipType(relationshipTypeConverter.fromModel(obj.getRelationshipType())); relationshipRest.setRelationshipType(converter.toRest(obj.getRelationshipType(), projection));
relationshipRest.setRightId(obj.getRightItem().getID()); relationshipRest.setRightId(obj.getRightItem().getID());
relationshipRest.setLeftPlace(obj.getLeftPlace()); relationshipRest.setLeftPlace(obj.getLeftPlace());
relationshipRest.setRightPlace(obj.getRightPlace()); relationshipRest.setRightPlace(obj.getRightPlace());
@@ -43,13 +38,8 @@ public class RelationshipConverter implements DSpaceConverter<Relationship, Rela
return relationshipRest; return relationshipRest;
} }
/** @Override
* This method converts the Relationship REST object that is passed along in the params to the model public Class<Relationship> getModelClass() {
* representation of this object return Relationship.class;
* @param obj The Relationship REST object to be converted
* @return The Relationship model object that is made from the REST object
*/
public Relationship toModel(RelationshipRest obj) {
throw new NotImplementedException();
} }
} }

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.RelationshipTypeRest; import org.dspace.app.rest.model.RelationshipTypeRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.RelationshipType; import org.dspace.content.RelationshipType;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -20,16 +21,12 @@ import org.springframework.stereotype.Component;
public class RelationshipTypeConverter implements DSpaceConverter<RelationshipType, RelationshipTypeRest> { public class RelationshipTypeConverter implements DSpaceConverter<RelationshipType, RelationshipTypeRest> {
@Autowired @Autowired
private EntityTypeConverter entityTypeConverter; private ConverterService converter;
/** @Override
* This method converts the RelationshipType model object that is passed along in the params to the public RelationshipTypeRest convert(RelationshipType obj, Projection projection) {
* REST representation of this object
* @param obj The RelationshipType model object to be converted
* @return The RelationshipType REST object that is made from the model object
*/
public RelationshipTypeRest fromModel(RelationshipType obj) {
RelationshipTypeRest relationshipTypeRest = new RelationshipTypeRest(); RelationshipTypeRest relationshipTypeRest = new RelationshipTypeRest();
relationshipTypeRest.setProjection(projection);
relationshipTypeRest.setId(obj.getID()); relationshipTypeRest.setId(obj.getID());
relationshipTypeRest.setLeftwardType(obj.getLeftwardType()); relationshipTypeRest.setLeftwardType(obj.getLeftwardType());
@@ -38,20 +35,14 @@ public class RelationshipTypeConverter implements DSpaceConverter<RelationshipTy
relationshipTypeRest.setLeftMaxCardinality(obj.getLeftMaxCardinality()); relationshipTypeRest.setLeftMaxCardinality(obj.getLeftMaxCardinality());
relationshipTypeRest.setRightMinCardinality(obj.getRightMinCardinality()); relationshipTypeRest.setRightMinCardinality(obj.getRightMinCardinality());
relationshipTypeRest.setRightMaxCardinality(obj.getRightMaxCardinality()); relationshipTypeRest.setRightMaxCardinality(obj.getRightMaxCardinality());
relationshipTypeRest.setLeftType(entityTypeConverter.fromModel(obj.getLeftType())); relationshipTypeRest.setLeftType(converter.toRest(obj.getLeftType(), projection));
relationshipTypeRest.setRightType(entityTypeConverter.fromModel(obj.getRightType())); relationshipTypeRest.setRightType(converter.toRest(obj.getRightType(), projection));
return relationshipTypeRest; return relationshipTypeRest;
} }
/** @Override
* This method converts the RelationshipType REST object that is passed along in the params to the model public Class<RelationshipType> getModelClass() {
* representation of this object return RelationshipType.class;
* @param obj The RelationshipType REST object to be converted
* @return The RelationshipType model object that is made from the REST object
*/
public RelationshipType toModel(RelationshipTypeRest obj) {
return null;
} }
} }

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.ResourcePolicyRest; import org.dspace.app.rest.model.ResourcePolicyRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.authorize.ResourcePolicy; import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.service.ResourcePolicyService; import org.dspace.authorize.service.ResourcePolicyService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -26,9 +27,10 @@ public class ResourcePolicyConverter implements DSpaceConverter<ResourcePolicy,
ResourcePolicyService resourcePolicyService; ResourcePolicyService resourcePolicyService;
@Override @Override
public ResourcePolicyRest fromModel(ResourcePolicy obj) { public ResourcePolicyRest convert(ResourcePolicy obj, Projection projection) {
ResourcePolicyRest model = new ResourcePolicyRest(); ResourcePolicyRest model = new ResourcePolicyRest();
model.setProjection(projection);
model.setId(obj.getID()); model.setId(obj.getID());
@@ -52,9 +54,8 @@ public class ResourcePolicyConverter implements DSpaceConverter<ResourcePolicy,
} }
@Override @Override
public ResourcePolicy toModel(ResourcePolicyRest obj) { public Class<ResourcePolicy> getModelClass() {
// TODO Auto-generated method stub return ResourcePolicy.class;
return null;
} }
} }

View File

@@ -7,10 +7,15 @@
*/ */
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.converter.processes.ParameterConverter; import java.util.LinkedList;
import java.util.List;
import org.apache.commons.cli.Option;
import org.apache.commons.collections4.CollectionUtils;
import org.dspace.app.rest.model.ParameterRest;
import org.dspace.app.rest.model.ScriptRest; import org.dspace.app.rest.model.ScriptRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.scripts.DSpaceRunnable; import org.dspace.scripts.DSpaceRunnable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
@@ -20,21 +25,29 @@ import org.springframework.stereotype.Component;
@Component @Component
public class ScriptConverter implements DSpaceConverter<DSpaceRunnable, ScriptRest> { public class ScriptConverter implements DSpaceConverter<DSpaceRunnable, ScriptRest> {
@Autowired
private ParameterConverter parameterConverter;
@Override @Override
public ScriptRest fromModel(DSpaceRunnable script) { public ScriptRest convert(DSpaceRunnable script, Projection projection) {
ScriptRest scriptRest = new ScriptRest(); ScriptRest scriptRest = new ScriptRest();
scriptRest.setProjection(projection);
scriptRest.setDescription(script.getDescription()); scriptRest.setDescription(script.getDescription());
scriptRest.setId(script.getName()); scriptRest.setId(script.getName());
scriptRest.setName(script.getName()); scriptRest.setName(script.getName());
scriptRest.setParameterRestList(parameterConverter.convertOptionsToParameterRestList(script.getOptions()));
List<ParameterRest> parameterRestList = new LinkedList<>();
for (Option option : CollectionUtils.emptyIfNull(script.getOptions().getOptions())) {
ParameterRest parameterRest = new ParameterRest();
parameterRest.setDescription(option.getDescription());
parameterRest.setName((option.getOpt() != null ? "-" + option.getOpt() : "--" + option.getLongOpt()));
parameterRest.setType(((Class) option.getType()).getSimpleName());
parameterRestList.add(parameterRest);
}
scriptRest.setParameterRestList(parameterRestList);
return scriptRest; return scriptRest;
} }
@Override @Override
public DSpaceRunnable toModel(ScriptRest obj) { public Class<DSpaceRunnable> getModelClass() {
return null; return DSpaceRunnable.class;
} }
} }

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.SiteRest; import org.dspace.app.rest.model.SiteRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.Site; import org.dspace.content.Site;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -18,16 +19,11 @@ import org.springframework.stereotype.Component;
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@Component @Component
public class SiteConverter public class SiteConverter extends DSpaceObjectConverter<Site, SiteRest> {
extends DSpaceObjectConverter<org.dspace.content.Site, org.dspace.app.rest.model.SiteRest> {
@Override
public org.dspace.content.Site toModel(org.dspace.app.rest.model.SiteRest obj) {
return (org.dspace.content.Site) super.toModel(obj);
}
@Override @Override
public SiteRest fromModel(org.dspace.content.Site obj) { public SiteRest convert(Site obj, Projection projection) {
return (SiteRest) super.fromModel(obj); return super.convert(obj, projection);
} }
@Override @Override
@@ -36,7 +32,7 @@ public class SiteConverter
} }
@Override @Override
protected Class<Site> getModelClass() { public Class<Site> getModelClass() {
return Site.class; return Site.class;
} }
} }

View File

@@ -13,11 +13,11 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.model.CollectionRest; import org.dspace.app.rest.model.CollectionRest;
import org.dspace.app.rest.model.SubmissionDefinitionRest; import org.dspace.app.rest.model.SubmissionDefinitionRest;
import org.dspace.app.rest.model.SubmissionSectionRest; import org.dspace.app.rest.model.SubmissionSectionRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.ContextUtil; import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.util.SubmissionConfig; import org.dspace.app.util.SubmissionConfig;
import org.dspace.app.util.SubmissionConfigReaderException; import org.dspace.app.util.SubmissionConfigReaderException;
@@ -47,17 +47,18 @@ public class SubmissionDefinitionConverter implements DSpaceConverter<Submission
private RequestService requestService; private RequestService requestService;
@Autowired @Autowired
private CollectionConverter collectionConverter; private ConverterService converter;
@Override @Override
public SubmissionDefinitionRest fromModel(SubmissionConfig obj) { public SubmissionDefinitionRest convert(SubmissionConfig obj, Projection projection) {
SubmissionDefinitionRest sd = new SubmissionDefinitionRest(); SubmissionDefinitionRest sd = new SubmissionDefinitionRest();
sd.setProjection(projection);
sd.setName(obj.getSubmissionName()); sd.setName(obj.getSubmissionName());
sd.setDefaultConf(obj.isDefaultConf()); sd.setDefaultConf(obj.isDefaultConf());
List<SubmissionSectionRest> panels = new LinkedList<SubmissionSectionRest>(); List<SubmissionSectionRest> panels = new LinkedList<SubmissionSectionRest>();
for (int idx = 0; idx < obj.getNumberOfSteps(); idx++) { for (int idx = 0; idx < obj.getNumberOfSteps(); idx++) {
SubmissionStepConfig step = obj.getStep(idx); SubmissionStepConfig step = obj.getStep(idx);
SubmissionSectionRest sp = panelConverter.convert(step); SubmissionSectionRest sp = converter.toRest(step, projection);
panels.add(sp); panels.add(sp);
} }
@@ -68,8 +69,9 @@ public class SubmissionDefinitionConverter implements DSpaceConverter<Submission
List<Collection> collections = panelConverter.getSubmissionConfigReader() List<Collection> collections = panelConverter.getSubmissionConfigReader()
.getCollectionsBySubmissionConfig(context, .getCollectionsBySubmissionConfig(context,
obj.getSubmissionName()); obj.getSubmissionName());
List<CollectionRest> collectionsRest = collections.stream().map( DSpaceConverter<Collection, CollectionRest> cc = converter.getConverter(Collection.class);
(collection) -> collectionConverter.convert(collection)).collect(Collectors.toList()); List<CollectionRest> collectionsRest = collections.stream().map((collection) ->
cc.convert(collection, projection)).collect(Collectors.toList());
sd.setCollections(collectionsRest); sd.setCollections(collectionsRest);
} catch (SQLException | IllegalStateException | SubmissionConfigReaderException e) { } catch (SQLException | IllegalStateException | SubmissionConfigReaderException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
@@ -79,7 +81,7 @@ public class SubmissionDefinitionConverter implements DSpaceConverter<Submission
} }
@Override @Override
public SubmissionConfig toModel(SubmissionDefinitionRest obj) { public Class<SubmissionConfig> getModelClass() {
throw new NotImplementedException("Method not implemented"); return SubmissionConfig.class;
} }
} }

View File

@@ -11,7 +11,6 @@ import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.dspace.app.rest.model.ScopeEnum; import org.dspace.app.rest.model.ScopeEnum;
import org.dspace.app.rest.model.SubmissionFormFieldRest; import org.dspace.app.rest.model.SubmissionFormFieldRest;
@@ -22,6 +21,7 @@ import org.dspace.app.rest.model.SubmissionVisibilityRest;
import org.dspace.app.rest.model.VisibilityEnum; import org.dspace.app.rest.model.VisibilityEnum;
import org.dspace.app.rest.model.submit.SelectableMetadata; import org.dspace.app.rest.model.submit.SelectableMetadata;
import org.dspace.app.rest.model.submit.SelectableRelationship; import org.dspace.app.rest.model.submit.SelectableRelationship;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.repository.SubmissionFormRestRepository; import org.dspace.app.rest.repository.SubmissionFormRestRepository;
import org.dspace.app.rest.utils.AuthorityUtils; import org.dspace.app.rest.utils.AuthorityUtils;
import org.dspace.app.util.DCInput; import org.dspace.app.util.DCInput;
@@ -51,8 +51,9 @@ public class SubmissionFormConverter implements DSpaceConverter<DCInputSet, Subm
private SubmissionFormRestRepository submissionFormRestRepository; private SubmissionFormRestRepository submissionFormRestRepository;
@Override @Override
public SubmissionFormRest fromModel(DCInputSet obj) { public SubmissionFormRest convert(DCInputSet obj, Projection projection) {
SubmissionFormRest sd = new SubmissionFormRest(); SubmissionFormRest sd = new SubmissionFormRest();
sd.setProjection(projection);
sd.setName(obj.getFormName()); sd.setName(obj.getFormName());
DCInput[][] step = obj.getFields(); DCInput[][] step = obj.getFields();
List<SubmissionFormRowRest> rows = getPage(step, obj.getFormName()); List<SubmissionFormRowRest> rows = getPage(step, obj.getFormName());
@@ -203,7 +204,7 @@ public class SubmissionFormConverter implements DSpaceConverter<DCInputSet, Subm
} }
@Override @Override
public DCInputSet toModel(SubmissionFormRest obj) { public Class<DCInputSet> getModelClass() {
throw new NotImplementedException("Method not implemented"); return DCInputSet.class;
} }
} }

View File

@@ -11,6 +11,7 @@ import org.apache.logging.log4j.Logger;
import org.dspace.app.rest.model.SubmissionSectionRest; import org.dspace.app.rest.model.SubmissionSectionRest;
import org.dspace.app.rest.model.SubmissionVisibilityRest; import org.dspace.app.rest.model.SubmissionVisibilityRest;
import org.dspace.app.rest.model.VisibilityEnum; import org.dspace.app.rest.model.VisibilityEnum;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.util.SubmissionConfigReader; import org.dspace.app.util.SubmissionConfigReader;
import org.dspace.app.util.SubmissionConfigReaderException; import org.dspace.app.util.SubmissionConfigReaderException;
import org.dspace.app.util.SubmissionStepConfig; import org.dspace.app.util.SubmissionStepConfig;
@@ -30,8 +31,9 @@ public class SubmissionSectionConverter implements DSpaceConverter<SubmissionSte
private SubmissionConfigReader submissionConfigReader; private SubmissionConfigReader submissionConfigReader;
@Override @Override
public SubmissionSectionRest fromModel(SubmissionStepConfig step) { public SubmissionSectionRest convert(SubmissionStepConfig step, Projection projection) {
SubmissionSectionRest sp = new SubmissionSectionRest(); SubmissionSectionRest sp = new SubmissionSectionRest();
sp.setProjection(projection);
sp.setMandatory(step.isMandatory()); sp.setMandatory(step.isMandatory());
sp.setHeader(step.getHeading()); sp.setHeader(step.getHeading());
sp.setSectionType(step.getType()); sp.setSectionType(step.getType());
@@ -41,7 +43,6 @@ public class SubmissionSectionConverter implements DSpaceConverter<SubmissionSte
return sp; return sp;
} }
@Override
public SubmissionStepConfig toModel(SubmissionSectionRest obj) { public SubmissionStepConfig toModel(SubmissionSectionRest obj) {
SubmissionStepConfig step; SubmissionStepConfig step;
@@ -53,10 +54,15 @@ public class SubmissionSectionConverter implements DSpaceConverter<SubmissionSte
return step; return step;
} }
@Override
public Class<SubmissionStepConfig> getModelClass() {
return SubmissionStepConfig.class;
}
public SubmissionConfigReader getSubmissionConfigReader() throws SubmissionConfigReaderException { public SubmissionConfigReader getSubmissionConfigReader() throws SubmissionConfigReaderException {
if (submissionConfigReader == null) { if (submissionConfigReader == null) {
submissionConfigReader = new SubmissionConfigReader(); submissionConfigReader = new SubmissionConfigReader();
} }
return submissionConfigReader; return submissionConfigReader;
} }
} }

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.WorkflowItemRest; import org.dspace.app.rest.model.WorkflowItemRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.util.SubmissionConfigReaderException; import org.dspace.app.util.SubmissionConfigReaderException;
import org.dspace.discovery.IndexableObject; import org.dspace.discovery.IndexableObject;
import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem; import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
@@ -29,15 +30,16 @@ public class WorkflowItemConverter
} }
@Override @Override
public WorkflowItemRest fromModel(XmlWorkflowItem obj) { public WorkflowItemRest convert(XmlWorkflowItem obj, Projection projection) {
WorkflowItemRest witem = new WorkflowItemRest(); WorkflowItemRest witem = new WorkflowItemRest();
fillFromModel(obj, witem); witem.setProjection(projection);
fillFromModel(obj, witem, projection);
return witem; return witem;
} }
@Override @Override
public XmlWorkflowItem toModel(WorkflowItemRest obj) { public Class<XmlWorkflowItem> getModelClass() {
return null; return XmlWorkflowItem.class;
} }
@Override @Override

View File

@@ -8,6 +8,7 @@
package org.dspace.app.rest.converter; package org.dspace.app.rest.converter;
import org.dspace.app.rest.model.WorkspaceItemRest; import org.dspace.app.rest.model.WorkspaceItemRest;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.util.SubmissionConfigReaderException; import org.dspace.app.util.SubmissionConfigReaderException;
import org.dspace.content.WorkspaceItem; import org.dspace.content.WorkspaceItem;
import org.dspace.discovery.IndexableObject; import org.dspace.discovery.IndexableObject;
@@ -28,18 +29,22 @@ public class WorkspaceItemConverter
} }
@Override @Override
public WorkspaceItemRest fromModel(org.dspace.content.WorkspaceItem obj) { public WorkspaceItemRest convert(org.dspace.content.WorkspaceItem obj, Projection projection) {
WorkspaceItemRest witem = new WorkspaceItemRest(); WorkspaceItemRest witem = new WorkspaceItemRest();
witem.setProjection(projection);
fillFromModel(obj, witem); fillFromModel(obj, witem, projection);
return witem; return witem;
} }
@Override
public org.dspace.content.WorkspaceItem toModel(WorkspaceItemRest obj) { public org.dspace.content.WorkspaceItem toModel(WorkspaceItemRest obj) {
return null; return null;
} }
@Override
public Class<WorkspaceItem> getModelClass() {
return WorkspaceItem.class;
}
@Override @Override
public boolean supportsModel(IndexableObject object) { public boolean supportsModel(IndexableObject object) {
return object instanceof WorkspaceItem; return object instanceof WorkspaceItem;

View File

@@ -1,43 +0,0 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.converter.processes;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.collections4.CollectionUtils;
import org.dspace.app.rest.model.ParameterRest;
import org.springframework.stereotype.Component;
/**
* This converter will convert the Options of a script to a list of ParameterRest objects
*/
@Component
public class ParameterConverter {
/**
* This method will convert the Options of a script to a list of ParameterRest objects
* @param options The options of a script
* @return The resulting list of ParameterRest objects
*/
public List<ParameterRest> convertOptionsToParameterRestList(Options options) {
List<ParameterRest> listToReturn = new LinkedList<>();
for (Option option : CollectionUtils.emptyIfNull(options.getOptions())) {
ParameterRest parameterRest = new ParameterRest();
parameterRest.setDescription(option.getDescription());
parameterRest.setName((option.getOpt() != null ? "-" + option.getOpt() : "--" + option.getLongOpt()));
parameterRest.setType(((Class) option.getType()).getSimpleName());
listToReturn.add(parameterRest);
}
return listToReturn;
}
}

View File

@@ -41,14 +41,14 @@ public class AuthorityEntryHalLinkFactory extends HalLinkFactory<AuthorityEntryR
.findRel(null, null, AuthorityRest.CATEGORY, .findRel(null, null, AuthorityRest.CATEGORY,
English.plural(AuthorityRest.NAME), English.plural(AuthorityRest.NAME),
entry.getAuthorityName() + "/" + AuthorityRest.ENTRY, entry.getAuthorityName() + "/" + AuthorityRest.ENTRY,
entry.getOtherInformation().get(AuthorityUtils.RESERVED_KEYMAP_PARENT), null, null, entry.getOtherInformation().get(AuthorityUtils.RESERVED_KEYMAP_PARENT), null, null))
null)).toUriComponentsBuilder(); .toUriComponentsBuilder();
list.add(buildLink(AuthorityUtils.RESERVED_KEYMAP_PARENT, uriComponentsBuilder.build().toString())); list.add(buildLink(AuthorityUtils.RESERVED_KEYMAP_PARENT, uriComponentsBuilder.build().toString()));
} }
} }
String selfLinkString = linkTo( String selfLinkString = linkTo(
getMethodOn().findOne(entry.getCategory(), English.plural(entry.getType()), entry.getAuthorityName(), null)) getMethodOn().findOne(entry.getCategory(), English.plural(entry.getType()), entry.getAuthorityName()))
.toUriComponentsBuilder().build().toString() + "/entryValues/" + entry.getId(); .toUriComponentsBuilder().build().toString() + "/entryValues/" + entry.getId();
list.add(buildLink(Link.REL_SELF, selfLinkString)); list.add(buildLink(Link.REL_SELF, selfLinkString));
} }

View File

@@ -37,7 +37,7 @@ public class BrowseEntryHalLinkFactory extends HalLinkFactory<BrowseEntryResourc
UriComponentsBuilder baseLink = uriBuilder( UriComponentsBuilder baseLink = uriBuilder(
getMethodOn(bix.getCategory(), bix.getType()).findRel(null, null, bix.getCategory(), getMethodOn(bix.getCategory(), bix.getType()).findRel(null, null, bix.getCategory(),
English.plural(bix.getType()), bix.getId(), English.plural(bix.getType()), bix.getId(),
BrowseIndexRest.ITEMS, null, null, null)); BrowseIndexRest.ITEMS, null, null));
addFilterParams(baseLink, data); addFilterParams(baseLink, data);

View File

@@ -21,7 +21,6 @@ import org.dspace.app.rest.model.RestModel;
import org.dspace.app.rest.model.hateoas.DSpaceResource; import org.dspace.app.rest.model.hateoas.DSpaceResource;
import org.dspace.app.rest.utils.Utils; import org.dspace.app.rest.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.Link; import org.springframework.hateoas.Link;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -46,26 +45,33 @@ public class DSpaceResourceHalLinkFactory extends HalLinkFactory<DSpaceResource,
Method readMethod = pd.getReadMethod(); Method readMethod = pd.getReadMethod();
String name = pd.getName(); String name = pd.getName();
if (readMethod != null && !"class".equals(name)) { if (readMethod != null && !"class".equals(name)) {
LinkRest linkAnnotation = AnnotationUtils.findAnnotation(readMethod, LinkRest.class); LinkRest linkRest = utils.findLinkAnnotation(readMethod);
if (linkAnnotation != null) { if (linkRest != null) {
if (StringUtils.isNotBlank(linkAnnotation.name())) { if (StringUtils.isNotBlank(linkRest.name())) {
name = linkAnnotation.name(); name = linkRest.name();
} }
Link linkToSubResource = utils.linkToSubResource(data, name); Link linkToSubResource = utils.linkToSubResource(data, name);
// no method is specified to retrieve the linked object(s) so check if it is already here // no method is specified to retrieve the linked object(s) so check if it is already here
if (StringUtils.isBlank(linkAnnotation.method())) { if (StringUtils.isBlank(linkRest.method())) {
Object linkedObject = readMethod.invoke(data); Object linkedObject = readMethod.invoke(data);
if (linkedObject instanceof RestAddressableModel if (linkedObject instanceof RestAddressableModel
&& linkAnnotation.linkClass().isAssignableFrom(linkedObject.getClass())) { && linkRest.linkClass().isAssignableFrom(linkedObject.getClass())) {
linkToSubResource = utils linkToSubResource = utils
.linkToSingleResource((RestAddressableModel) linkedObject, name); .linkToSingleResource((RestAddressableModel) linkedObject, name);
} }
if (linkedObject != null || !linkAnnotation.optional()) { if (linkedObject != null || !linkRest.linkOptional() || !linkRest.embedOptional()) {
if (linkRest.linkOptional() && linkRest.embedOptional()
&& !halResource.getContent().getProjection()
.allowOptionalLink(halResource, linkRest)) {
continue; // projection disallows this optional method-level link
}
halResource.add(linkToSubResource); halResource.add(linkToSubResource);
} }
} }

View File

@@ -39,7 +39,7 @@ public class SubmissionSectionHalLinkFactory extends HalLinkFactory<SubmissionSe
UriComponentsBuilder uriComponentsBuilder = linkTo( UriComponentsBuilder uriComponentsBuilder = linkTo(
getMethodOn(SubmissionFormRest.CATEGORY, SubmissionFormRest.NAME) getMethodOn(SubmissionFormRest.CATEGORY, SubmissionFormRest.NAME)
.findRel(null, null, SubmissionFormRest.CATEGORY, English.plural(SubmissionFormRest.NAME), .findRel(null, null, SubmissionFormRest.CATEGORY, English.plural(SubmissionFormRest.NAME),
sd.getId(), "", null, null, null)) sd.getId(), "", null, null))
.toUriComponentsBuilder(); .toUriComponentsBuilder();
String uribuilder = uriComponentsBuilder.build().toString(); String uribuilder = uriComponentsBuilder.build().toString();
list.add( list.add(
@@ -49,7 +49,7 @@ public class SubmissionSectionHalLinkFactory extends HalLinkFactory<SubmissionSe
UriComponentsBuilder uriComponentsBuilder = linkTo( UriComponentsBuilder uriComponentsBuilder = linkTo(
getMethodOn(RestResourceController.class, SubmissionUploadRest.CATEGORY, SubmissionUploadRest.NAME) getMethodOn(RestResourceController.class, SubmissionUploadRest.CATEGORY, SubmissionUploadRest.NAME)
.findRel(null, null, SubmissionUploadRest.CATEGORY, English.plural(SubmissionUploadRest.NAME), .findRel(null, null, SubmissionUploadRest.CATEGORY, English.plural(SubmissionUploadRest.NAME),
sd.getId(), "", null, null, null)) sd.getId(), "", null, null))
.toUriComponentsBuilder(); .toUriComponentsBuilder();
String uribuilder = uriComponentsBuilder.build().toString(); String uribuilder = uriComponentsBuilder.build().toString();
list.add( list.add(

View File

@@ -27,7 +27,8 @@ import org.springframework.stereotype.Component;
public class EntityTypeHalLinkFactory extends HalLinkFactory<EntityTypeResource, RelationshipTypeRestController> { public class EntityTypeHalLinkFactory extends HalLinkFactory<EntityTypeResource, RelationshipTypeRestController> {
@Override @Override
protected void addLinks(EntityTypeResource halResource, Pageable pageable, LinkedList<Link> list) throws Exception { protected void addLinks(EntityTypeResource halResource, Pageable pageable, LinkedList<Link> list) throws Exception {
list.add(buildLink("relationshiptypes", getMethodOn().retrieve(halResource.getContent().getId(), null, null))); list.add(buildLink("relationshiptypes", getMethodOn().retrieve(
halResource.getContent().getId(), null, null)));
} }
@Override @Override

View File

@@ -29,10 +29,10 @@ public class RelationshipHalLinkFactory extends HalLinkFactory<RelationshipResou
throws Exception { throws Exception {
list.add(buildLink("leftItem", getMethodOn() list.add(buildLink("leftItem", getMethodOn()
.findOne(ItemRest.CATEGORY, English.plural(ItemRest.NAME), halResource.getContent().getLeftId(), null))); .findOne(ItemRest.CATEGORY, English.plural(ItemRest.NAME), halResource.getContent().getLeftId())));
list.add(buildLink("rightItem", getMethodOn() list.add(buildLink("rightItem", getMethodOn()
.findOne(ItemRest.CATEGORY, English.plural(ItemRest.NAME), halResource.getContent().getRightId(), null))); .findOne(ItemRest.CATEGORY, English.plural(ItemRest.NAME), halResource.getContent().getRightId())));
} }
@Override @Override

View File

@@ -35,10 +35,6 @@ public abstract class AInprogressSubmissionRest<T extends Serializable> extends
@JsonIgnore @JsonIgnore
private EPersonRest submitter; private EPersonRest submitter;
public AInprogressSubmissionRest() {
super();
}
public Date getLastModified() { public Date getLastModified() {
return lastModified; return lastModified;
} }
@@ -90,4 +86,4 @@ public abstract class AInprogressSubmissionRest<T extends Serializable> extends
this.collection = collection; this.collection = collection;
} }
} }

View File

@@ -56,7 +56,7 @@ public class AuthenticationStatusRest extends BaseObjectRest<Integer> {
} }
} }
@LinkRest(linkClass = EPersonRest.class, name = "eperson", optional = true) @LinkRest(linkClass = EPersonRest.class, name = "eperson", linkOptional = true)
@JsonIgnore @JsonIgnore
public EPersonRest getEPersonRest() { public EPersonRest getEPersonRest() {
return ePersonRest; return ePersonRest;
@@ -81,4 +81,4 @@ public class AuthenticationStatusRest extends BaseObjectRest<Integer> {
public void setOkay(boolean okay) { public void setOkay(boolean okay) {
this.okay = okay; this.okay = okay;
} }
} }

View File

@@ -17,7 +17,7 @@ import org.dspace.app.rest.RestResourceController;
* *
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
public class AuthorityEntryRest implements RestAddressableModel { public class AuthorityEntryRest extends RestAddressableModel {
public static final String NAME = "authorityEntry"; public static final String NAME = "authorityEntry";
private String id; private String id;
private String display; private String display;

View File

@@ -15,8 +15,19 @@ import org.dspace.app.rest.RestResourceController;
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@LinksRest(links = { @LinksRest(links = {
@LinkRest(name = AuthorityRest.ENTRIES, linkClass = AuthorityEntryRest.class, method = "query", optional = true), @LinkRest(name = AuthorityRest.ENTRIES,
@LinkRest(name = AuthorityRest.ENTRY, linkClass = AuthorityEntryRest.class, method = "getResource", optional = true) linkClass = AuthorityEntryRest.class,
method = "query",
embedOptional = true,
linkOptional = true
),
@LinkRest(
name = AuthorityRest.ENTRY,
linkClass = AuthorityEntryRest.class,
method = "getResource",
embedOptional = true,
linkOptional = true
)
}) })
public class AuthorityRest extends BaseObjectRest<String> { public class AuthorityRest extends BaseObjectRest<String> {

View File

@@ -21,7 +21,7 @@ import org.springframework.hateoas.Identifiable;
* @param <T> the class of the resource identifier * @param <T> the class of the resource identifier
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
public abstract class BaseObjectRest<T extends Serializable> implements Identifiable<T>, RestAddressableModel { public abstract class BaseObjectRest<T extends Serializable> extends RestAddressableModel implements Identifiable<T> {
protected T id; protected T id;

View File

@@ -101,4 +101,4 @@ public class BitstreamFormatRest extends BaseObjectRest<Integer> {
public Class getController() { public Class getController() {
return RestResourceController.class; return RestResourceController.class;
} }
} }

View File

@@ -19,9 +19,19 @@ import org.dspace.app.rest.RestResourceController;
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@LinksRest(links = { @LinksRest(links = {
@LinkRest(name = BrowseIndexRest.ITEMS, linkClass = ItemRest.class, method = "listBrowseItems"), @LinkRest(
@LinkRest(name = BrowseIndexRest.ENTRIES, linkClass = BrowseEntryRest.class, method = "listBrowseEntries", name = BrowseIndexRest.ITEMS,
optional = true) linkClass = ItemRest.class,
method = "listBrowseItems",
embedOptional = true
),
@LinkRest(
name = BrowseIndexRest.ENTRIES,
linkClass = BrowseEntryRest.class,
method = "listBrowseEntries",
embedOptional = true,
linkOptional = true
)
}) })
public class BrowseIndexRest extends BaseObjectRest<String> { public class BrowseIndexRest extends BaseObjectRest<String> {
private static final long serialVersionUID = -4870333170249999559L; private static final long serialVersionUID = -4870333170249999559L;

View File

@@ -92,4 +92,4 @@ public class ClaimedTaskRest extends BaseObjectRest<Integer> {
public void setWorkflowitem(WorkflowItemRest workflowitem) { public void setWorkflowitem(WorkflowItemRest workflowitem) {
this.workflowitem = workflowitem; this.workflowitem = workflowitem;
} }
} }

View File

@@ -18,8 +18,13 @@ import com.fasterxml.jackson.annotation.JsonProperty;
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@LinksRest(links = { @LinksRest(links = {
@LinkRest(name = CollectionRest.LICENSE, linkClass = LicenseRest.class, method = "getLicenseCollection", optional @LinkRest(
= true) name = CollectionRest.LICENSE,
linkClass = LicenseRest.class,
method = "getLicenseCollection",
embedOptional = true,
linkOptional = true
)
}) })
public class CollectionRest extends DSpaceObjectRest { public class CollectionRest extends DSpaceObjectRest {
public static final String NAME = "collection"; public static final String NAME = "collection";

View File

@@ -11,7 +11,6 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import org.dspace.app.rest.DiscoveryRestController; import org.dspace.app.rest.DiscoveryRestController;
import org.dspace.app.rest.parameter.SearchFilter; import org.dspace.app.rest.parameter.SearchFilter;

View File

@@ -123,4 +123,4 @@ public class EPersonRest extends DSpaceObjectRest {
return RestResourceController.class; return RestResourceController.class;
} }
} }

View File

@@ -156,7 +156,7 @@ public class HarvestedCollectionRest extends BaseObjectRest<Integer> {
this.lastHarvested = lastHarvested; this.lastHarvested = lastHarvested;
} }
@LinkRest(linkClass = HarvesterMetadataRest.class, name = "harvestermetadata", optional = true) @LinkRest(linkClass = HarvesterMetadataRest.class, name = "harvestermetadata", linkOptional = true)
@JsonIgnore @JsonIgnore
public HarvesterMetadataRest getMetadataConfigs() { public HarvesterMetadataRest getMetadataConfigs() {
return metadata_configs; return metadata_configs;

View File

@@ -18,10 +18,19 @@ import com.fasterxml.jackson.annotation.JsonProperty;
* *
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@LinksRest(links = {
@LinkRest(
name = ItemRest.RELATIONSHIPS,
linkClass = RelationshipRest.class,
method = "getItemRelationships",
embedOptional = true
)
})
public class ItemRest extends DSpaceObjectRest { public class ItemRest extends DSpaceObjectRest {
public static final String NAME = "item"; public static final String NAME = "item";
public static final String PLURAL_NAME = "items"; public static final String PLURAL_NAME = "items";
public static final String CATEGORY = RestAddressableModel.CORE; public static final String CATEGORY = RestAddressableModel.CORE;
public static final String RELATIONSHIPS = "relationships";
private boolean inArchive = false; private boolean inArchive = false;
private boolean discoverable = false; private boolean discoverable = false;
private boolean withdrawn = false; private boolean withdrawn = false;
@@ -32,7 +41,6 @@ public class ItemRest extends DSpaceObjectRest {
private CollectionRest templateItemOf; private CollectionRest templateItemOf;
List<BundleRest> bundles; List<BundleRest> bundles;
List<RelationshipRest> relationships;
@Override @Override
public String getCategory() { public String getCategory() {
@@ -102,14 +110,4 @@ public class ItemRest extends DSpaceObjectRest {
public void setBundles(List<BundleRest> bundles) { public void setBundles(List<BundleRest> bundles) {
this.bundles = bundles; this.bundles = bundles;
} }
@LinkRest(linkClass = RelationshipRest.class)
@JsonIgnore
public List<RelationshipRest> getRelationships() {
return relationships;
}
public void setRelationships(List<RelationshipRest> relationships) {
this.relationships = relationships;
}
} }

View File

@@ -13,8 +13,15 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import org.dspace.app.rest.model.hateoas.HALResource;
import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.repository.LinkRestRepository;
import org.dspace.app.rest.utils.Utils;
import org.springframework.stereotype.Component;
/** /**
* This annotation allows to specify the direct linked REST entities * Class or method-level annotation to control linking/embedding behavior when a {@link RestModel}
* is wrapped as a {@link HALResource}
* *
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
@@ -22,11 +29,71 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
public @interface LinkRest { public @interface LinkRest {
/**
* The rel name to use for the link and/or embed.
* <p>
* This is optional if the annotation is used at the method level. If unspecified at the method level,
* the bean name (inferred by the the name of the method) will be used as the name.
* </p>
* <p>
* This is required if the annotation is used at the class level.
* </p>
*
* @return the name, or the empty string if unspecified by the annotation.
*/
String name() default ""; String name() default "";
/**
* The name of the method to invoke in the associated link repository.
* <p>
* When this is specified, whether at the class or method level, the value of the resource must be provided
* by a {@link LinkRestRepository}, which is found by its {@link Component} name. See
* {@link Utils#getResourceRepository(String, String)}} for details.
* </p>
*
* @return the method name, or the empty string if unspecified by the annotation.
*/
String method() default ""; String method() default "";
/**
* The class of object returned by invoking the link method. If a list or page is returned, this should
* specify the inner type.
*
* @return the class.
*/
Class linkClass(); Class linkClass();
boolean optional() default false; /**
* Tells whether embedding the resource indicated by this link is optional.
* <p>
* If false (the default), it means the resource will always be embedded unless the {@link LinkRestRepository}
* forbids it via {@link LinkRestRepository#isEmbeddableRelation(Object, String)}.
* </p>
* <p>
* If true, it means the resource will be embedded normally, unless forbidden by the {@link LinkRestRepository}
* or the projection, in use, via {@link Projection#allowOptionalEmbed(HALResource, LinkRest)}.
* </p>
*
* @return whether embedding is optional.
*/
boolean embedOptional() default false;
/**
* Tells whether linking the resource indicated by this link is optional.
* <p>
* If false (the default), it means the resource will always be linked.
* </p>
* <p>
* If true, it means the resource will only be linked if:
* <ul>
* <li> The resource is embedded, or</li>
* <li> The value returned by the link method is not null and linking is not forbidden by the
* projection in use, via {@link Projection#allowOptionalLink(HALResource, LinkRest)}</li>
* </ul>
* </p>
*
* @return whether linking is optional.
*/
boolean linkOptional() default false;
} }

View File

@@ -22,5 +22,5 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
public @interface LinksRest { public @interface LinksRest {
LinkRest[] links(); LinkRest[] links() default {};
} }

View File

@@ -16,7 +16,7 @@ import org.dspace.content.Item;
/** /**
* The REST object that will define a list of CollectionRest objects to be returned by the REST api * The REST object that will define a list of CollectionRest objects to be returned by the REST api
*/ */
public class MappedCollectionRestWrapper implements RestAddressableModel { public class MappedCollectionRestWrapper extends RestAddressableModel {
@JsonIgnore @JsonIgnore
private List<CollectionRest> mappedCollectionRestList; private List<CollectionRest> mappedCollectionRestList;

View File

@@ -16,7 +16,7 @@ import org.dspace.app.rest.MappedItemRestController;
/** /**
* The REST object that will define a list of ItemRest objects to be returned by the REST api * The REST object that will define a list of ItemRest objects to be returned by the REST api
*/ */
public class MappedItemRestWrapper implements RestAddressableModel { public class MappedItemRestWrapper extends RestAddressableModel {
@JsonIgnore @JsonIgnore
private List<ItemRest> mappedItemRestList; private List<ItemRest> mappedItemRestList;

View File

@@ -76,4 +76,4 @@ public class MetadataFieldRest extends BaseObjectRest<Integer> {
public String getCategory() { public String getCategory() {
return CATEGORY; return CATEGORY;
} }
} }

View File

@@ -54,4 +54,4 @@ public class MetadataSchemaRest extends BaseObjectRest<Integer> {
public String getCategory() { public String getCategory() {
return CATEGORY; return CATEGORY;
} }
} }

View File

@@ -0,0 +1,39 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.model;
import java.util.AbstractList;
import java.util.List;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.converter.MetadataConverter;
import org.dspace.app.rest.projection.Projection;
import org.dspace.content.MetadataValue;
/**
* Type-safe wrapper for a list of {@link MetadataValue}s for use with {@link MetadataConverter},
* so it can be invoked properly via calls to {@link ConverterService#toRest(Object, Projection)}.
*/
public class MetadataValueList extends AbstractList<MetadataValue> {
private final List<MetadataValue> list;
public MetadataValueList(List<MetadataValue> list) {
this.list = list;
}
@Override
public MetadataValue get(int index) {
return list.get(index);
}
@Override
public int size() {
return list.size();
}
}

View File

@@ -107,4 +107,4 @@ public class PoolTaskRest extends BaseObjectRest<Integer> {
public void setWorkflowitem(WorkflowItemRest workflowitem) { public void setWorkflowitem(WorkflowItemRest workflowitem) {
this.workflowitem = workflowitem; this.workflowitem = workflowitem;
} }
} }

View File

@@ -18,7 +18,7 @@ import org.dspace.app.rest.RelationshipTypeRestController;
* RelationshipTypeRest objects * RelationshipTypeRest objects
* The other methods are generic getters and setters * The other methods are generic getters and setters
*/ */
public class RelationshipTypeRestWrapper implements RestAddressableModel { public class RelationshipTypeRestWrapper extends RestAddressableModel {
@JsonIgnore @JsonIgnore
private List<RelationshipTypeRest> relationshipTypeRestList; private List<RelationshipTypeRest> relationshipTypeRestList;
@@ -26,8 +26,6 @@ public class RelationshipTypeRestWrapper implements RestAddressableModel {
private String entityTypeLabel; private String entityTypeLabel;
private Integer entityTypeId; private Integer entityTypeId;
public List<RelationshipTypeRest> getRelationshipTypeRestList() { public List<RelationshipTypeRest> getRelationshipTypeRestList() {
return relationshipTypeRestList; return relationshipTypeRestList;
} }

View File

@@ -8,17 +8,29 @@
package org.dspace.app.rest.model; package org.dspace.app.rest.model;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import org.dspace.app.rest.projection.Projection;
/** /**
* A directly addressable REST resource * A directly addressable REST resource
* *
* @author Andrea Bollini (andrea.bollini at 4science.it) * @author Andrea Bollini (andrea.bollini at 4science.it)
*/ */
public interface RestAddressableModel extends RestModel { public abstract class RestAddressableModel implements RestModel {
private Projection projection = Projection.DEFAULT;
@JsonIgnore @JsonIgnore
public String getCategory(); public abstract String getCategory();
@JsonIgnore @JsonIgnore
public Class getController(); public abstract Class getController();
@JsonIgnore
public Projection getProjection() {
return projection;
}
public void setProjection(Projection projection) {
this.projection = projection;
}
} }

View File

@@ -14,7 +14,7 @@ import org.dspace.app.rest.RootRestResourceController;
/** /**
* The purpose of this class is to show the representation of information on the home/root page of the REST API * The purpose of this class is to show the representation of information on the home/root page of the REST API
*/ */
public class RootRest implements RestAddressableModel { public class RootRest extends RestAddressableModel {
public static final String NAME = "root"; public static final String NAME = "root";
public static final String CATEGORY = RestModel.ROOT; public static final String CATEGORY = RestModel.ROOT;
private String dspaceURL; private String dspaceURL;

View File

@@ -29,19 +29,6 @@ public class SearchEventRest extends BaseObjectRest<UUID> {
private SearchResultsRest.Sorting sort; private SearchResultsRest.Sorting sort;
private PageRest page; private PageRest page;
public SearchEventRest(String query, UUID scope, String configuration,
List<SearchResultsRest.AppliedFilter> appliedFilters,
SearchResultsRest.Sorting sort) {
this.query = query;
this.scope = scope;
this.configuration = configuration;
this.appliedFilters = appliedFilters;
this.sort = sort;
}
public SearchEventRest() {
}
public String getCategory() { public String getCategory() {
return CATEGORY; return CATEGORY;
} }

View File

@@ -18,7 +18,7 @@ import org.dspace.discovery.configuration.DiscoverySearchFilterFacet;
/** /**
* This class' purpose is to create a container for the information used in the SearchFacetEntryResource * This class' purpose is to create a container for the information used in the SearchFacetEntryResource
*/ */
public class SearchFacetEntryRest implements RestAddressableModel { public class SearchFacetEntryRest extends RestAddressableModel {
public static final String NAME = "discover"; public static final String NAME = "discover";
public static final String CATEGORY = RestModel.DISCOVER; public static final String CATEGORY = RestModel.DISCOVER;

View File

@@ -13,7 +13,7 @@ import org.dspace.app.rest.DiscoveryRestController;
/** /**
* This class' purpose is to create a container for the information used in the SearchFacetValueResource * This class' purpose is to create a container for the information used in the SearchFacetValueResource
*/ */
public class SearchFacetValueRest implements RestAddressableModel { public class SearchFacetValueRest extends RestAddressableModel {
public static final String NAME = "discover"; public static final String NAME = "discover";
public static final String CATEGORY = RestModel.DISCOVER; public static final String CATEGORY = RestModel.DISCOVER;

Some files were not shown because too many files have changed in this diff Show More