no message

This commit is contained in:
Ioannis Kalyvas 2018-03-05 18:18:45 +02:00
parent 52bceed971
commit 8cb464c1e9
80 changed files with 1052 additions and 1284 deletions

View File

@ -189,15 +189,45 @@
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/fop -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>fop</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/fr.opensagres.xdocreport/org.apache.poi.xwpf.converter.pdf -->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/fr.opensagres.xdocreport/org.apache.poi.xwpf.converter.core -->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.core</artifactId>
<version>1.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/fr.opensagres.xdocreport/fr.opensagres.xdocreport.itext.extension -->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.itext.extension</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
</dependency>
</dependencies>

View File

@ -67,7 +67,7 @@ public class DevelDatabaseConfiguration {
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL92Dialect");
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.show_sql", "false");
properties.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false");
return properties;
}

View File

@ -1,11 +1,16 @@
package eu.eudat.configurations;
import eu.eudat.controllers.interceptors.RequestInterceptor;
import eu.eudat.handlers.PrincipalArgumentResolver;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.ApiContext;
import eu.eudat.services.operations.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import eu.eudat.types.WarningLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
@ -14,12 +19,25 @@ import java.util.List;
@Configuration
public class WebMVCConfiguration extends WebMvcConfigurerAdapter {
@Autowired
AuthenticationService authenticationService;
private ApiContext apiContext;
private AuthenticationService authenticationService;
@Autowired
public WebMVCConfiguration(ApiContext apiContext, AuthenticationService authenticationService) {
this.apiContext = apiContext;
this.authenticationService = authenticationService;
}
@Autowired
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new PrincipalArgumentResolver(this.authenticationService));
argumentResolvers.add(new PrincipalArgumentResolver(authenticationService));
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor(this.apiContext.getHelpersService().getLoggerService()));
}
}

View File

@ -33,7 +33,7 @@ public class Admin extends BaseController {
public ResponseEntity<Object> addDmp(@Valid @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
try {
eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile, getApiContext());
this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId());
} catch (Exception ex) {
ex.printStackTrace();
@ -47,9 +47,9 @@ public class Admin extends BaseController {
try {
eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile, getApiContext());
eu.eudat.entities.DatasetProfile datasetprofile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.entities.DatasetProfile datasetprofile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
datasetprofile.setDefinition(modelDefinition.getDefinition());
this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile);
this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
@ -61,7 +61,7 @@ public class Admin extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/admin/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<DatasetProfile>> get(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
try {
eu.eudat.entities.DatasetProfile profile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(datasetprofile));

View File

@ -24,13 +24,13 @@ public abstract class BaseController {
@InitBinder()
protected void initBinder(WebDataBinder binder) {
if (binder.getTarget() != null && DataManagementPlanTableRequestValidator.supportsType((binder.getTarget().getClass())))
binder.addValidators(this.apiContext.getApplicationContext().getBean("dataManagementPlanTableRequestValidator", DataManagementPlanTableRequestValidator.class));
binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("dataManagementPlanTableRequestValidator", DataManagementPlanTableRequestValidator.class));
if (binder.getTarget() != null && ProjectTableRequestValidator.supportsType((binder.getTarget().getClass())))
binder.addValidators(this.apiContext.getApplicationContext().getBean("projectTableRequestValidator", ProjectTableRequestValidator.class));
binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("projectTableRequestValidator", ProjectTableRequestValidator.class));
if (binder.getTarget() != null && DatasetProfileValidator.supportsType((binder.getTarget().getClass())))
binder.addValidators(this.apiContext.getApplicationContext().getBean("datasetProfileValidator", DatasetProfileValidator.class));
binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("datasetProfileValidator", DatasetProfileValidator.class));
if (binder.getTarget() != null && ProjectModelValidator.supportsType((binder.getTarget().getClass())))
binder.addValidators(this.apiContext.getApplicationContext().getBean("projectModelValidator", ProjectModelValidator.class));
binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("projectModelValidator", ProjectModelValidator.class));
}
}

View File

@ -40,7 +40,6 @@ public class DMPs extends BaseController {
try {
DataTableData<DataManagementPlanListingModel> dataTable = new DataManagementPlanManager().getPaged(this.getApiContext(), dataManagementPlanTableRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
} catch (Exception ex) {
ex.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage()));
@ -51,7 +50,7 @@ public class DMPs extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<DataManagementPlan>> getSingle(@PathVariable String id, Principal principal) {
try {
eu.eudat.models.dmp.DataManagementPlan dataManagementPlan = new DataManagementPlanManager().getSingle(this.getApiContext().getDatabaseRepository().getDmpDao(), id, principal);
eu.eudat.models.dmp.DataManagementPlan dataManagementPlan = new DataManagementPlanManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
} catch (Exception ex) {
@ -101,9 +100,8 @@ public class DMPs extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<List<DataManagementPlan>>> getWithCriteria(@RequestBody DataManagementPlanCriteriaRequest dataManagementPlanCriteria, Principal principal) {
try {
List<DataManagementPlan> dataTable = new DataManagementPlanManager().getWithCriteria(this.getApiContext().getDatabaseRepository().getDmpDao(), dataManagementPlanCriteria);
List<DataManagementPlan> dataTable = new DataManagementPlanManager().getWithCriteria(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), dataManagementPlanCriteria);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataManagementPlan>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
} catch (Exception ex) {
ex.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<List<DataManagementPlan>>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage()));

View File

@ -27,8 +27,8 @@ public class DashBoardController extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/getStatistics"}, produces = "application/json")
public ResponseEntity<ResponseItem<DashBoardStatistics>> getStatistics() {
try {
DashBoardStatistics statistics = new DashBoardManager().getStatistics(this.getApiContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getDatabaseRepository().getDmpDao()
, this.getApiContext().getDatabaseRepository().getProjectDao());
DashBoardStatistics statistics = new DashBoardManager().getStatistics(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao()
, this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DashBoardStatistics>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
} catch (Exception ex) {
ex.printStackTrace();
@ -39,8 +39,8 @@ public class DashBoardController extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/me/getStatistics"}, produces = "application/json")
public ResponseEntity<ResponseItem<DashBoardStatistics>> getStatistics(Principal principal) {
try {
DashBoardStatistics statistics = new DashBoardManager().getMeStatistics(this.getApiContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getDatabaseRepository().getDmpDao()
, this.getApiContext().getDatabaseRepository().getProjectDao(), principal);
DashBoardStatistics statistics = new DashBoardManager().getMeStatistics(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao()
, this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DashBoardStatistics>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
} catch (Exception ex) {
ex.printStackTrace();

View File

@ -28,7 +28,7 @@ public class DataRepositories extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<List<Map<String, String>>>> listExternalDataRepositories(@RequestParam(value = "query", required = false) String query) {
try {
List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getRepositories(query);
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getRepositories(query);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Map<String, String>>>().status(ApiMessageCode.NO_MESSAGE).payload(remoteRepos));
} catch (NoURLFound ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<List<Map<String, String>>>().status(ApiMessageCode.ERROR_MESSAGE).message(ex.getMessage()).payload(null));

View File

@ -34,7 +34,7 @@ public class DatasetProfileController extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/datasetwizard/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getSingle(@PathVariable String id) {
try {
eu.eudat.entities.DatasetProfile profile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.user.composite.DatasetProfile datasetprofile = UserManager.generateDatasetProfileModel(profile);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
@ -49,13 +49,13 @@ public class DatasetProfileController extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/save/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> updateDataset(@PathVariable String id, @RequestBody PropertiesModel properties) {
try {
eu.eudat.entities.Dataset dataset = this.getApiContext().getDatabaseRepository().getDatasetDao().find(UUID.fromString(id));
eu.eudat.entities.Dataset dataset = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao().find(UUID.fromString(id));
Map<String, Object> values = new HashMap();
properties.toMap(values);
JSONObject jobject = new JSONObject(values);
dataset.setProperties(jobject.toString());
dataset.setStatus((short) properties.getStatus());
this.getApiContext().getDatabaseRepository().getDatasetDao().createOrUpdate(dataset); //TODO
this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(dataset); //TODO
return ResponseEntity.status(HttpStatus.OK).body(properties);
} catch (Exception ex) {
ex.printStackTrace();
@ -66,7 +66,7 @@ public class DatasetProfileController extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/search/autocomplete"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> getDataForAutocomplete(@RequestBody AutoCompleteLookupItem lookupItem) {
try {
eu.eudat.entities.Dataset dataset = this.getApiContext().getDatabaseRepository().getDatasetDao().find(UUID.fromString(lookupItem.getProfileID()));
eu.eudat.entities.Dataset dataset = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao().find(UUID.fromString(lookupItem.getProfileID()));
eu.eudat.entities.xmlmodels.datasetprofiledefinition.Field modelfield = new eu.eudat.entities.xmlmodels.datasetprofiledefinition.Field();
AutoCompleteData data = new AutoCompleteData().fromData(modelfield.getData());

View File

@ -31,7 +31,7 @@ public class DatasetProfiles extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<List<DatasetProfileAutocompleteItem>>> get(@RequestBody DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) {
try {
List<DatasetProfileAutocompleteItem> datasetProfileAutocompleteItems = DatasetProfileManager.getWithCriteria(this.getApiContext().getDatabaseRepository().getDatasetProfileDao(), datasetProfileAutocompleteRequest);
List<DatasetProfileAutocompleteItem> datasetProfileAutocompleteItems = DatasetProfileManager.getWithCriteria(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao(), datasetProfileAutocompleteRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DatasetProfileAutocompleteItem>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileAutocompleteItems));
} catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<List<DatasetProfileAutocompleteItem>>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE));
@ -53,7 +53,7 @@ public class DatasetProfiles extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<List<DatasetProfileListingModel>>> getAll() {
try {
List<DatasetProfileListingModel> datasetProfileTableData = DatasetProfileManager.getAll(this.getApiContext().getDatabaseRepository().getDatasetProfileDao());
List<DatasetProfileListingModel> datasetProfileTableData = DatasetProfileManager.getAll(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
} catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<List<DatasetProfileListingModel>>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE));

View File

@ -12,17 +12,20 @@ import eu.eudat.models.helpers.responses.ResponseItem;
import eu.eudat.models.security.Principal;
import eu.eudat.services.ApiContext;
import eu.eudat.types.ApiMessageCode;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.activation.MimetypesFileTypeMap;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@ -32,16 +35,19 @@ import java.util.List;
@RequestMapping(value = {"api/datasetwizard"})
public class DatasetWizardController extends BaseController {
private Environment environment;
@Autowired
public DatasetWizardController(ApiContext apiContext) {
public DatasetWizardController(ApiContext apiContext, Environment environment) {
super(apiContext);
this.environment = environment;
}
@RequestMapping(method = RequestMethod.POST, value = {"/userDmps"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataManagentPlanListingModel>>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) {
try {
List<DataManagentPlanListingModel> dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, principal);
List<DataManagentPlanListingModel> dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataManagentPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
} catch (Exception ex) {
@ -54,7 +60,7 @@ public class DatasetWizardController extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<List<AssociatedProfile>>> getAvailableProfiles(@RequestBody DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest, Principal principal) {
try {
List<AssociatedProfile> dataManagementPlans = DatasetWizardManager.getAvailableProfiles(this.getApiContext().getDatabaseRepository().getDmpDao(), datasetProfileWizardAutocompleteRequest);
List<AssociatedProfile> dataManagementPlans = DatasetWizardManager.getAvailableProfiles(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetProfileWizardAutocompleteRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<AssociatedProfile>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
} catch (Exception ex) {
@ -67,7 +73,7 @@ public class DatasetWizardController extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<DatasetWizardModel>> getSingle(@PathVariable String id, Principal principal) {
try {
DatasetWizardModel dataset = new DatasetManager().getSingle(this.getApiContext().getDatabaseRepository().getDatasetDao(), id);
DatasetWizardModel dataset = new DatasetManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
} catch (Exception ex) {
ex.printStackTrace();
@ -88,21 +94,29 @@ public class DatasetWizardController extends BaseController {
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/getWordDocument/{id}"}, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@RequestMapping(method = RequestMethod.GET, value = {"/getWordDocument/{id}"})
public @ResponseBody
ResponseEntity<InputStreamResource> getWordDocument(@PathVariable String id) {
ResponseEntity<byte[]> getWordDocument(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException {
try {
File file = new DatasetManager().getWordDocument(this.getApiContext().getDatabaseRepository().getDatasetDao(), id);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
File file = new DatasetManager().getWordDocument(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
File pdffile = new DatasetManager().convertToPDF(file, environment, file.getName());
InputStream resource = new FileInputStream(pdffile);
System.out.println("Mime Type of " + file.getName() + " is " +
new MimetypesFileTypeMap().getContentType(file));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(pdffile.length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + pdffile.getName());
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=" + file.getName())
.contentType(MediaType.APPLICATION_PDF).contentLength(file.length())
.body(resource);
} catch (Exception ex) {
ex.printStackTrace();
return new ResponseEntity<InputStreamResource>(HttpStatus.BAD_REQUEST);
byte[] content = IOUtils.toByteArray(resource);
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
}

View File

@ -47,8 +47,8 @@ public class Datasets extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> makePublic(@PathVariable UUID id, Principal principal, Locale locale) {
try {
DatasetManager.makePublic(this.getApiContext().getDatabaseRepository().getDatasetDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message(this.getApiContext().getMessageSource().getMessage("dataset.public", new Object[]{}, locale)));
DatasetManager.makePublic(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message(this.getApiContext().getHelpersService().getMessageSource().getMessage("dataset.public", new Object[]{}, locale)));
} catch (Exception ex) {
ex.printStackTrace();

View File

@ -44,7 +44,7 @@ public class ExternalDatasets extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<List<ExternalDatasetListingModel>>> getWithExternal(@RequestParam(value = "query", required = false) String query, Principal principal) {
try {
List<ExternalDatasetListingModel> dataTable = new ExternalDatasetManager().getWithExternal(this.getApiContext(), query, this.getApiContext().getRemoteFetcher());
List<ExternalDatasetListingModel> dataTable = new ExternalDatasetManager().getWithExternal(this.getApiContext(), query, this.getApiContext().getOperationsContext().getRemoteFetcher());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<ExternalDatasetListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
ex.printStackTrace();
@ -56,7 +56,7 @@ public class ExternalDatasets extends BaseController {
public @ResponseBody
ResponseItem<ExternalDatasetListingModel> getWithExternal(@PathVariable UUID id, Principal principal) {
try {
ExternalDatasetListingModel externalDatasetModel = new ExternalDatasetManager().getSingle(this.getApiContext().getDatabaseRepository().getExternalDatasetDao(), id);
ExternalDatasetListingModel externalDatasetModel = new ExternalDatasetManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getExternalDatasetDao(), id);
return new ResponseItem<ExternalDatasetListingModel>().payload(externalDatasetModel).status(ApiMessageCode.NO_MESSAGE);
} catch (Exception ex) {
ex.printStackTrace();

View File

@ -11,7 +11,7 @@ import eu.eudat.security.validators.b2access.B2AccessTokenValidator;
import eu.eudat.security.validators.b2access.helpers.B2AccessRequest;
import eu.eudat.security.validators.b2access.helpers.B2AccessResponseToken;
import eu.eudat.security.validators.twitter.TwitterTokenValidator;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
@ -29,16 +29,16 @@ public class Login {
private CustomAuthenticationProvider customAuthenticationProvider;
private AuthenticationService authenticationService;
private AuthenticationServiceImpl authenticationServiceImpl;
private TwitterTokenValidator twitterTokenValidator;
private B2AccessTokenValidator b2AccessTokenValidator;
@Autowired
public Login(CustomAuthenticationProvider customAuthenticationProvider, AuthenticationService authenticationService, TwitterTokenValidator twitterTokenValidator, B2AccessTokenValidator b2AccessTokenValidator) {
public Login(CustomAuthenticationProvider customAuthenticationProvider, AuthenticationServiceImpl authenticationServiceImpl, TwitterTokenValidator twitterTokenValidator, B2AccessTokenValidator b2AccessTokenValidator) {
this.customAuthenticationProvider = customAuthenticationProvider;
this.authenticationService = authenticationService;
this.authenticationServiceImpl = authenticationServiceImpl;
this.twitterTokenValidator = twitterTokenValidator;
this.b2AccessTokenValidator = b2AccessTokenValidator;
}
@ -62,7 +62,7 @@ public class Login {
public @ResponseBody
ResponseEntity<ResponseItem<Principal>> nativelogin(@RequestBody Credentials credentials) {
try {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(UserManager.authenticate(this.authenticationService, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(UserManager.authenticate(this.authenticationServiceImpl, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (UnauthorisedException ex) {
throw ex;
} catch (Exception ex) {
@ -97,7 +97,7 @@ public class Login {
public @ResponseBody
ResponseEntity<ResponseItem<Principal>> authMe(Principal principal) {
try {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(this.authenticationService.Touch(principal.getToken())).status(ApiMessageCode.NO_MESSAGE));
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(this.authenticationServiceImpl.Touch(principal.getToken())).status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
ex.printStackTrace();
@ -110,7 +110,7 @@ public class Login {
public @ResponseBody
ResponseEntity<ResponseItem<Principal>> logout(Principal principal) {
try {
this.authenticationService.Logout(principal.getToken());
this.authenticationServiceImpl.Logout(principal.getToken());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {

View File

@ -29,7 +29,7 @@ public class Organisations extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<OrganisationsExternalSourcesModel>> listExternalOrganisations(@RequestParam(value = "query", required = false) String query) {
try {
List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getOrganisations(query);
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getOrganisations(query);
OrganisationsExternalSourcesModel projectsExternalSourcesModel = new OrganisationsExternalSourcesModel().fromExternalItem(remoteRepos);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<OrganisationsExternalSourcesModel>().payload(projectsExternalSourcesModel).status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (NoURLFound ex) {

View File

@ -38,7 +38,7 @@ public class Projects extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<ProjectListingModel>>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, Principal principal) {
try {
DataTableData<eu.eudat.models.project.ProjectListingModel> dataTable = new ProjectManager().getPaged(this.getApiContext().getDatabaseRepository().getProjectDao(), projectTableRequest);
DataTableData<eu.eudat.models.project.ProjectListingModel> dataTable = new ProjectManager().getPaged(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), projectTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<eu.eudat.models.project.ProjectListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
@ -51,7 +51,7 @@ public class Projects extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<eu.eudat.models.project.Project>> getSingle(@PathVariable String id, Principal principal) {
try {
eu.eudat.models.project.Project project = new ProjectManager().getSingle(this.getApiContext().getDatabaseRepository().getProjectDao(), id);
eu.eudat.models.project.Project project = new ProjectManager().getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.project.Project>().payload(project).status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
ex.printStackTrace();
@ -65,7 +65,7 @@ public class Projects extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<Project>> addProject(@Valid @RequestBody eu.eudat.models.project.Project project, Principal principal) {
try {
ProjectManager.createOrUpdate(this.getApiContext().getDatabaseRepository().getProjectDao(), this.getApiContext().getDatabaseRepository().getUserInfoDao(), project, principal);
ProjectManager.createOrUpdate(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao(), project, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.entities.Project>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
} catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<eu.eudat.entities.Project>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage()));
@ -78,7 +78,7 @@ public class Projects extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<Project>> inactivate(@PathVariable String id, Principal principal) {
try {
Project project = new ProjectManager().inactivate(this.getApiContext().getDatabaseRepository().getProjectDao(), id);
Project project = new ProjectManager().inactivate(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.entities.Project>().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<eu.eudat.entities.Project>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage()));
@ -90,7 +90,7 @@ public class Projects extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.project.Project>>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) {
try {
List<eu.eudat.models.project.Project> dataTable = new ProjectManager().getCriteriaWithExternal(this.getApiContext(), projectCriteria, this.getApiContext().getRemoteFetcher());
List<eu.eudat.models.project.Project> dataTable = new ProjectManager().getCriteriaWithExternal(this.getApiContext(), projectCriteria, this.getApiContext().getOperationsContext().getRemoteFetcher());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.project.Project>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
ex.printStackTrace();
@ -102,7 +102,7 @@ public class Projects extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.project.Project>>> get(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) {
try {
List<eu.eudat.models.project.Project> dataTable = new ProjectManager().getCriteria(this.getApiContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getRemoteFetcher());
List<eu.eudat.models.project.Project> dataTable = new ProjectManager().getCriteria(this.getApiContext().getOperationsContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getOperationsContext().getRemoteFetcher());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.project.Project>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
} catch (Exception ex) {
ex.printStackTrace();
@ -114,7 +114,7 @@ public class Projects extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<ProjectsExternalSourcesModel>> listExternalProjects(@RequestParam(value = "query", required = false) String query, Principal principal) {
try {
List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getProjects(query);
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getProjects(query);
ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ProjectsExternalSourcesModel>().payload(projectsExternalSourcesModel).status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (NoURLFound ex) {

View File

@ -29,7 +29,7 @@ public class Registries extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<RegistriesExternalSourcesModel>> listExternalRegistries(@RequestParam(value = "query", required = false) String query) {
try {
List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getRegistries(query);
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getRegistries(query);
RegistriesExternalSourcesModel registriesExternalSourcesModel = new RegistriesExternalSourcesModel().fromExternalItem(remoteRepos);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<RegistriesExternalSourcesModel>().payload(registriesExternalSourcesModel).status(ApiMessageCode.NO_MESSAGE));
} catch (NoURLFound ex) {

View File

@ -35,7 +35,7 @@ public class Researchers extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<ResearchersExternalSourcesModel>> listExternalResearchers(@RequestParam(value = "query", required = false) String query) {
try {
List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getResearchers(query);
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getResearchers(query);
ResearchersExternalSourcesModel researchersExternalSourcesModel = new ResearchersExternalSourcesModel().fromExternalItem(remoteRepos);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ResearchersExternalSourcesModel>().payload(researchersExternalSourcesModel).status(ApiMessageCode.NO_MESSAGE));
} catch (NoURLFound ex) {

View File

@ -29,7 +29,7 @@ public class Services extends BaseController {
public @ResponseBody
ResponseEntity<ResponseItem<ServiceExternalSourcesModel>> listExternalServices(@RequestParam(value = "query", required = false) String query) {
try {
List<Map<String, String>> remoteRepos = this.getApiContext().getRemoteFetcher().getServices(query);
List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getServices(query);
ServiceExternalSourcesModel serviceExternalSourcesModel = new ServiceExternalSourcesModel().fromExternalItem(remoteRepos);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ServiceExternalSourcesModel>().payload(serviceExternalSourcesModel).status(ApiMessageCode.NO_MESSAGE));
} catch (NoURLFound ex) {

View File

@ -0,0 +1,38 @@
package eu.eudat.controllers.controllerhandler;
import eu.eudat.models.helpers.responses.ResponseItem;
import eu.eudat.services.ApiContext;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.WarningLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
/**
* Created by ikalyvas on 3/1/2018.
*/
@ControllerAdvice
public class GeneralErrorHandler extends ResponseEntityExceptionHandler {
private ApiContext apiContext;
@Autowired
public GeneralErrorHandler(ApiContext apiContext) {
this.apiContext = apiContext;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseItem<?> processValidationError(HttpServletRequest req, Exception ex) {
apiContext.getHelpersService().getLoggerService().log(ex.getMessage(), WarningLevel.ERROR);
return new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(ex.getMessage());
}
}

View File

@ -0,0 +1,33 @@
package eu.eudat.controllers.interceptors;
import eu.eudat.services.helpers.LoggerService;
import eu.eudat.types.WarningLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
* Created by ikalyvas on 3/1/2018.
*/
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
private LoggerService loggerService;
@Autowired
public RequestInterceptor(LoggerService loggerService) {
this.loggerService = loggerService;
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String reqUri = request.getRequestURI();
this.loggerService.log("Call to " + reqUri + " method: " + request.getMethod() + " at: " + new Date(), WarningLevel.INFO);
return super.preHandle(request, response, handler);
}
}

View File

@ -7,7 +7,8 @@ import eu.eudat.models.user.components.datasetprofile.FieldSet;
import eu.eudat.models.user.components.datasetprofile.Section;
import eu.eudat.models.user.composite.DatasetProfilePage;
import eu.eudat.models.user.composite.PagedDatasetProfile;
import eu.eudat.utilities.interfaces.Applier;
import eu.eudat.services.forms.VisibilityRuleService;
import eu.eudat.utilities.interfaces.ApplierWithValue;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;
@ -15,6 +16,7 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STNumberFormat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
@ -27,7 +29,7 @@ import java.util.Map;
*/
public class WordBuilder {
private Map<ParagraphStyle, Applier<XWPFDocument, String, XWPFParagraph>> options = new HashMap<>();
private Map<ParagraphStyle, ApplierWithValue<XWPFDocument, String, XWPFParagraph>> options = new HashMap<>();
private CTAbstractNum cTAbstractNum;
private BigInteger numId;
@ -87,63 +89,69 @@ public class WordBuilder {
});
}
public File build(PagedDatasetProfile pagedDatasetProfile) throws IOException {
XWPFDocument document = new XWPFDocument();
public File build(PagedDatasetProfile pagedDatasetProfile, String label, VisibilityRuleService visibilityRuleService) throws IOException {
XWPFDocument document = new XWPFDocument(new FileInputStream((WordBuilder.class.getClassLoader().getResource("documents/h2020.docx")).getFile()));
this.buildOptions();
createPages(pagedDatasetProfile.getPages(), document, true);
createPages(pagedDatasetProfile.getPages(), document, true, visibilityRuleService);
XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
XWPFNumbering numbering = document.createNumbering();
BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
this.numId = numbering.addNum(abstractNumID);
createPages(pagedDatasetProfile.getPages(), document, false);
File exportFile = new File("welcome.docx");
createPages(pagedDatasetProfile.getPages(), document, false, visibilityRuleService);
File exportFile = new File(label);
FileOutputStream out = new FileOutputStream(exportFile);
document.write(out);
out.close();
return exportFile;
}
public void createPages(List<DatasetProfilePage> datasetProfilePages, XWPFDocument mainDocumentPart, Boolean createListing) {
public void createPages(List<DatasetProfilePage> datasetProfilePages, XWPFDocument mainDocumentPart, Boolean createListing, VisibilityRuleService visibilityRuleService) {
//if (createListing) this.addListing(mainDocumentPart, 0, false, true);
datasetProfilePages.forEach(item -> {
createSections(item.getSections(), mainDocumentPart, ParagraphStyle.TITLE, 0, createListing);
createSections(item.getSections(), mainDocumentPart, ParagraphStyle.TITLE, 0, createListing, visibilityRuleService);
});
}
public void createSections(List<Section> sections, XWPFDocument mainDocumentPart, ParagraphStyle style, Integer indent, Boolean createListing) {
public void createSections(List<Section> sections, XWPFDocument mainDocumentPart, ParagraphStyle style, Integer indent, Boolean createListing, VisibilityRuleService visibilityRuleService) {
if (createListing) this.addListing(mainDocumentPart, indent, false, true);
BigInteger listing = numId;
sections.forEach(section -> {
if (!createListing) {
XWPFParagraph paragraph = addParagraphContent(section.getTitle(), mainDocumentPart, style, listing);
CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl();
number.setVal(BigInteger.valueOf(indent));
if (visibilityRuleService.isElementVisible(section.getId())) {
if (!createListing) {
XWPFParagraph paragraph = addParagraphContent(section.getTitle(), mainDocumentPart, style, listing);
CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl();
number.setVal(BigInteger.valueOf(indent));
}
createSections(section.getSections(), mainDocumentPart, ParagraphStyle.HEADER2, 1, createListing, visibilityRuleService);
createCompositeFields(section.getCompositeFields(), mainDocumentPart, 2, createListing, visibilityRuleService);
}
createSections(section.getSections(), mainDocumentPart, ParagraphStyle.HEADER2, 1, createListing);
createCompositeFields(section.getCompositeFields(), mainDocumentPart, 2, createListing);
});
}
public void createCompositeFields(List<FieldSet> compositeFields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing) {
public void createCompositeFields(List<FieldSet> compositeFields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, VisibilityRuleService visibilityRuleService) {
if (createListing) this.addListing(mainDocumentPart, indent, true, true);
compositeFields.forEach(compositeField -> {
if (compositeField.getTitle() != null && !compositeField.getTitle().isEmpty() && !createListing) {
XWPFParagraph paragraph = addParagraphContent(compositeField.getTitle(), mainDocumentPart, ParagraphStyle.HEADER3, numId);
CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl();
number.setVal(BigInteger.valueOf(indent));
if (visibilityRuleService.isElementVisible(compositeField.getId())) {
if (compositeField.getTitle() != null && !compositeField.getTitle().isEmpty() && !createListing) {
XWPFParagraph paragraph = addParagraphContent(compositeField.getTitle(), mainDocumentPart, ParagraphStyle.HEADER3, numId);
CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl();
number.setVal(BigInteger.valueOf(indent));
}
createFields(compositeField.getFields(), mainDocumentPart, 3, createListing, visibilityRuleService);
}
createFields(compositeField.getFields(), mainDocumentPart, 3, createListing);
});
}
public void createFields(List<Field> fields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing) {
public void createFields(List<Field> fields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, VisibilityRuleService visibilityRuleService) {
if (createListing) this.addListing(mainDocumentPart, indent, false, false);
fields.forEach(field -> {
if (!createListing) {
XWPFParagraph paragraph = addParagraphContent(field.getValue(), mainDocumentPart, ParagraphStyle.TEXT, numId);
CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl();
number.setVal(BigInteger.valueOf(indent));
if (visibilityRuleService.isElementVisible(field.getId())) {
if (!createListing) {
XWPFParagraph paragraph = addParagraphContent(field.getValue() == null ? "" : field.getValue(), mainDocumentPart, ParagraphStyle.TEXT, numId);
CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl();
number.setVal(BigInteger.valueOf(indent));
}
}
});
}
@ -173,13 +181,18 @@ public class WordBuilder {
cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
cTLvl.addNewLvlText().setVal("Q " + textLevel);
cTLvl.addNewStart().setVal(BigInteger.valueOf(1));
cTLvl.setIlvl(BigInteger.valueOf(indent));
} else if (!question && hasIndication) {
cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
cTLvl.addNewLvlText().setVal(textLevel);
cTLvl.addNewStart().setVal(BigInteger.valueOf(1));
cTLvl.setIlvl(BigInteger.valueOf(indent));
}
if (!question && !hasIndication) {
cTLvl.addNewNumFmt().setVal(STNumberFormat.NONE);
cTLvl.addNewLvlText().setVal("");
cTLvl.addNewStart().setVal(BigInteger.valueOf(1));
cTLvl.setIlvl(BigInteger.valueOf(indent));
}
/*if (this.numId == null) {

View File

@ -3,7 +3,8 @@ package eu.eudat.handlers;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.models.security.Principal;
import eu.eudat.security.claims.ClaimedAuthorities;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.operations.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import eu.eudat.types.Authorities;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;

View File

@ -22,7 +22,7 @@ public class AdminManager {
viewStyleDoc.appendChild(elementViewStyle);
String xml = XmlBuilder.generateXml(viewStyleDoc);
eu.eudat.entities.DatasetProfile datasetProfile = apiContext.getBuilderFactory().getBuilder(DatasetProfileBuilder.class).definition(xml).label(profile.getLabel())
eu.eudat.entities.DatasetProfile datasetProfile = apiContext.getOperationsContext().getBuilderFactory().getBuilder(DatasetProfileBuilder.class).definition(xml).label(profile.getLabel())
.status((short) 1).created(new Date())
.build();

View File

@ -33,8 +33,8 @@ public class DataManagementPlanManager {
public DataTableData<DataManagementPlanListingModel> getPaged(ApiContext apiContext, DataManagementPlanTableRequest dataManagementPlanTableRequest, Principal principal) throws Exception {
UserInfo userInfo = new UserInfo();
userInfo.setId(principal.getId());
QueryableList<DMP> items = apiContext.getDatabaseRepository().getDmpDao().getWithCriteria(dataManagementPlanTableRequest.getCriteria());
QueryableList<DMP> authItems = apiContext.getDatabaseRepository().getDmpDao().getAuthenticated(items, userInfo);
QueryableList<DMP> items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dataManagementPlanTableRequest.getCriteria());
QueryableList<DMP> authItems = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, userInfo);
QueryableList<DMP> pagedItems = PaginationManager.applyPaging(authItems, dataManagementPlanTableRequest);
DataTableData<DataManagementPlanListingModel> dataTable = new DataTableData<DataManagementPlanListingModel>();
@ -68,12 +68,12 @@ public class DataManagementPlanManager {
public static void createOrUpdate(ApiContext apiContext, DataManagementPlan dataManagementPlan, Principal principal) throws Exception {
DMP newDmp = dataManagementPlan.toDataModel();
createOrganisationsIfTheyDontExist(newDmp, apiContext.getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getDatabaseRepository().getUserInfoDao().find(principal.getId());
createProjectIfItDoesntExist(newDmp, apiContext.getDatabaseRepository().getProjectDao(), user);
createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
createProjectIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getProjectDao(), user);
newDmp.setCreator(user);
newDmp = apiContext.getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
newDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
if (dataManagementPlan.getAssociatedUsers().stream().filter(item -> item.getId() == principal.getId()).collect(Collectors.toList()).size() == 0)
assignUser(newDmp, user, apiContext);
}
@ -83,44 +83,44 @@ public class DataManagementPlanManager {
userDMP.setDmp(dmp);
userDMP.setUser(userInfo);
userDMP.setRole(UserDMP.UserDMPRoles.OWNER.getValue());
apiContext.getDatabaseRepository().getUserDmpDao().createOrUpdate(userDMP);
apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(userDMP);
}
public static void newVersion(ApiContext apiContext, UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
DMP oldDmp = apiContext.getDatabaseRepository().getDmpDao().find(uuid);
DMP oldDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(uuid);
DMP newDmp = dataManagementPlan.toDataModel();
createOrganisationsIfTheyDontExist(newDmp, apiContext.getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
createProjectIfItDoesntExist(newDmp, apiContext.getDatabaseRepository().getProjectDao(), user);
createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
createProjectIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getProjectDao(), user);
newDmp.setCreator(user);
newDmp.setGroupId(oldDmp.getGroupId());
newDmp.setVersion(oldDmp.getVersion() + 1);
newDmp.setId(null);
newDmp = apiContext.getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
copyDatasets(newDmp, apiContext.getDatabaseRepository().getDatasetDao());
newDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
copyDatasets(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao());
}
public static void clone(ApiContext apiContext, UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
DMP newDmp = dataManagementPlan.toDataModel();
createOrganisationsIfTheyDontExist(newDmp, apiContext.getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
createProjectIfItDoesntExist(newDmp, apiContext.getDatabaseRepository().getProjectDao(), user);
createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao());
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
createProjectIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getProjectDao(), user);
newDmp.setCreator(user);
newDmp.setGroupId(UUID.randomUUID());
newDmp.setVersion(0);
newDmp.setId(null);
newDmp = apiContext.getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
copyDatasets(newDmp, apiContext.getDatabaseRepository().getDatasetDao());
newDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp);
copyDatasets(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao());
}
public static void delete(ApiContext apiContext, UUID uuid) throws DMPWithDatasetsException {
DMP oldDmp = apiContext.getDatabaseRepository().getDmpDao().find(uuid);
DMP oldDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(uuid);
if (oldDmp.getDataset().size() > 0)
throw new DMPWithDatasetsException("You cannot Remove Datamanagement Plan with Datasets");
oldDmp.setStatus(DMP.DMPStatus.DELETED.getValue());
apiContext.getDatabaseRepository().getDmpDao().createOrUpdate(oldDmp);
apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(oldDmp);
}
private static void createResearchersIfTheyDontExist(DMP newDmp, ResearcherDao researcherRepository) {

View File

@ -17,24 +17,32 @@ import eu.eudat.models.security.Principal;
import eu.eudat.models.user.composite.PagedDatasetProfile;
import eu.eudat.queryable.QueryableList;
import eu.eudat.services.ApiContext;
import eu.eudat.services.forms.VisibilityRuleService;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class DatasetManager {
public DataTableData<DatasetListingModel> getPaged(ApiContext apiContext, DatasetTableRequest datasetTableRequest, Principal principal) throws Exception {
UserInfo userInfo = apiContext.getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
QueryableList<eu.eudat.entities.Dataset> items = apiContext.getDatabaseRepository().getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria());
QueryableList<eu.eudat.entities.Dataset> authItems = apiContext.getDatabaseRepository().getDatasetDao().getAuthenticated(items, userInfo);
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
QueryableList<eu.eudat.entities.Dataset> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria());
QueryableList<eu.eudat.entities.Dataset> authItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getAuthenticated(items, userInfo);
QueryableList<eu.eudat.entities.Dataset> pagedItems = PaginationManager.applyPaging(authItems, datasetTableRequest);
DataTableData<DatasetListingModel> dataTable = new DataTableData<DatasetListingModel>();
@ -72,24 +80,94 @@ public class DatasetManager {
return pagedDatasetProfile;
}
public File getWordDocument(DatasetDao datatasetRepository, String id) throws InstantiationException, IllegalAccessException, IOException {
public File getWordDocument(DatasetDao datatasetRepository, String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException {
WordBuilder wordBuilder = new WordBuilder();
DatasetWizardModel dataset = new DatasetWizardModel();
eu.eudat.entities.Dataset datasetEntity = datatasetRepository.find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
PagedDatasetProfile pagedDatasetProfile = getPagedProfile(dataset,datasetEntity);
return wordBuilder.build(pagedDatasetProfile);
Map<String, Object> properties = new HashMap<>();
if (datasetEntity.getProperties() != null) {
JSONObject jobject = new JSONObject(datasetEntity.getProperties());
properties = (Map<String, Object>) jobject.toMap();
}
PagedDatasetProfile pagedDatasetProfile = getPagedProfile(dataset, datasetEntity);
visibilityRuleService.setProperties(properties);
visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules());
File file = wordBuilder.build(pagedDatasetProfile, datasetEntity.getLabel(),visibilityRuleService);
return file;
}
public File convertToPDF(File file, Environment environment, String label) throws IOException, InterruptedException {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
map, headers);
Map queueResult = new RestTemplate().postForObject(
environment.getProperty("pdf.converter.url") +
"api/v1/", requestEntity, Map.class);
Map mediaResult = new RestTemplate().getForObject(environment.getProperty("pdf.converter.url") +
"/api/v1/" + queueResult.get("id"), Map.class);
System.out.println("Status: " + mediaResult.get("status"));
while (!mediaResult.get("status").equals("finished")) {
Thread.sleep(500);
mediaResult = new RestTemplate().getForObject(environment.getProperty("pdf.converter.url") +
"api/v1/" + queueResult.get("id"), Map.class);
System.out.println("Polling");
}
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
HttpHeaders headers2 = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers2);
ResponseEntity<byte[]> response = restTemplate.exchange(environment.getProperty("pdf.converter.url") +
mediaResult.get("result_url"), HttpMethod.GET, entity, byte[].class, "1");
UUID uuid = UUID.randomUUID();
File zip = new File(uuid + ".zip");
if (response.getStatusCode().equals(HttpStatus.OK)) {
FileOutputStream output = new FileOutputStream(zip);
IOUtils.write(response.getBody(), output);
}
return extractFromZip(zip, label + ".pdf");
}
private File extractFromZip(File file, String filename) throws IOException {
byte[] buffer = new byte[1024];
File newFile = new File(filename);
ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
String zippedFileName = zipEntry.getName();
if (zippedFileName.equals("pdf")) {
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zipEntry = zis.getNextEntry();
}
}
zis.closeEntry();
zis.close();
return newFile;
}
public static eu.eudat.entities.Dataset createOrUpdate(ApiContext apiContext, DatasetWizardModel profile, Principal principal) throws Exception {
eu.eudat.entities.Dataset dataset = profile.toDataModel();
propertiesModelToString(profile, dataset);
UserInfo userInfo = apiContext.getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
dataset.setCreator(userInfo);
createRegistriesIfTheyDontExist(apiContext.getDatabaseRepository().getRegistryDao(), dataset);
createDataRepositoriesIfTheyDontExist(apiContext.getDatabaseRepository().getDataRepositoryDao(), dataset);
createServicesIfTheyDontExist(apiContext.getDatabaseRepository().getServiceDao(), dataset);
createExternalDatasetsIfTheyDontExist(apiContext.getDatabaseRepository().getExternalDatasetDao(), dataset);
return apiContext.getDatabaseRepository().getDatasetDao().createOrUpdate(dataset);
createRegistriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao(), dataset);
createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), dataset);
createServicesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getServiceDao(), dataset);
createExternalDatasetsIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao(), dataset);
return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(dataset);
}
private static void propertiesModelToString(DatasetWizardModel datasetWizardModel, eu.eudat.entities.Dataset dataset) {

View File

@ -24,10 +24,10 @@ public class DatasetProfileManager {
}
public static DataTableData<DatasetProfileListingModel> getPaged(ApiContext apiContext, DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws Exception {
QueryableList<DatasetProfile> items = apiContext.getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria());
QueryableList<DatasetProfile> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria());
QueryableList<DatasetProfile> pagedItems = PaginationManager.applyPaging(items, datasetProfileTableRequestItem);
List<DatasetProfileListingModel> datasetProfiles = pagedItems.select(item -> new DatasetProfileListingModel().fromDataModel(item));
return apiContext.getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(datasetProfiles).totalCount(items.count()).build();
return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(datasetProfiles).totalCount(items.count()).build();
}
public static List<DatasetProfileListingModel> getAll(DatasetProfileDao datasetProfileRepository) throws IllegalAccessException, InstantiationException {

View File

@ -22,15 +22,15 @@ import java.util.stream.Collectors;
public class ExternalDatasetManager {
public DataTableData<ExternalDatasetListingModel> getPaged(ApiContext apiContext, ExternalDatasetTableRequest externalDatasetTableRequest) throws Exception {
QueryableList<ExternalDataset> items = apiContext.getDatabaseRepository().getExternalDatasetDao().getWithCriteria(externalDatasetTableRequest.getCriteria());
QueryableList<ExternalDataset> items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(externalDatasetTableRequest.getCriteria());
QueryableList<ExternalDataset> pagedItems = PaginationManager.applyPaging(items, externalDatasetTableRequest);
List<ExternalDatasetListingModel> externalDatasetListingmodels = pagedItems.select(item -> new ExternalDatasetListingModel().fromDataModel(item));
return apiContext.getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(externalDatasetListingmodels).totalCount(items.count()).build();
return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(externalDatasetListingmodels).totalCount(items.count()).build();
}
public List<ExternalDatasetListingModel> getWithExternal(ApiContext apiContext, String query, RemoteFetcher remoteFetcher) throws HugeResultSet, NoURLFound, InstantiationException, IllegalAccessException {
ExternalDatasetCriteria criteria = apiContext.getBuilderFactory().getBuilder(ExternalDatasetCriteriaBuilder.class).like(query).build();
QueryableList<eu.eudat.entities.ExternalDataset> items = apiContext.getDatabaseRepository().getExternalDatasetDao().getWithCriteria(criteria);
ExternalDatasetCriteria criteria = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ExternalDatasetCriteriaBuilder.class).like(query).build();
QueryableList<eu.eudat.entities.ExternalDataset> items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(criteria);
List<ExternalDatasetListingModel> externalDatasets = items.select(item -> new ExternalDatasetListingModel().fromDataModel(item));
return externalDatasets;
}

View File

@ -22,27 +22,27 @@ public class InvitationsManager {
principalUser.setId(principal.getId());
List<UserInfoInvitationModel> alreadySignedInUsers = invitation.getUsers().stream().filter(item -> item.getId() != null).collect(Collectors.toList());
List<UserInfo> alreadySignedInUsersEntities = alreadySignedInUsers.stream().map(item -> item.toDataModel()).collect(Collectors.toList());
DMP dataManagementPlan = apiContext.getDatabaseRepository().getDmpDao().find(invitation.getDataManagementPlan());
apiContext.getInvitationService().createInvitations(apiContext.getDatabaseRepository().getInvitationDao(), apiContext.getMailService(), invitation.getUsers().stream().map(item -> item.toDataModel()).collect(Collectors.toList()), dataManagementPlan, principalUser);
apiContext.getInvitationService().assignToDmp(apiContext.getDatabaseRepository().getDmpDao(), alreadySignedInUsersEntities, dataManagementPlan);
DMP dataManagementPlan = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(invitation.getDataManagementPlan());
apiContext.getUtilitiesService().getInvitationService().createInvitations(apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao(), apiContext.getUtilitiesService().getMailService(), invitation.getUsers().stream().map(item -> item.toDataModel()).collect(Collectors.toList()), dataManagementPlan, principalUser);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), alreadySignedInUsersEntities, dataManagementPlan);
}
public static List<UserInfoInvitationModel> getUsers(ApiContext apiContext, UserInfoRequestItem userInfoRequestItem) throws InstantiationException, IllegalAccessException {
QueryableList<UserInfo> users = apiContext.getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoRequestItem.getCriteria());
QueryableList<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoRequestItem.getCriteria());
List<UserInfoInvitationModel> userModels = users.select(item -> new UserInfoInvitationModel().fromDataModel(item));
return userModels;
}
public static UUID assignUserAcceptedInvitation(ApiContext apiContext, UUID invitationID, Principal principal) throws UnauthorisedException {
eu.eudat.entities.Invitation invitation = apiContext.getDatabaseRepository().getInvitationDao().find(invitationID);
eu.eudat.entities.Invitation invitation = apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().find(invitationID);
if (invitation == null)
throw new UnauthorisedException("There is no Data Management Plan assigned to this Link");
if (invitation.getAcceptedInvitation()) throw new UnauthorisedException("This Url Has Expired");
UserInfo invitedUser = apiContext.getDatabaseRepository().getUserInfoDao().find(principal.getId());
UserInfo invitedUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
DMP datamanagementPlan = invitation.getDmp();
apiContext.getInvitationService().assignToDmp(apiContext.getDatabaseRepository().getDmpDao(), invitedUser, datamanagementPlan);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), invitedUser, datamanagementPlan);
invitation.setAcceptedInvitation(true);
apiContext.getDatabaseRepository().getInvitationDao().createOrUpdate(invitation);
apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().createOrUpdate(invitation);
return datamanagementPlan.getId();
}
}

View File

@ -56,12 +56,12 @@ public class ProjectManager {
}
public List<eu.eudat.models.project.Project> getCriteriaWithExternal(ApiContext apiContext, ProjectCriteriaRequest projectCriteria, RemoteFetcher remoteFetcher) throws IllegalAccessException, InstantiationException, HugeResultSet, NoURLFound {
QueryableList<eu.eudat.entities.Project> items = apiContext.getDatabaseRepository().getProjectDao().getWithCriteria(projectCriteria.getCriteria());
QueryableList<eu.eudat.entities.Project> items = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().getWithCriteria(projectCriteria.getCriteria());
List<eu.eudat.models.project.Project> projects = items.select(item -> new Project().fromDataModel(item));
List<Map<String, String>> remoteRepos = remoteFetcher.getProjects(projectCriteria.getCriteria().getLike());
ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos);
for (ExternalSourcesItemModel externalListingItem : projectsExternalSourcesModel) {
eu.eudat.models.project.Project project = apiContext.getBuilderFactory().getBuilder(ProjectBuilder.class)
eu.eudat.models.project.Project project = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ProjectBuilder.class)
.reference(externalListingItem.getRemoteId()).label(externalListingItem.getName())
.description(externalListingItem.getDescription()).uri(externalListingItem.getUri())
.abbreviation(externalListingItem.getAbbreviation()).status(eu.eudat.entities.Project.Status.fromInteger(0))

View File

@ -10,6 +10,6 @@ public class ResearcherManager {
public static Researcher create(ApiContext apiContext, eu.eudat.models.researcher.Researcher researcher) throws Exception {
Researcher researcherEntity = researcher.toDataModel();
return apiContext.getDatabaseRepository().getResearcherDao().createOrUpdate(researcherEntity);
return apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().createOrUpdate(researcherEntity);
}
}

View File

@ -11,13 +11,12 @@ import eu.eudat.models.userinfo.UserInfoTableRequestItem;
import eu.eudat.models.userinfo.UserListingModel;
import eu.eudat.queryable.QueryableList;
import eu.eudat.services.ApiContext;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import eu.eudat.utilities.builders.XmlBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.List;
import java.util.stream.Collectors;
public class UserManager {
public static eu.eudat.models.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.entities.DatasetProfile profile) {
@ -32,24 +31,24 @@ public class UserManager {
}
public static DataTableData<UserListingModel> getPaged(ApiContext apiContext, UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
QueryableList<eu.eudat.entities.UserInfo> users = apiContext.getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoTableRequestItem.getCriteria());
QueryableList<eu.eudat.entities.UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoTableRequestItem.getCriteria());
QueryableList<eu.eudat.entities.UserInfo> pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem);
List<UserListingModel> modelUsers = pagedUsers.select(item -> new UserListingModel().fromDataModel(item));
return apiContext.getBuilderFactory().getBuilder(DataTableDataBuilder.class).totalCount(users.count()).data(modelUsers).build();
return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).totalCount(users.count()).data(modelUsers).build();
}
public static void editRoles(ApiContext apiContext, UserListingModel user) {
eu.eudat.entities.UserInfo userInfo = apiContext.getDatabaseRepository().getUserInfoDao().find(user.getId());
userInfo.getUserRoles().stream().forEach(item -> apiContext.getDatabaseRepository().getUserRoleDao().delete(item));
eu.eudat.entities.UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(user.getId());
userInfo.getUserRoles().stream().forEach(item -> apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().delete(item));
for (Integer role : user.getAppRoles()) {
UserRole userRole = apiContext.getBuilderFactory().getBuilder(UserRoleBuilder.class).role(role).userInfo(userInfo).build();
apiContext.getDatabaseRepository().getUserRoleDao().createOrUpdate(userRole);
UserRole userRole = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserRoleBuilder.class).role(role).userInfo(userInfo).build();
apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(userRole);
}
}
public static Principal authenticate(AuthenticationService authenticationService, Credentials credentials) {
Principal principal = authenticationService.Touch(credentials);
public static Principal authenticate(AuthenticationServiceImpl authenticationServiceImpl, Credentials credentials) {
Principal principal = authenticationServiceImpl.Touch(credentials);
if (principal == null) throw new UnauthorisedException("Could not Sign In User");
return principal;
}

View File

@ -1,10 +1,12 @@
package eu.eudat.models.helpers.responses;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.ApiResponseType;
public class ResponseItem<T> {
private Integer statusCode;
private Integer responseType = ApiResponseType.JSON_RESPONSE.getValue();
private String message;
private T payload;
@ -32,6 +34,14 @@ public class ResponseItem<T> {
this.payload = payload;
}
public Integer getResponseType() {
return responseType;
}
public void setResponseType(Integer responseType) {
this.responseType = responseType;
}
public ResponseItem<T> status(ApiMessageCode statusCode) {
this.statusCode = statusCode.getValue();
return this;
@ -47,4 +57,9 @@ public class ResponseItem<T> {
return this;
}
public ResponseItem<T> responseType(ApiResponseType apiResponseType) {
this.responseType = apiResponseType.getValue();
return this;
}
}

View File

@ -9,7 +9,7 @@ import eu.eudat.security.customproviders.B2AccessUser;
import eu.eudat.security.validators.TokenValidator;
import eu.eudat.security.validators.b2access.helpers.B2AccessRequest;
import eu.eudat.security.validators.b2access.helpers.B2AccessResponseToken;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@ -24,12 +24,12 @@ import java.security.GeneralSecurityException;
public class B2AccessTokenValidator implements TokenValidator {
private B2AccessCustomProvider b2AccessCustomProvider;
private AuthenticationService authenticationService;
private AuthenticationServiceImpl authenticationServiceImpl;
private Environment environment;
@Autowired
public B2AccessTokenValidator(AuthenticationService authenticationService, Environment environment, B2AccessCustomProvider b2AccessCustomProvider) {
this.authenticationService = authenticationService;
public B2AccessTokenValidator(AuthenticationServiceImpl authenticationServiceImpl, Environment environment, B2AccessCustomProvider b2AccessCustomProvider) {
this.authenticationServiceImpl = authenticationServiceImpl;
this.environment = environment;
this.b2AccessCustomProvider = b2AccessCustomProvider;
}
@ -43,7 +43,7 @@ public class B2AccessTokenValidator implements TokenValidator {
user.setName(b2AccessUser.getName());
user.setProvider(credentials.getProvider());
user.setSecret(credentials.getTicket());
return this.authenticationService.Touch(user);
return this.authenticationServiceImpl.Touch(user);
}
public B2AccessResponseToken getAccessToken(B2AccessRequest b2AccessRequest) {

View File

@ -8,7 +8,7 @@ import eu.eudat.models.security.Principal;
import eu.eudat.security.validators.TokenValidator;
import eu.eudat.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.services.ApiContext;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.social.facebook.api.User;
@ -26,14 +26,14 @@ public class FacebookTokenValidator implements TokenValidator {
private Environment environment;
private ApiContext apiContext;
private AuthenticationService authenticationService;
private AuthenticationServiceImpl authenticationServiceImpl;
private FacebookServiceProvider facebookServiceProvider;
@Autowired
public FacebookTokenValidator(Environment environment, ApiContext apiContext, AuthenticationService authenticationService) {
public FacebookTokenValidator(Environment environment, ApiContext apiContext, AuthenticationServiceImpl authenticationServiceImpl) {
this.environment = environment;
this.apiContext = apiContext;
this.authenticationService = authenticationService;
this.authenticationServiceImpl = authenticationServiceImpl;
this.facebookServiceProvider = new FacebookServiceProvider(this.environment.getProperty("facebook.login.clientId"), this.environment.getProperty("facebook.login.clientSecret"), this.environment.getProperty("facebook.login.namespace"));
}
@ -49,7 +49,7 @@ public class FacebookTokenValidator implements TokenValidator {
user.setName(profile.getName());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.FACEBOOK);
user.setSecret(credentials.getTicket());
return this.authenticationService.Touch(user);
return this.authenticationServiceImpl.Touch(user);
}

View File

@ -12,7 +12,7 @@ import eu.eudat.models.loginprovider.LoginProviderUser;
import eu.eudat.security.validators.TokenValidator;
import eu.eudat.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.services.ApiContext;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@ -26,15 +26,15 @@ public class GoogleTokenValidator implements TokenValidator {
private static final HttpTransport transport = new NetHttpTransport();
private ApiContext apiContext;
private AuthenticationService authenticationService;
private AuthenticationServiceImpl authenticationServiceImpl;
private GoogleIdTokenVerifier verifier;
private Environment environment;
@Autowired
public GoogleTokenValidator(ApiContext apiContext, Environment environment, AuthenticationService authenticationService) {
public GoogleTokenValidator(ApiContext apiContext, Environment environment, AuthenticationServiceImpl authenticationServiceImpl) {
this.apiContext = apiContext;
this.environment = environment;
this.authenticationService = authenticationService;
this.authenticationServiceImpl = authenticationServiceImpl;
verifier = new GoogleIdTokenVerifier.Builder(transport, JacksonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(this.environment.getProperty("google.login.clientId")))
.build();
@ -56,7 +56,7 @@ public class GoogleTokenValidator implements TokenValidator {
user.setName((String) payload.get("name"));
user.setEmail(payload.getEmail());
user.setIsVerified(payload.getEmailVerified());
return this.authenticationService.Touch(user);
return this.authenticationServiceImpl.Touch(user);
}
}

View File

@ -8,7 +8,7 @@ import eu.eudat.models.security.Principal;
import eu.eudat.security.validators.TokenValidator;
import eu.eudat.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.services.ApiContext;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.social.linkedin.api.LinkedIn;
@ -26,14 +26,14 @@ public class LinkedInTokenValidator implements TokenValidator {
private Environment environment;
private ApiContext apiContext;
private AuthenticationService authenticationService;
private AuthenticationServiceImpl authenticationServiceImpl;
private LinkedInServiceProvider linkedInServiceProvider;
@Autowired
public LinkedInTokenValidator(Environment environment, ApiContext apiContext, AuthenticationService authenticationService) {
public LinkedInTokenValidator(Environment environment, ApiContext apiContext, AuthenticationServiceImpl authenticationServiceImpl) {
this.environment = environment;
this.apiContext = apiContext;
this.authenticationService = authenticationService;
this.authenticationServiceImpl = authenticationServiceImpl;
this.linkedInServiceProvider = new LinkedInServiceProvider(this.environment.getProperty("linkedin.login.clientId"), this.environment.getProperty("linkedin.login.clientSecret"));
}
@ -52,6 +52,6 @@ public class LinkedInTokenValidator implements TokenValidator {
user.setName(linkedInProfile.getFirstName() + " " + linkedInProfile.getLastName());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.LINKEDIN);
user.setSecret(accessGrant.getAccessToken());
return this.authenticationService.Touch(user);
return this.authenticationServiceImpl.Touch(user);
}
}

View File

@ -8,7 +8,7 @@ import eu.eudat.models.security.Principal;
import eu.eudat.security.validators.TokenValidator;
import eu.eudat.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.services.ApiContext;
import eu.eudat.services.AuthenticationService;
import eu.eudat.services.operations.AuthenticationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.social.oauth1.AuthorizedRequestToken;
@ -28,14 +28,14 @@ public class TwitterTokenValidator implements TokenValidator {
private Environment environment;
private ApiContext apiContext;
private AuthenticationService authenticationService;
private AuthenticationServiceImpl authenticationServiceImpl;
private TwitterServiceProvider twitterServiceProvider;
@Autowired
public TwitterTokenValidator(Environment environment, ApiContext apiContext, AuthenticationService authenticationService) {
public TwitterTokenValidator(Environment environment, ApiContext apiContext, AuthenticationServiceImpl authenticationServiceImpl) {
this.environment = environment;
this.apiContext = apiContext;
this.authenticationService = authenticationService;
this.authenticationServiceImpl = authenticationServiceImpl;
this.twitterServiceProvider = new TwitterServiceProvider(this.environment.getProperty("twitter.login.clientId"), this.environment.getProperty("twitter.login.clientSecret"));
}
@ -58,7 +58,7 @@ public class TwitterTokenValidator implements TokenValidator {
user.setName(profile.getName());
user.setProvider(TokenValidatorFactoryImpl.LoginProvider.TWITTER);
user.setSecret(finalOauthToken.getValue());
return this.authenticationService.Touch(user);
return this.authenticationServiceImpl.Touch(user);
}
public OAuthToken getRequestToken() {

View File

@ -1,23 +1,14 @@
package eu.eudat.services;
import eu.eudat.builders.BuilderFactory;
import eu.eudat.proxy.fetching.RemoteFetcher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import eu.eudat.services.helpers.HelpersService;
import eu.eudat.services.operations.OperationsContext;
import eu.eudat.services.utilities.UtilitiesService;
public interface ApiContext {
DatabaseRepository getDatabaseRepository();
ApplicationContext getApplicationContext();
HelpersService getHelpersService();
InvitationService getInvitationService();
OperationsContext getOperationsContext();
RemoteFetcher getRemoteFetcher();
MailService getMailService();
MessageSource getMessageSource();
BuilderFactory getBuilderFactory();
UtilitiesService getUtilitiesService();
}

View File

@ -1,91 +1,36 @@
package eu.eudat.services;
import eu.eudat.builders.BuilderFactory;
import eu.eudat.proxy.fetching.RemoteFetcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import eu.eudat.services.helpers.HelpersService;
import eu.eudat.services.operations.OperationsContext;
import eu.eudat.services.utilities.UtilitiesService;
import org.springframework.stereotype.Service;
@Service("apiContext")
public class ApiContextImpl implements ApiContext {
private DatabaseRepository databaseRepository;
private ApplicationContext applicationContext;
private RemoteFetcher remoteFetcher;
private InvitationService invitationService;
private MailService mailService;
private MessageSource messageSource;
private BuilderFactory builderFactory;
private OperationsContext operationsContext;
private HelpersService helpersService;
private UtilitiesService utilitiesService;
@Autowired
public void setDatabaseRepository(DatabaseRepository databaseRepository) {
this.databaseRepository = databaseRepository;
public ApiContextImpl(OperationsContext operationsContext, HelpersService helpersService, UtilitiesService utilitiesService) {
this.operationsContext = operationsContext;
this.helpersService = helpersService;
this.utilitiesService = utilitiesService;
}
@Override
public DatabaseRepository getDatabaseRepository() {
return databaseRepository;
public OperationsContext getOperationsContext() {
return operationsContext;
}
@Override
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
public HelpersService getHelpersService() {
return helpersService;
}
@Override
public RemoteFetcher getRemoteFetcher() {
return remoteFetcher;
}
@Autowired
public void setRemoteFetcher(RemoteFetcher remoteFetcher) {
this.remoteFetcher = remoteFetcher;
}
@Override
public InvitationService getInvitationService() {
return invitationService;
}
@Autowired
public void setInvitationService(InvitationService invitationService) {
this.invitationService = invitationService;
}
@Override
public MailService getMailService() {
return mailService;
}
@Autowired
public void setMailService(MailService mailService) {
this.mailService = mailService;
}
@Override
public MessageSource getMessageSource() {
return messageSource;
}
@Autowired
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
@Override
public BuilderFactory getBuilderFactory() {
return builderFactory;
}
@Autowired
public void setBuilderFactory(BuilderFactory builderFactory) {
this.builderFactory = builderFactory;
public UtilitiesService getUtilitiesService() {
return utilitiesService;
}
}

View File

@ -0,0 +1,45 @@
package eu.eudat.services.forms;
import eu.eudat.models.user.components.commons.Rule;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
/**
* Created by ikalyvas on 3/5/2018.
*/
public class VisibilityContext {
private List<VisibilityRule> visibilityRules = new LinkedList<>();
public List<VisibilityRule> getVisibilityRules() {
return visibilityRules;
}
public VisibilityRule get(String id) {
Optional<VisibilityRule> rule = visibilityRules.stream().filter(item -> item.getVisibilityRuleTargetId().equals(id)).findFirst();
if (rule.isPresent()) return rule.get();
return null;
}
public void buildVisibilityContext(List<Rule> sources) {
sources.forEach(this::addToVisibilityRulesContext);
}
private void addToVisibilityRulesContext(Rule item) {
VisibilityRuleSource source = new VisibilityRuleSource();
source.setVisibilityRuleSourceId(item.getSourceField());
source.setVisibilityRuleSourceValue(item.getRequiredValue());
Optional<VisibilityRule> visibilityRuleOptional = visibilityRules.stream().filter(rule -> rule.getVisibilityRuleTargetId().equals(item.getTargetField())).findFirst();
if (visibilityRuleOptional.isPresent()) visibilityRuleOptional.get().getVisibilityRuleSources().add(source);
else {
List<VisibilityRuleSource> sources = new LinkedList<>();
sources.add(source);
VisibilityRule visibilityRule = new VisibilityRule();
visibilityRule.setVisibilityRuleTargetId(item.getTargetField());
visibilityRule.setVisibilityRuleSources(sources);
this.visibilityRules.add(visibilityRule);
}
}
}

View File

@ -0,0 +1,27 @@
package eu.eudat.services.forms;
import java.util.List;
/**
* Created by ikalyvas on 3/5/2018.
*/
public class VisibilityRule {
private String visibilityRuleTargetId;
private List<VisibilityRuleSource> visibilityRuleSources;
public String getVisibilityRuleTargetId() {
return visibilityRuleTargetId;
}
public void setVisibilityRuleTargetId(String visibilityRuleTargetId) {
this.visibilityRuleTargetId = visibilityRuleTargetId;
}
public List<VisibilityRuleSource> getVisibilityRuleSources() {
return visibilityRuleSources;
}
public void setVisibilityRuleSources(List<VisibilityRuleSource> visibilityRuleSources) {
this.visibilityRuleSources = visibilityRuleSources;
}
}

View File

@ -0,0 +1,17 @@
package eu.eudat.services.forms;
import eu.eudat.models.user.components.commons.Rule;
import java.util.List;
import java.util.Map;
/**
* Created by ikalyvas on 3/5/2018.
*/
public interface VisibilityRuleService {
Boolean isElementVisible(String id);
void buildVisibilityContext(List<Rule> sources);
void setProperties(Map<String, Object> properties);
}

View File

@ -0,0 +1,46 @@
package eu.eudat.services.forms;
import eu.eudat.models.user.components.commons.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by ikalyvas on 3/5/2018.
*/
@Service("visibilityRuleService")
public class VisibilityRuleServiceImpl implements VisibilityRuleService {
private Map<String, Boolean> elementVisibility = new HashMap<>();
private VisibilityContext visibilityContext;
private Map<String, Object> properties;
public Boolean isElementVisible(String id) {
if (!this.elementVisibility.containsKey(id) || this.elementVisibility.get(id)) return true;
return false;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
public void buildVisibilityContext(List<Rule> sources) {
this.visibilityContext = new VisibilityContext();
this.visibilityContext.buildVisibilityContext(sources);
this.visibilityContext.getVisibilityRules().forEach(item-> this.evaluateVisibility(item));
}
private void evaluateVisibility(VisibilityRule rule) {
List<VisibilityRuleSource> sources = rule.getVisibilityRuleSources();
for(int i = 0; i < sources.size(); i++){
if (!properties.containsKey(sources.get(i).getVisibilityRuleSourceId()) || !properties.get(sources.get(i).getVisibilityRuleSourceId()).equals(sources.get(i).getVisibilityRuleSourceValue())) {
this.elementVisibility.put(rule.getVisibilityRuleTargetId(), false);
return;
}else{
this.elementVisibility.put(rule.getVisibilityRuleTargetId(), true);
}
}
}
}

View File

@ -0,0 +1,25 @@
package eu.eudat.services.forms;
/**
* Created by ikalyvas on 3/5/2018.
*/
public class VisibilityRuleSource {
private String visibilityRuleSourceId;
private String visibilityRuleSourceValue;
public String getVisibilityRuleSourceId() {
return visibilityRuleSourceId;
}
public void setVisibilityRuleSourceId(String visibilityRuleSourceId) {
this.visibilityRuleSourceId = visibilityRuleSourceId;
}
public String getVisibilityRuleSourceValue() {
return visibilityRuleSourceValue;
}
public void setVisibilityRuleSourceValue(String visibilityRuleSourceValue) {
this.visibilityRuleSourceValue = visibilityRuleSourceValue;
}
}

View File

@ -0,0 +1,13 @@
package eu.eudat.services.helpers;
import org.springframework.context.MessageSource;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface HelpersService {
MessageSource getMessageSource();
LoggerService getLoggerService();
}

View File

@ -0,0 +1,31 @@
package eu.eudat.services.helpers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
/**
* Created by ikalyvas on 3/1/2018.
*/
@Service("helpersService")
public class HelpersServiceImpl implements HelpersService {
private MessageSource messageSource;
private LoggerService loggerService;
@Autowired
public HelpersServiceImpl(MessageSource messageSource, LoggerService loggerService) {
this.messageSource = messageSource;
this.loggerService = loggerService;
}
@Override
public MessageSource getMessageSource() {
return messageSource;
}
@Override
public LoggerService getLoggerService() {
return loggerService;
}
}

View File

@ -0,0 +1,12 @@
package eu.eudat.services.helpers;
import eu.eudat.types.WarningLevel;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface LoggerService {
void log(String message);
void log(String message, WarningLevel level);
}

View File

@ -0,0 +1,39 @@
package eu.eudat.services.helpers;
import eu.eudat.types.WarningLevel;
import eu.eudat.utilities.interfaces.Applier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ikalyvas on 3/1/2018.
*/
@Service("loggerService")
public class LoggerServiceImpl implements LoggerService {
private static final Logger logger = LoggerFactory.getLogger(LoggerServiceImpl.class);
private WarningLevel level;
private Map<WarningLevel, Applier<Logger, String>> options = new HashMap<>();
public void setLevel(WarningLevel level) {
this.level = level;
}
public LoggerServiceImpl() {
this.options.put(WarningLevel.DEBUG, (logger, message) -> logger.debug(message));
this.options.put(WarningLevel.INFO, (logger, message) -> logger.info(message));
this.options.put(WarningLevel.WARN, (logger, message) -> logger.warn(message));
this.options.put(WarningLevel.ERROR, (logger, message) -> logger.error(message));
}
public void log(String message) {
this.options.get(this.level).apply(logger, message);
}
public void log(String message, WarningLevel level) {
this.options.get(level).apply(logger, message);
}
}

View File

@ -0,0 +1,23 @@
package eu.eudat.services.operations;
import eu.eudat.entities.Credential;
import eu.eudat.entities.UserToken;
import eu.eudat.models.login.Credentials;
import eu.eudat.models.loginprovider.LoginProviderUser;
import eu.eudat.models.security.Principal;
import java.util.UUID;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface AuthenticationService {
Principal Touch(LoginProviderUser profile);
Principal Touch(Credentials credentials);
void Logout(UUID token);
Principal Touch(UUID token);
}

View File

@ -1,4 +1,4 @@
package eu.eudat.services;
package eu.eudat.services.operations;
import eu.eudat.builders.entity.CredentialBuilder;
import eu.eudat.builders.entity.UserInfoBuilder;
@ -13,6 +13,7 @@ import eu.eudat.models.login.Credentials;
import eu.eudat.models.loginprovider.LoginProviderUser;
import eu.eudat.models.security.Principal;
import eu.eudat.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.services.ApiContext;
import eu.eudat.types.Authorities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
@ -22,41 +23,41 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service("authenticationService ")
public class AuthenticationService {
@Service("authenticationService")
public class AuthenticationServiceImpl implements AuthenticationService {
private ApiContext apiContext;
private Environment environment;
@Autowired
public AuthenticationService(ApiContext apiContext, Environment environment) {
public AuthenticationServiceImpl(ApiContext apiContext, Environment environment) {
this.environment = environment;
this.apiContext = apiContext;
}
public Principal Touch(UUID token) {
UserToken tokenEntry = this.apiContext.getDatabaseRepository().getUserTokenDao().find(token);
UserToken tokenEntry = this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().find(token);
if (tokenEntry == null || tokenEntry.getExpiresAt().before(new Date())) return null;
return this.Touch(tokenEntry);
}
public void Logout(UUID token) {
UserToken tokenEntry = this.apiContext.getDatabaseRepository().getUserTokenDao().find(token);
this.apiContext.getDatabaseRepository().getUserTokenDao().delete(tokenEntry);
UserToken tokenEntry = this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().find(token);
this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().delete(tokenEntry);
}
private Principal Touch(UserToken token) {
if (token == null || token.getExpiresAt().before(new Date())) return null;
UserInfo user = this.apiContext.getDatabaseRepository().getUserInfoDao().find(token.getUser().getId());
UserInfo user = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(token.getUser().getId());
if (user == null) return null;
Principal principal = this.apiContext.getBuilderFactory().getBuilder(PrincipalBuilder.class)
Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class)
.id(user.getId()).token(token.getToken())
.expiresAt(token.getExpiresAt()).name(user.getName())
.build();
List<UserRole> userRoles = apiContext.getDatabaseRepository().getUserRoleDao().getUserRoles(user);
List<UserRole> userRoles = apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().getUserRoles(user);
for (UserRole item : userRoles) {
if (principal.getAuthz() == null) principal.setAuthorities(new HashSet<>());
principal.getAuthz().add(Authorities.fromInteger(item.getRole()));
@ -65,7 +66,7 @@ public class AuthenticationService {
}
public Principal Touch(Credentials credentials) {
Credential credential = this.apiContext.getDatabaseRepository().getCredentialDao().getLoggedInCredentials(credentials);
Credential credential = this.apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().getLoggedInCredentials(credentials);
if (credential == null && credentials.getUsername().equals(environment.getProperty("autouser.root.username"))) {
try {
@ -77,12 +78,12 @@ public class AuthenticationService {
}
if (credential == null) return null;
UserToken userToken = this.apiContext.getBuilderFactory().getBuilder(UserTokenBuilder.class)
UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class)
.issuedAt(new Date()).user(credential.getUserInfo())
.token(UUID.randomUUID()).expiresAt(addADay(new Date()))
.build();
userToken = apiContext.getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
userToken = apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
return this.Touch(userToken);
@ -92,38 +93,38 @@ public class AuthenticationService {
UserInfoCriteria criteria = new UserInfoCriteria();
criteria.setEmail(profile.getEmail());
UserInfo userInfo = apiContext.getDatabaseRepository().getUserInfoDao().asQueryable().withHint("userInfo").where((builder, root) -> builder.equal(root.get("email"), profile.getEmail())).getSingleOrDefault();
UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().withHint("userInfo").where((builder, root) -> builder.equal(root.get("email"), profile.getEmail())).getSingleOrDefault();
if(userInfo == null){
Optional<Credential> optionalCredential = Optional.ofNullable(apiContext.getDatabaseRepository().getCredentialDao()
if (userInfo == null) {
Optional<Credential> optionalCredential = Optional.ofNullable(apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao()
.asQueryable().withHint("credentialUserInfo")
.where((builder, root) -> builder.and(builder.equal(root.get("provider"), profile.getProvider().getValue()), builder.equal(root.get("externalId"), profile.getId())))
.getSingleOrDefault());
userInfo = optionalCredential.map(Credential::getUserInfo).orElse(null);
}
final Credential credential = this.apiContext.getBuilderFactory().getBuilder(CredentialBuilder.class)
final Credential credential = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(CredentialBuilder.class)
.id(UUID.randomUUID()).creationTime(new Date()).status(1)
.lastUpdateTime(new Date()).provider((int) profile.getProvider().getValue())
.secret(profile.getSecret()).externalId(profile.getId())
.build();
if (userInfo == null) {
userInfo = this.apiContext.getBuilderFactory().getBuilder(UserInfoBuilder.class)
userInfo = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class)
.name(profile.getName()).verified_email(profile.getIsVerified())
.email(profile.getEmail()).created(new Date()).lastloggedin(new Date())
.authorization_level((short) 1).usertype((short) 1)
.build();
userInfo = apiContext.getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
credential.setPublicValue(userInfo.getName());
credential.setUserInfo(userInfo);
apiContext.getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
UserRole role = new UserRole();
role.setRole(Authorities.USER.getValue());
role.setUserInfo(userInfo);
apiContext.getDatabaseRepository().getUserRoleDao().createOrUpdate(role);
apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(role);
} else {
userInfo.setLastloggedin(new Date());
@ -135,18 +136,18 @@ public class AuthenticationService {
credential.setUserInfo(userInfo);
credential.setId(UUID.randomUUID());
credential.setPublicValue(userInfo.getName());
apiContext.getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
userInfo.getCredentials().add(credential);
}
userInfo = apiContext.getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
}
UserToken userToken = this.apiContext.getBuilderFactory().getBuilder(UserTokenBuilder.class)
UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class)
.token(UUID.randomUUID()).user(userInfo)
.expiresAt(addADay(new Date())).issuedAt(new Date())
.build();
apiContext.getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
return Touch(userToken.getToken());
}
@ -165,24 +166,24 @@ public class AuthenticationService {
if (!environment.getProperty("autouser.root.username").equals(username) || !environment.getProperty("autouser.root.password").equals(password))
return null;
UserInfo userInfo = this.apiContext.getBuilderFactory().getBuilder(UserInfoBuilder.class)
UserInfo userInfo = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class)
.name(username).email(environment.getProperty("autouser.root.email")).created(new Date())
.lastloggedin(new Date()).authorization_level((short) 1).usertype((short) 1)
.build();
userInfo = this.apiContext.getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
userInfo = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo);
UserRole role = new UserRole();
role.setRole(Authorities.ADMIN.getValue());
role.setUserInfo(userInfo);
this.apiContext.getDatabaseRepository().getUserRoleDao().createOrUpdate(role);
this.apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(role);
Credential credential = this.apiContext.getBuilderFactory().getBuilder(CredentialBuilder.class)
Credential credential = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(CredentialBuilder.class)
.userInfo(userInfo).publicValue(username).secret(password)
.provider((int) TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue())
.creationTime(new Date()).lastUpdateTime(new Date()).status(0)
.build();
return this.apiContext.getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
return this.apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential);
}
}

View File

@ -1,4 +1,4 @@
package eu.eudat.services;
package eu.eudat.services.operations;
import eu.eudat.dao.entities.*;
import eu.eudat.dao.entities.security.CredentialDao;

View File

@ -1,4 +1,4 @@
package eu.eudat.services;
package eu.eudat.services.operations;
import eu.eudat.dao.entities.*;
import eu.eudat.dao.entities.security.CredentialDao;

View File

@ -0,0 +1,20 @@
package eu.eudat.services.operations;
import eu.eudat.builders.BuilderFactory;
import eu.eudat.proxy.fetching.RemoteFetcher;
import org.springframework.context.ApplicationContext;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface OperationsContext {
DatabaseRepository getDatabaseRepository();
ApplicationContext getApplicationContext();
BuilderFactory getBuilderFactory();
RemoteFetcher getRemoteFetcher();
}

View File

@ -0,0 +1,48 @@
package eu.eudat.services.operations;
import eu.eudat.builders.BuilderFactory;
import eu.eudat.proxy.fetching.RemoteFetcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
/**
* Created by ikalyvas on 3/1/2018.
*/
@Service("operationsContext")
public class OperationsContextImpl implements OperationsContext {
private DatabaseRepository databaseRepository;
private ApplicationContext applicationContext;
private RemoteFetcher remoteFetcher;
private BuilderFactory builderFactory;
@Autowired
public OperationsContextImpl(DatabaseRepository databaseRepository, ApplicationContext applicationContext, RemoteFetcher remoteFetcher, BuilderFactory builderFactory) {
this.databaseRepository = databaseRepository;
this.applicationContext = applicationContext;
this.remoteFetcher = remoteFetcher;
this.builderFactory = builderFactory;
}
@Override
public DatabaseRepository getDatabaseRepository() {
return databaseRepository;
}
@Override
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public RemoteFetcher getRemoteFetcher() {
return remoteFetcher;
}
@Override
public BuilderFactory getBuilderFactory() {
return builderFactory;
}
}

View File

@ -1,4 +1,4 @@
package eu.eudat.services;
package eu.eudat.services.utilities;
import eu.eudat.dao.entities.DMPDao;

View File

@ -1,4 +1,4 @@
package eu.eudat.services;
package eu.eudat.services.utilities;
import eu.eudat.dao.entities.DMPDao;
import eu.eudat.dao.entities.InvitationDao;

View File

@ -1,4 +1,4 @@
package eu.eudat.services;
package eu.eudat.services.utilities;
import eu.eudat.models.mail.SimpleMail;

View File

@ -1,4 +1,4 @@
package eu.eudat.services;
package eu.eudat.services.utilities;
import eu.eudat.models.mail.SimpleMail;
import org.springframework.beans.factory.annotation.Autowired;

View File

@ -0,0 +1,15 @@
package eu.eudat.services.utilities;
import eu.eudat.services.forms.VisibilityRuleService;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface UtilitiesService {
InvitationService getInvitationService();
MailService getMailService();
VisibilityRuleService getVisibilityRuleService();
}

View File

@ -0,0 +1,38 @@
package eu.eudat.services.utilities;
import eu.eudat.services.forms.VisibilityRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by ikalyvas on 3/1/2018.
*/
@Service("utilitiesService")
public class UtilitiesServiceImpl implements UtilitiesService {
private InvitationService invitationService;
private MailService mailService;
private VisibilityRuleService visibilityRuleService;
@Autowired
public UtilitiesServiceImpl(InvitationService invitationService, MailService mailService, VisibilityRuleService visibilityRuleService) {
this.invitationService = invitationService;
this.mailService = mailService;
this.visibilityRuleService = visibilityRuleService;
}
@Override
public VisibilityRuleService getVisibilityRuleService() {
return visibilityRuleService;
}
@Override
public InvitationService getInvitationService() {
return invitationService;
}
@Override
public MailService getMailService() {
return mailService;
}
}

View File

@ -0,0 +1,29 @@
package eu.eudat.types;
/**
* Created by ikalyvas on 3/5/2018.
*/
public enum ApiResponseType {
JSON_RESPONSE(0), FILE_RESPONSE(1);
private Integer value;
private ApiResponseType(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
public static ApiResponseType fromInteger(Integer value) {
switch (value) {
case 0:
return JSON_RESPONSE;
case 200:
return FILE_RESPONSE;
default:
throw new RuntimeException("Unsupported Api Response Type Code");
}
}
}

View File

@ -0,0 +1,8 @@
package eu.eudat.types;
/**
* Created by ikalyvas on 3/1/2018.
*/
public enum WarningLevel {
INFO, WARN, DEBUG, ERROR
}

View File

@ -1,8 +1,8 @@
package eu.eudat.utilities.interfaces;
/**
* Created by ikalyvas on 2/27/2018.
* Created by ikalyvas on 3/1/2018.
*/
public interface Applier<A, V, R> {
R apply(A applier, V value);
public interface Applier<A, V> {
void apply(A applier, V value);
}

View File

@ -0,0 +1,8 @@
package eu.eudat.utilities.interfaces;
/**
* Created by ikalyvas on 2/27/2018.
*/
public interface ApplierWithValue<A, V, R> {
R apply(A applier, V value);
}

View File

@ -55,4 +55,6 @@ b2access.externallogin.user_info_url = https://b2access-integration.fz-juelich.d
b2access.externallogin.access_token_url = https://b2access-integration.fz-juelich.de:443/oauth2/token
b2access.externallogin.redirect_uri = http://dmp.eudat.org:4200/api/oauth/authorized/b2access
b2access.externallogin.clientid = eudatdmptool
b2access.externallogin.clientSecret = A3b*1*92
b2access.externallogin.clientSecret = A3b*1*92
#################################################################################
pdf.converter.url = http://localhost/

Binary file not shown.

View File

@ -356,6 +356,11 @@
"integrity": "sha512-q3zfJvaTroV5BjAAR+peTHEGAAhGrPX0z2EzCzpt2mwFA+qzUn2nigJLqSekXRtdULKmT8am7zjvTMZSapIgHw==",
"dev": true
},
"@types/file-saver": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@types/file-saver/-/file-saver-1.3.0.tgz",
"integrity": "sha512-fC12hKtEzVkrV/ZRcrmqvpHG/TMYDZtgpAmgMUA4F7KneDaQeFMwmPz8AfygKKJMqsdTi8bL+E+fciaaMLxUhg=="
},
"@types/minimist": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.0.tgz",
@ -1234,7 +1239,6 @@
"requires": {
"anymatch": "1.3.2",
"async-each": "1.0.1",
"fsevents": "1.1.3",
"glob-parent": "2.0.0",
"inherits": "2.0.3",
"is-binary-path": "1.0.1",
@ -2660,6 +2664,11 @@
"schema-utils": "0.3.0"
}
},
"file-saver": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/file-saver/-/file-saver-1.3.3.tgz",
"integrity": "sha1-zdTETTqiZOrC9o7BZbx5HDSvEjI="
},
"filename-regex": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz",
@ -2830,910 +2839,6 @@
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
"dev": true
},
"fsevents": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.1.3.tgz",
"integrity": "sha512-WIr7iDkdmdbxu/Gh6eKEZJL6KPE74/5MEsf2whTOFNxbIoIixogroLdKYqB6FDav4Wavh/lZdzzd3b2KxIXC5Q==",
"dev": true,
"optional": true,
"requires": {
"nan": "2.8.0",
"node-pre-gyp": "0.6.39"
},
"dependencies": {
"abbrev": {
"version": "1.1.0",
"bundled": true,
"dev": true,
"optional": true
},
"ajv": {
"version": "4.11.8",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"co": "4.6.0",
"json-stable-stringify": "1.0.1"
}
},
"ansi-regex": {
"version": "2.1.1",
"bundled": true,
"dev": true
},
"aproba": {
"version": "1.1.1",
"bundled": true,
"dev": true,
"optional": true
},
"are-we-there-yet": {
"version": "1.1.4",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"delegates": "1.0.0",
"readable-stream": "2.2.9"
}
},
"asn1": {
"version": "0.2.3",
"bundled": true,
"dev": true,
"optional": true
},
"assert-plus": {
"version": "0.2.0",
"bundled": true,
"dev": true,
"optional": true
},
"asynckit": {
"version": "0.4.0",
"bundled": true,
"dev": true,
"optional": true
},
"aws-sign2": {
"version": "0.6.0",
"bundled": true,
"dev": true,
"optional": true
},
"aws4": {
"version": "1.6.0",
"bundled": true,
"dev": true,
"optional": true
},
"balanced-match": {
"version": "0.4.2",
"bundled": true,
"dev": true
},
"bcrypt-pbkdf": {
"version": "1.0.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"tweetnacl": "0.14.5"
}
},
"block-stream": {
"version": "0.0.9",
"bundled": true,
"dev": true,
"requires": {
"inherits": "2.0.3"
}
},
"boom": {
"version": "2.10.1",
"bundled": true,
"dev": true,
"requires": {
"hoek": "2.16.3"
}
},
"brace-expansion": {
"version": "1.1.7",
"bundled": true,
"dev": true,
"requires": {
"balanced-match": "0.4.2",
"concat-map": "0.0.1"
}
},
"buffer-shims": {
"version": "1.0.0",
"bundled": true,
"dev": true
},
"caseless": {
"version": "0.12.0",
"bundled": true,
"dev": true,
"optional": true
},
"co": {
"version": "4.6.0",
"bundled": true,
"dev": true,
"optional": true
},
"code-point-at": {
"version": "1.1.0",
"bundled": true,
"dev": true
},
"combined-stream": {
"version": "1.0.5",
"bundled": true,
"dev": true,
"requires": {
"delayed-stream": "1.0.0"
}
},
"concat-map": {
"version": "0.0.1",
"bundled": true,
"dev": true
},
"console-control-strings": {
"version": "1.1.0",
"bundled": true,
"dev": true
},
"core-util-is": {
"version": "1.0.2",
"bundled": true,
"dev": true
},
"cryptiles": {
"version": "2.0.5",
"bundled": true,
"dev": true,
"requires": {
"boom": "2.10.1"
}
},
"dashdash": {
"version": "1.14.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"assert-plus": "1.0.0"
},
"dependencies": {
"assert-plus": {
"version": "1.0.0",
"bundled": true,
"dev": true,
"optional": true
}
}
},
"debug": {
"version": "2.6.8",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"ms": "2.0.0"
}
},
"deep-extend": {
"version": "0.4.2",
"bundled": true,
"dev": true,
"optional": true
},
"delayed-stream": {
"version": "1.0.0",
"bundled": true,
"dev": true
},
"delegates": {
"version": "1.0.0",
"bundled": true,
"dev": true,
"optional": true
},
"detect-libc": {
"version": "1.0.2",
"bundled": true,
"dev": true,
"optional": true
},
"ecc-jsbn": {
"version": "0.1.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"jsbn": "0.1.1"
}
},
"extend": {
"version": "3.0.1",
"bundled": true,
"dev": true,
"optional": true
},
"extsprintf": {
"version": "1.0.2",
"bundled": true,
"dev": true
},
"forever-agent": {
"version": "0.6.1",
"bundled": true,
"dev": true,
"optional": true
},
"form-data": {
"version": "2.1.4",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"asynckit": "0.4.0",
"combined-stream": "1.0.5",
"mime-types": "2.1.15"
}
},
"fs.realpath": {
"version": "1.0.0",
"bundled": true,
"dev": true
},
"fstream": {
"version": "1.0.11",
"bundled": true,
"dev": true,
"requires": {
"graceful-fs": "4.1.11",
"inherits": "2.0.3",
"mkdirp": "0.5.1",
"rimraf": "2.6.1"
}
},
"fstream-ignore": {
"version": "1.0.5",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"fstream": "1.0.11",
"inherits": "2.0.3",
"minimatch": "3.0.4"
}
},
"gauge": {
"version": "2.7.4",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"aproba": "1.1.1",
"console-control-strings": "1.1.0",
"has-unicode": "2.0.1",
"object-assign": "4.1.1",
"signal-exit": "3.0.2",
"string-width": "1.0.2",
"strip-ansi": "3.0.1",
"wide-align": "1.1.2"
}
},
"getpass": {
"version": "0.1.7",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"assert-plus": "1.0.0"
},
"dependencies": {
"assert-plus": {
"version": "1.0.0",
"bundled": true,
"dev": true,
"optional": true
}
}
},
"glob": {
"version": "7.1.2",
"bundled": true,
"dev": true,
"requires": {
"fs.realpath": "1.0.0",
"inflight": "1.0.6",
"inherits": "2.0.3",
"minimatch": "3.0.4",
"once": "1.4.0",
"path-is-absolute": "1.0.1"
}
},
"graceful-fs": {
"version": "4.1.11",
"bundled": true,
"dev": true
},
"har-schema": {
"version": "1.0.5",
"bundled": true,
"dev": true,
"optional": true
},
"har-validator": {
"version": "4.2.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"ajv": "4.11.8",
"har-schema": "1.0.5"
}
},
"has-unicode": {
"version": "2.0.1",
"bundled": true,
"dev": true,
"optional": true
},
"hawk": {
"version": "3.1.3",
"bundled": true,
"dev": true,
"requires": {
"boom": "2.10.1",
"cryptiles": "2.0.5",
"hoek": "2.16.3",
"sntp": "1.0.9"
}
},
"hoek": {
"version": "2.16.3",
"bundled": true,
"dev": true
},
"http-signature": {
"version": "1.1.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"assert-plus": "0.2.0",
"jsprim": "1.4.0",
"sshpk": "1.13.0"
}
},
"inflight": {
"version": "1.0.6",
"bundled": true,
"dev": true,
"requires": {
"once": "1.4.0",
"wrappy": "1.0.2"
}
},
"inherits": {
"version": "2.0.3",
"bundled": true,
"dev": true
},
"ini": {
"version": "1.3.4",
"bundled": true,
"dev": true,
"optional": true
},
"is-fullwidth-code-point": {
"version": "1.0.0",
"bundled": true,
"dev": true,
"requires": {
"number-is-nan": "1.0.1"
}
},
"is-typedarray": {
"version": "1.0.0",
"bundled": true,
"dev": true,
"optional": true
},
"isarray": {
"version": "1.0.0",
"bundled": true,
"dev": true
},
"isstream": {
"version": "0.1.2",
"bundled": true,
"dev": true,
"optional": true
},
"jodid25519": {
"version": "1.0.2",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"jsbn": "0.1.1"
}
},
"jsbn": {
"version": "0.1.1",
"bundled": true,
"dev": true,
"optional": true
},
"json-schema": {
"version": "0.2.3",
"bundled": true,
"dev": true,
"optional": true
},
"json-stable-stringify": {
"version": "1.0.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"jsonify": "0.0.0"
}
},
"json-stringify-safe": {
"version": "5.0.1",
"bundled": true,
"dev": true,
"optional": true
},
"jsonify": {
"version": "0.0.0",
"bundled": true,
"dev": true,
"optional": true
},
"jsprim": {
"version": "1.4.0",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"assert-plus": "1.0.0",
"extsprintf": "1.0.2",
"json-schema": "0.2.3",
"verror": "1.3.6"
},
"dependencies": {
"assert-plus": {
"version": "1.0.0",
"bundled": true,
"dev": true,
"optional": true
}
}
},
"mime-db": {
"version": "1.27.0",
"bundled": true,
"dev": true
},
"mime-types": {
"version": "2.1.15",
"bundled": true,
"dev": true,
"requires": {
"mime-db": "1.27.0"
}
},
"minimatch": {
"version": "3.0.4",
"bundled": true,
"dev": true,
"requires": {
"brace-expansion": "1.1.7"
}
},
"minimist": {
"version": "0.0.8",
"bundled": true,
"dev": true
},
"mkdirp": {
"version": "0.5.1",
"bundled": true,
"dev": true,
"requires": {
"minimist": "0.0.8"
}
},
"ms": {
"version": "2.0.0",
"bundled": true,
"dev": true,
"optional": true
},
"node-pre-gyp": {
"version": "0.6.39",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"detect-libc": "1.0.2",
"hawk": "3.1.3",
"mkdirp": "0.5.1",
"nopt": "4.0.1",
"npmlog": "4.1.0",
"rc": "1.2.1",
"request": "2.81.0",
"rimraf": "2.6.1",
"semver": "5.3.0",
"tar": "2.2.1",
"tar-pack": "3.4.0"
}
},
"nopt": {
"version": "4.0.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"abbrev": "1.1.0",
"osenv": "0.1.4"
}
},
"npmlog": {
"version": "4.1.0",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"are-we-there-yet": "1.1.4",
"console-control-strings": "1.1.0",
"gauge": "2.7.4",
"set-blocking": "2.0.0"
}
},
"number-is-nan": {
"version": "1.0.1",
"bundled": true,
"dev": true
},
"oauth-sign": {
"version": "0.8.2",
"bundled": true,
"dev": true,
"optional": true
},
"object-assign": {
"version": "4.1.1",
"bundled": true,
"dev": true,
"optional": true
},
"once": {
"version": "1.4.0",
"bundled": true,
"dev": true,
"requires": {
"wrappy": "1.0.2"
}
},
"os-homedir": {
"version": "1.0.2",
"bundled": true,
"dev": true,
"optional": true
},
"os-tmpdir": {
"version": "1.0.2",
"bundled": true,
"dev": true,
"optional": true
},
"osenv": {
"version": "0.1.4",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"os-homedir": "1.0.2",
"os-tmpdir": "1.0.2"
}
},
"path-is-absolute": {
"version": "1.0.1",
"bundled": true,
"dev": true
},
"performance-now": {
"version": "0.2.0",
"bundled": true,
"dev": true,
"optional": true
},
"process-nextick-args": {
"version": "1.0.7",
"bundled": true,
"dev": true
},
"punycode": {
"version": "1.4.1",
"bundled": true,
"dev": true,
"optional": true
},
"qs": {
"version": "6.4.0",
"bundled": true,
"dev": true,
"optional": true
},
"rc": {
"version": "1.2.1",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"deep-extend": "0.4.2",
"ini": "1.3.4",
"minimist": "1.2.0",
"strip-json-comments": "2.0.1"
},
"dependencies": {
"minimist": {
"version": "1.2.0",
"bundled": true,
"dev": true,
"optional": true
}
}
},
"readable-stream": {
"version": "2.2.9",
"bundled": true,
"dev": true,
"requires": {
"buffer-shims": "1.0.0",
"core-util-is": "1.0.2",
"inherits": "2.0.3",
"isarray": "1.0.0",
"process-nextick-args": "1.0.7",
"string_decoder": "1.0.1",
"util-deprecate": "1.0.2"
}
},
"request": {
"version": "2.81.0",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"aws-sign2": "0.6.0",
"aws4": "1.6.0",
"caseless": "0.12.0",
"combined-stream": "1.0.5",
"extend": "3.0.1",
"forever-agent": "0.6.1",
"form-data": "2.1.4",
"har-validator": "4.2.1",
"hawk": "3.1.3",
"http-signature": "1.1.1",
"is-typedarray": "1.0.0",
"isstream": "0.1.2",
"json-stringify-safe": "5.0.1",
"mime-types": "2.1.15",
"oauth-sign": "0.8.2",
"performance-now": "0.2.0",
"qs": "6.4.0",
"safe-buffer": "5.0.1",
"stringstream": "0.0.5",
"tough-cookie": "2.3.2",
"tunnel-agent": "0.6.0",
"uuid": "3.0.1"
}
},
"rimraf": {
"version": "2.6.1",
"bundled": true,
"dev": true,
"requires": {
"glob": "7.1.2"
}
},
"safe-buffer": {
"version": "5.0.1",
"bundled": true,
"dev": true
},
"semver": {
"version": "5.3.0",
"bundled": true,
"dev": true,
"optional": true
},
"set-blocking": {
"version": "2.0.0",
"bundled": true,
"dev": true,
"optional": true
},
"signal-exit": {
"version": "3.0.2",
"bundled": true,
"dev": true,
"optional": true
},
"sntp": {
"version": "1.0.9",
"bundled": true,
"dev": true,
"requires": {
"hoek": "2.16.3"
}
},
"sshpk": {
"version": "1.13.0",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"asn1": "0.2.3",
"assert-plus": "1.0.0",
"bcrypt-pbkdf": "1.0.1",
"dashdash": "1.14.1",
"ecc-jsbn": "0.1.1",
"getpass": "0.1.7",
"jodid25519": "1.0.2",
"jsbn": "0.1.1",
"tweetnacl": "0.14.5"
},
"dependencies": {
"assert-plus": {
"version": "1.0.0",
"bundled": true,
"dev": true,
"optional": true
}
}
},
"string-width": {
"version": "1.0.2",
"bundled": true,
"dev": true,
"requires": {
"code-point-at": "1.1.0",
"is-fullwidth-code-point": "1.0.0",
"strip-ansi": "3.0.1"
}
},
"string_decoder": {
"version": "1.0.1",
"bundled": true,
"dev": true,
"requires": {
"safe-buffer": "5.0.1"
}
},
"stringstream": {
"version": "0.0.5",
"bundled": true,
"dev": true,
"optional": true
},
"strip-ansi": {
"version": "3.0.1",
"bundled": true,
"dev": true,
"requires": {
"ansi-regex": "2.1.1"
}
},
"strip-json-comments": {
"version": "2.0.1",
"bundled": true,
"dev": true,
"optional": true
},
"tar": {
"version": "2.2.1",
"bundled": true,
"dev": true,
"requires": {
"block-stream": "0.0.9",
"fstream": "1.0.11",
"inherits": "2.0.3"
}
},
"tar-pack": {
"version": "3.4.0",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"debug": "2.6.8",
"fstream": "1.0.11",
"fstream-ignore": "1.0.5",
"once": "1.4.0",
"readable-stream": "2.2.9",
"rimraf": "2.6.1",
"tar": "2.2.1",
"uid-number": "0.0.6"
}
},
"tough-cookie": {
"version": "2.3.2",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"punycode": "1.4.1"
}
},
"tunnel-agent": {
"version": "0.6.0",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"safe-buffer": "5.0.1"
}
},
"tweetnacl": {
"version": "0.14.5",
"bundled": true,
"dev": true,
"optional": true
},
"uid-number": {
"version": "0.0.6",
"bundled": true,
"dev": true,
"optional": true
},
"util-deprecate": {
"version": "1.0.2",
"bundled": true,
"dev": true
},
"uuid": {
"version": "3.0.1",
"bundled": true,
"dev": true,
"optional": true
},
"verror": {
"version": "1.3.6",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"extsprintf": "1.0.2"
}
},
"wide-align": {
"version": "1.1.2",
"bundled": true,
"dev": true,
"optional": true,
"requires": {
"string-width": "1.0.2"
}
},
"wrappy": {
"version": "1.0.2",
"bundled": true,
"dev": true
}
}
},
"fstream": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.11.tgz",

View File

@ -26,7 +26,9 @@
"@covalent/core": "^1.0.0-rc.1",
"@ngx-translate/core": "^9.0.1",
"@ngx-translate/http-loader": "^2.0.0",
"@types/file-saver": "^1.3.0",
"core-js": "^2.4.1",
"file-saver": "1.3.3",
"rxjs": "^5.5.6",
"zone.js": "^0.8.17"
},

View File

@ -3,9 +3,11 @@
<h3 *ngIf="!isNew">{{datasetWizardModel?.dmp?.project?.label}} Dataset</h3>
<button mat-raised-button color="primary" *ngIf="datasetWizardModel&&datasetWizardModel?.status != 1" style="margin-top: 15px;margin-bottom: 15px;margin-right: 15px;"
(click)="save();" type="button">Save</button>
<!-- .toString() -->
<!-- .toString() -->
<button mat-raised-button color="primary" *ngIf="datasetWizardModel&&datasetWizardModel?.status != 1" style="margin-top: 15px;margin-bottom: 15px;margin-right: 15px;"
(click)="saveFinalize();" type="button">Save and Finalize</button>
<button mat-raised-button color="primary" *ngIf="datasetWizardModel&&datasetWizardModel?.status == 1" style="margin-top: 15px;margin-bottom: 15px;margin-right: 15px;"
(click)="downloadPDF();" type="button">Download PDF</button>
<mat-horizontal-stepper [linear]="isLinear" #stepper>
<mat-step [stepControl]="formGroup">
<form *ngIf="formGroup" [formGroup]="formGroup">
@ -92,7 +94,8 @@
</mat-step>
<mat-step>
<ng-template matStepLabel>{{'DATASET-WIZARD.THIRD-STEP.TITLE' | translate}}</ng-template>
<dynamic-form class="full-width" *ngIf="formGroup && datasetWizardModel && datasetWizardModel.datasetProfileDefinition" [form]="this.formGroup.get('datasetProfileDefinition')" [dataModel]="datasetWizardModel"></dynamic-form>
<dynamic-form class="full-width" *ngIf="formGroup && datasetWizardModel && datasetWizardModel.datasetProfileDefinition" [form]="this.formGroup.get('datasetProfileDefinition')"
[dataModel]="datasetWizardModel"></dynamic-form>
<div class="navigation-buttons-container">
<button style="margin-top:10px;" matStepperPrevious mat-raised-button color="primary">{{'DATASET-WIZARD.ACTIONS.BACK' | translate}}</button>
</div>

View File

@ -17,7 +17,7 @@ import { TranslateService } from '@ngx-translate/core';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { Component, ViewChild, OnInit, AfterViewInit, ViewEncapsulation } from "@angular/core";
import { FormGroup, Validators, FormBuilder } from "@angular/forms";
import * as FileSaver from 'file-saver';
import { MatPaginator, MatSort, MatSnackBar, MatStepper } from "@angular/material";
@Component({
@ -28,7 +28,7 @@ import { MatPaginator, MatSort, MatSnackBar, MatStepper } from "@angular/materia
encapsulation: ViewEncapsulation.None
})
export class DatasetWizardComponent {
@ViewChild('stepper') stepper: MatStepper;
@ViewChild('stepper') stepper: MatStepper;
//dmpAutoCompleteConfiguration: AutoCompleteConfiguration;
//datasetProfileAutoCompleteConfiguration: AutoCompleteConfiguration;
@ -48,7 +48,7 @@ export class DatasetWizardComponent {
filteredRegistries: ExternalSourcesItemModel[];
filteredServices: ExternalSourcesItemModel[];
filteredExternalDatasets: ExternalSourcesItemModel[];
itemId: string
constructor(
private datasetWizardService: DatasetWizardService,
private formBuilder: FormBuilder,
@ -73,11 +73,11 @@ export class DatasetWizardComponent {
this.route.params.subscribe((params: Params) => {
const itemId = params['id'];
this.itemId = params['id'];
const dmpId = params['dmpId'];
if (itemId != null) {
if (this.itemId != null) {
this.isNew = false;
this.datasetWizardService.getSingle(itemId).map(data => data as DatasetWizardModel)
this.datasetWizardService.getSingle(this.itemId).map(data => data as DatasetWizardModel)
.subscribe(data => {
this.datasetWizardModel = JsonSerializer.fromJSONObject(data, DatasetWizardModel);
this.formGroup = this.datasetWizardModel.buildForm();
@ -105,7 +105,7 @@ export class DatasetWizardComponent {
ngAfterViewInit() {
this.route.params.subscribe((params: Params) => {
let itemId = params['id'];
if(itemId !=null) this.stepper.selectedIndex = 2;
if (itemId != null) this.stepper.selectedIndex = 2;
})
}
@ -126,9 +126,9 @@ export class DatasetWizardComponent {
getDefinition() {
if (this.isNew) {
this.datasetWizardService.getDefinition(this.formGroup.get("profile").get("id").value).subscribe(item => {
this.datasetWizardModel.datasetProfileDefinition = JsonSerializer.fromJSONObject(item,DatasetProfileDefinitionModel);
this.datasetWizardModel.datasetProfileDefinition = JsonSerializer.fromJSONObject(item, DatasetProfileDefinitionModel);
this.datasetProfileDefinitionModel = this.datasetWizardModel.datasetProfileDefinition;
this.formGroup.addControl("datasetProfileDefinition",this.datasetProfileDefinitionModel.buildForm())
this.formGroup.addControl("datasetProfileDefinition", this.datasetProfileDefinitionModel.buildForm())
})
}
}
@ -165,12 +165,12 @@ export class DatasetWizardComponent {
save() {
this.datasetWizardModel.status = "0";
this.formGroup.get("status").setValue("0");
this.submit();
}
saveFinalize() {
this.datasetWizardModel.status = "1";
this.formGroup.get("status").setValue("1");
this.submit();
}
@ -245,4 +245,32 @@ export class DatasetWizardComponent {
});
}
}
downloadPDF(): void {
this.datasetWizardService.downloadPDF(this.itemId).subscribe(response => {
const blob = new Blob([response.body], { type: 'application/pdf' })
const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
FileSaver.saveAs(blob, filename)
})
}
getFilenameFromContentDispositionHeader(header: string): string { // expecting filename=XXXX or filename="XXXX" to exist
// const regex: RegExp = new RegExp(/filename=((\"(.*)\")|([^;]*))/g);
const regex: RegExp = new RegExp(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/g);
const matches = header.match(regex);
let filename: string;
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
if (match.includes('filename="')) {
filename = match.substring(10, match.length - 1);
break;
} else if (match.includes('filename=')) {
filename = match.substring(9);
break;
}
}
return filename;
}
}

View File

@ -18,7 +18,7 @@
</div>
</div>
<div class="col-md-12" id="form-container">
<div *ngIf='datasetProfileDefinitionModel' class="col-md-12" id="form-container">
<!-- <form *ngIf="form" novalidate [formGroup]="form" (ngSubmit)="onSubmit()"> -->
<mat-vertical-stepper #stepper [linear]="false">
<div *ngFor="let page of datasetProfileDefinitionModel.pages let z=index;">

View File

@ -58,11 +58,11 @@ export class DynamicFormComponent implements OnInit {
ngOnInit() {
let rules: Rule[] = JsonSerializer.fromJSONArray(this.dataModel.datasetProfileDefinition.rules, Rule);
this.visibilityRulesService.formGroup = this.form;
this.visibilityRulesService.buildVisibilityRules(rules)
this.datasetProfileDefinitionModel = this.dataModel.datasetProfileDefinition
this.createPagination();
this.visibilityRulesService.formGroup = this.form;
let rules: Rule[] = JsonSerializer.fromJSONArray(this.datasetProfileDefinitionModel.rules, Rule);
this.visibilityRulesService.buildVisibilityRules(rules)
this.progressbar = true;
this.route.fragment.subscribe((fragment: string) => {

View File

@ -6,16 +6,17 @@ import { Serializable } from './interfaces/Serializable';
import { Multiplicity } from './Multiplicity';
import { DefaultValue } from './DefaultValue';
import { ValidationTypes } from '@app/models/common/ValidationTypes';
import { ViewStyle } from './datasetProfileAdmin/ViewStyle';
export class Field extends BaseModel implements Serializable<Field>, FormGenerator<FormGroup>{
public id: string;
public title: string;
public value: string;
public value: any;
public defaultValue: DefaultValue;
public description: string;
public extendedDescription: string;
public viewStyle: any;
public viewStyle: ViewStyle;
public defaultVisibility: boolean;
public page: number;
public multiplicity: Multiplicity;
@ -38,26 +39,29 @@ export class Field extends BaseModel implements Serializable<Field>, FormGenerat
this.defaultValue = JsonSerializer.fromJSONObject(item.defaultValue, DefaultValue);
this.value = this.defaultValue.value && !item.value ? this.defaultValue.value : item.value;
//this.multiplicity = new Multiplicity();
if (this.viewStyle.renderStyle === "checkBox") {
this.value = this.value === 'true';
}
//this.multiplicity.max = 2;
if(item.multiplicityItems)this.multiplicityItems = JsonSerializer.fromJSONArray(item.multiplicityItems, Field);
if (item.multiplicityItems) this.multiplicityItems = JsonSerializer.fromJSONArray(item.multiplicityItems, Field);
this.data = item.data;
return this;
}
buildForm(): FormGroup {
if(this.validations)
buildForm(): FormGroup {
if (this.validations)
this.validations.forEach(validation => {
if (validation == ValidationTypes.Required ) this.validationRequired = true;
if (validation == ValidationTypes.Required) this.validationRequired = true;
});
let formGroup = this.formBuilder.group({
id: [this.id],
data:[this.data],
data: [this.data],
/* title: [this.title], */
value: [this.value, this.validationRequired == true? Validators.required:null]/* ,
value: [this.value, this.validationRequired == true ? Validators.required : null]/* ,
description: [this.description],
extendedDescription:[this.extendedDescription],
viewStyle: [this.viewStyle],

View File

@ -2,7 +2,7 @@ import { DatasetProfileDefinitionModel } from '../../models/DatasetProfileDefini
import { DatasetWizardModel } from '../../models/datasets/DatasetWizardModel';
import { DatasetProfileCriteria } from '../../models/criteria/dataset-profile/DatasetProfileCriteria';
import 'rxjs/add/operator/map';
import { HttpHeaders } from '@angular/common/http';
import { HttpHeaders, HttpResponse, HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { HostConfiguration } from './../../app.constants';
import { BaseHttpService } from '../../utilities/cite-http-service-module/base-http.service';
@ -11,6 +11,7 @@ import { DataManagementPlanModel } from '../../models/data-managemnt-plans/DataM
import { DataManagementPlanCriteria } from '../../models/criteria/data-management-plan/DataManagementPlanCriteria';
import { RequestItem } from '../../models/criteria/RequestItem';
import { DatasetProfileModel } from '@app/models/datasetprofile/DatasetProfileModel';
import { ResponseContentType } from '@angular/http';
@Injectable()
@ -19,7 +20,7 @@ export class DatasetWizardService {
private actionUrl: string;
private headers: HttpHeaders;
constructor(private http: BaseHttpService) {
constructor(private http: BaseHttpService, private httpClient: HttpClient) {
this.actionUrl = HostConfiguration.Server + 'datasetwizard/';
@ -44,10 +45,9 @@ export class DatasetWizardService {
return this.http.post<DatasetWizardModel>(this.actionUrl + 'createOrUpdate', datasetModel, { headers: this.headers });
}
/* public saveDataset(datasetWizard: DatasetWizardModel, formValue) {
datasetWizard.properties = formValue;
return this.createDataset(datasetWizard)
} */
public downloadPDF(id: string): Observable<HttpResponse<Blob>> {
return this.httpClient.get(this.actionUrl + 'getWordDocument/' + id, { responseType: 'blob', observe: 'response' })
}
public getDefinition(id: String): Observable<DatasetProfileDefinitionModel> {
return this.http.get<DatasetProfileDefinitionModel>(this.actionUrl + 'get/' + id, { headers: this.headers });

View File

@ -22,8 +22,8 @@ export class DatasetCriteriaComponent extends BaseCriteriaComponent implements O
public criteria: DatasetCriteria= new DatasetCriteria();
statuses = [
{value: '0', viewValue: 'Active'},
{value: '1', viewValue: 'Inactive'}
{value: '0', viewValue: 'Saved'},
{value: '1', viewValue: 'Finalised'}
];
constructor(

View File

@ -10,6 +10,7 @@ import { HttpClient } from '@angular/common/http';
import { AuthService } from '../../services/auth/auth.service';
import { SnackBarNotificationComponent } from '../../shared/components/notificaiton/snack-bar-notification.component';
import { BaseHttpResponseModel } from '../../models/http/BaseHttpResponseModel';
import { ApiResponseCode } from '@app/utilities/types/ApiResponseCode';
@Injectable()
export class BaseHttpService {
@ -22,39 +23,39 @@ export class BaseHttpService {
public route: ActivatedRoute
) {
}
get<T>(url: string, options?: any): Observable<T> {
return this.interceptRepsonse<T>(this.http.get(url, this.buildRequestOptions(options)));
get<T>(url: string, options?: any, appendOptions: boolean = true): Observable<T> {
return this.interceptRepsonse<T>(this.http.get(url, this.buildRequestOptions(appendOptions, options)));
}
post<T>(url: string, body: any, options?: any): Observable<T> {
return this.interceptRepsonse<T>(this.http.post(url, body, this.buildRequestOptions(options)));
post<T>(url: string, body: any, options?: any, appendOptions: boolean = true): Observable<T> {
return this.interceptRepsonse<T>(this.http.post(url, body, this.buildRequestOptions(appendOptions, options)));
}
put<T>(url: string, body: any, options?: any): Observable<T> {
return this.interceptRepsonse<T>(this.http.put(url, body, this.buildRequestOptions(options)));
put<T>(url: string, body: any, options?: any, appendOptions: boolean = true): Observable<T> {
return this.interceptRepsonse<T>(this.http.put(url, body, this.buildRequestOptions(appendOptions, options)));
}
delete<T>(url: string, options?: any): Observable<T> {
return this.interceptRepsonse<T>(this.http.delete(url, this.buildRequestOptions(options)));
delete<T>(url: string, options?: any, appendOptions: boolean = true): Observable<T> {
return this.interceptRepsonse<T>(this.http.delete(url, this.buildRequestOptions(appendOptions, options)));
}
patch<T>(url: string, body: any, options?: any): Observable<T> {
return this.interceptRepsonse(this.http.patch(url, body, this.buildRequestOptions(options)));
patch<T>(url: string, body: any, options?: any, appendOptions: boolean = true): Observable<T> {
return this.interceptRepsonse(this.http.patch(url, body, this.buildRequestOptions(appendOptions, options)));
}
head<T>(url: string, options?: any): Observable<T> {
return this.interceptRepsonse<T>(this.http.head(url, this.buildRequestOptions(options)));
head<T>(url: string, options?: any, appendOptions: boolean = true): Observable<T> {
return this.interceptRepsonse<T>(this.http.head(url, this.buildRequestOptions(appendOptions, options)));
}
options<T>(url: string, options?: any): Observable<T> {
return this.interceptRepsonse<T>(this.http.options(url, this.buildRequestOptions(options)));
options<T>(url: string, options?: any, appendOptions: boolean = true): Observable<T> {
return this.interceptRepsonse<T>(this.http.options(url, this.buildRequestOptions(appendOptions, options)));
}
protected buildRequestOptions(options?: any): Object {
protected buildRequestOptions(appendOptions: boolean, options?: any): Object {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
if (!options.headers.has('Content-Type')) {
if (!options.headers.has('Content-Type') && appendOptions) {
options.headers = options.headers.set('Content-Type', 'application/json');
}
if (!options.headers.has('Content-Type')) {
if (!options.headers.has('Content-Type') && appendOptions) {
options.headers = options.headers.set('Content-Type', 'application/json');
}
if (!options.headers.has('AuthToken')) {
@ -81,26 +82,27 @@ export class BaseHttpService {
//this.notification.httpError(error);
return Observable.of<T>();
} else {
let error:any = errorResponse.error
if(error.statusCode == ApiMessageCode.ERROR_MESSAGE){
let error: any = errorResponse.error
if (error.statusCode == ApiMessageCode.ERROR_MESSAGE) {
this.snackBar.openFromComponent(SnackBarNotificationComponent, {
data: { message: error.message, language: null },
duration: 3000,
extraClasses: ['snackbar-warning']
})
return Observable.throw(errorResponse);
return Observable.throw(errorResponse);
}
else{
else {
this.snackBar.openFromComponent(SnackBarNotificationComponent, {
data: { message: 'GENERAL.ERRORS.HTTP-REQUEST-ERROR', language: this.language },
duration: 3000,
extraClasses: ['snackbar-warning']
})
return Observable.throw(errorResponse);
return Observable.throw(errorResponse);
}
}
})
.map(response => {
if (response instanceof Blob) return response
if (response.statusCode == ApiMessageCode.SUCCESS_MESSAGE) {
//throw new Error('Request failed');
this.snackBar.openFromComponent(SnackBarNotificationComponent, {
@ -109,12 +111,12 @@ export class BaseHttpService {
extraClasses: ['snackbar-success']
})
return response.payload;
}
else if(response.statusCode == ApiMessageCode.NO_MESSAGE){
else if (response.statusCode == ApiMessageCode.NO_MESSAGE) {
return response.payload;
}
else{
else {
return response.payload;
}
});

View File

@ -0,0 +1,4 @@
export enum ApiResponseCode {
JSON_RESPONSE = 0,
FILE_RESPONSE = 1,
}

View File

@ -40,11 +40,11 @@ export class VisibilityRulesService {
private evaluateVisibility(visibilityRule: VisibilityRule) {
for (let i = 0; i < visibilityRule.sourceVisibilityRules.length; i++) {
let pathKey = this.fieldsPathMemory[visibilityRule.sourceVisibilityRules[i].sourceControlId];
if (this.formGroup.get(pathKey + '.value') && this.formGroup.get(pathKey + '.value').value != '' + visibilityRule.sourceVisibilityRules[i].sourceControlValue) {
if (this.formGroup.get(pathKey + '.value') && (!this.formGroup.get(pathKey + '.value').value || ""+this.formGroup.get(pathKey + '.value').value != ""+visibilityRule.sourceVisibilityRules[i].sourceControlValue)) {
this.elementVisibilityMap.set(visibilityRule.targetControlId, false)
} else {
this.elementVisibilityMap.set(visibilityRule.targetControlId, true)
return;
}
this.elementVisibilityMap.set(visibilityRule.targetControlId, true)
}
}

BIN
welcome.docx Normal file

Binary file not shown.