code clean up

This commit is contained in:
Efstratios Giannopoulos 2024-02-08 11:04:38 +02:00
parent f8251aaf43
commit ab653e4f94
272 changed files with 97 additions and 19585 deletions

View File

@ -1,17 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.commons.enums.DmpBlueprintStatus;
import eu.eudat.data.DmpBlueprintEntity;
public class DataManagementPlanBlueprintCriteria extends Criteria<DmpBlueprintEntity> {
private DmpBlueprintStatus status;
public DmpBlueprintStatus getStatus() {
return status;
}
public void setStatus(DmpBlueprintStatus status) {
this.status = status;
}
}

View File

@ -1,126 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.DmpBlueprintEntity;
import eu.eudat.data.DmpEntity;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class DataManagementPlanCriteria extends Criteria<DmpEntity> {
private Date periodStart;
private Date periodEnd;
private DmpBlueprintEntity profile;
private boolean allVersions;
private List<UUID> groupIds;
private Integer status;
private List<String> organisations;
private Integer role;
private List<UUID> collaborators;
private List<UUID> datasetTemplates;
private boolean isPublic;
private boolean onlyPublic;
private Short grantStatus;
private boolean hasDoi;
public Date getPeriodStart() {
return periodStart;
}
public void setPeriodStart(Date periodStart) {
this.periodStart = periodStart;
}
public Date getPeriodEnd() {
return periodEnd;
}
public void setPeriodEnd(Date periodEnd) {
this.periodEnd = periodEnd;
}
public DmpBlueprintEntity getProfile() {
return profile;
}
public void setProfile(DmpBlueprintEntity profile) {
this.profile = profile;
}
public boolean getAllVersions() {
return allVersions;
}
public void setAllVersions(boolean allVersions) {
this.allVersions = allVersions;
}
public List<UUID> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<UUID> groupIds) {
this.groupIds = groupIds;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public List<String> getOrganisations() {
return organisations;
}
public void setOrganisations(List<String> organisations) {
this.organisations = organisations;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public List<UUID> getCollaborators() {
return collaborators;
}
public void setCollaborators(List<UUID> collaborators) {
this.collaborators = collaborators;
}
public List<UUID> getDatasetTemplates() {
return datasetTemplates;
}
public void setDatasetTemplates(List<UUID> datasetTemplates) {
this.datasetTemplates = datasetTemplates;
}
public boolean getIsPublic() {
return isPublic;
}
public void setIsPublic(boolean isPublic) {
this.isPublic = isPublic;
}
public boolean isOnlyPublic() {
return onlyPublic;
}
public void setOnlyPublic(boolean onlyPublic) {
this.onlyPublic = onlyPublic;
}
public Short getGrantStatus() {
return grantStatus;
}
public void setGrantStatus(Short grantStatus) {
this.grantStatus = grantStatus;
}
public boolean hasDoi() {
return hasDoi;
}
public void setHasDoi(boolean hasDoi) {
this.hasDoi = hasDoi;
}
}

View File

@ -1,9 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.DmpBlueprintEntity;
/**
* Created by ikalyvas on 3/21/2018.
*/
public class DataManagementPlanProfileCriteria extends Criteria<DmpBlueprintEntity> {
}

View File

@ -1,66 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.DmpEntity;
import eu.eudat.types.grant.GrantStateType;
import java.util.List;
import java.util.UUID;
public class DataManagementPlanPublicCriteria extends Criteria<DmpEntity> {
private GrantStateType grantStatus;
private List<UUID> grants;
public List<UUID> datasetProfile;
private List<String> dmpOrganisations;
private Integer role;
private boolean allVersions;
private List<UUID> groupIds;
public GrantStateType getGrantStatus() {
return grantStatus;
}
public void setGrantStatus(GrantStateType grantStatus) {
this.grantStatus = grantStatus;
}
public List<UUID> getGrants() {
return grants;
}
public void setGrants(List<UUID> grants) {
this.grants = grants;
}
public List<UUID> getDatasetProfile() {
return datasetProfile;
}
public void setDatasetProfile(List<UUID> datasetProfile) {
this.datasetProfile = datasetProfile;
}
public List<String> getDmpOrganisations() {
return dmpOrganisations;
}
public void setDmpOrganisations(List<String> dmpOrganisations) {
this.dmpOrganisations = dmpOrganisations;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public boolean getAllVersions() {
return allVersions;
}
public void setAllVersions(boolean allVersions) {
this.allVersions = allVersions;
}
public List<UUID> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<UUID> groupIds) {
this.groupIds = groupIds;
}
}

View File

@ -1,142 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.DescriptionEntity;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class DatasetCriteria extends Criteria<DescriptionEntity> {
private Integer status;
private Date periodStart;
private Date periodEnd;
private List<UUID> dmpIds;
// private List<Tag> tags; //TODO
private boolean allVersions;
private UUID profileDatasetId;
private List<String> organisations;
private Integer role;
private List<UUID> grants;
private List<UUID> collaborators;
private List<UUID> datasetTemplates;
private List<UUID> groupIds;
private Boolean isPublic;
private Short grantStatus;
private boolean hasDoi;
public boolean getAllVersions() {
return allVersions;
}
public void setAllVersions(boolean allVersions) {
this.allVersions = allVersions;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getPeriodStart() {
return periodStart;
}
public void setPeriodStart(Date periodStart) {
this.periodStart = periodStart;
}
public Date getPeriodEnd() {
return periodEnd;
}
public void setPeriodEnd(Date periodEnd) {
this.periodEnd = periodEnd;
}
public List<UUID> getDmpIds() {
return dmpIds;
}
public void setDmpIds(List<UUID> dmpIds) {
this.dmpIds = dmpIds;
}
// public List<Tag> getTags() {
// return tags;
// }
// public void setTags(List<Tag> tags) {
// this.tags = tags;
// }
public UUID getProfileDatasetId() {
return profileDatasetId;
}
public void setProfileDatasetId(UUID profileDatasetId) {
this.profileDatasetId = profileDatasetId;
}
public List<String> getOrganisations() {
return organisations;
}
public void setOrganisations(List<String> organisations) {
this.organisations = organisations;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public List<UUID> getGrants() {
return grants;
}
public void setGrants(List<UUID> grants) {
this.grants = grants;
}
public List<UUID> getCollaborators() {
return collaborators;
}
public void setCollaborators(List<UUID> collaborators) {
this.collaborators = collaborators;
}
public List<UUID> getDatasetTemplates() {
return datasetTemplates;
}
public void setDatasetTemplates(List<UUID> datasetTemplates) {
this.datasetTemplates = datasetTemplates;
}
public List<UUID> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<UUID> groupIds) {
this.groupIds = groupIds;
}
public Boolean getIsPublic() {
return isPublic;
}
public void setIsPublic(Boolean isPublic) {
this.isPublic = isPublic;
}
public Short getGrantStatus() {
return grantStatus;
}
public void setGrantStatus(Short grantStatus) {
this.grantStatus = grantStatus;
}
public boolean hasDoi() {
return hasDoi;
}
public void setHasDoi(boolean hasDoi) {
this.hasDoi = hasDoi;
}
}

View File

@ -1,101 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.DescriptionTemplateEntity;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class DatasetProfileCriteria extends Criteria<DescriptionTemplateEntity> {
public enum DatasetProfileFilter {
DMPs((short) 0), Datasets((short) 1);
private short value;
private DatasetProfileFilter(short value) {
this.value = value;
}
public short getValue() { return value; }
public static DatasetProfileFilter fromInteger(short value) {
switch (value) {
case 0:
return DMPs;
case 1:
return Datasets;
default:
throw new RuntimeException("Unsupported DescriptionTemplate filter");
}
}
}
private boolean allVersions;
private List<UUID> groupIds;
private Short filter;
private UUID userId;
private boolean finalized;
private Integer status;
private Integer role;
private List<UUID> ids;
private Date periodStart;
public boolean getAllVersions() { return allVersions; }
public void setAllVersions(boolean allVersions) { this.allVersions = allVersions; }
public List<UUID> getGroupIds() { return groupIds; }
public void setGroupIds(List<UUID> groupIds) { this.groupIds = groupIds; }
public Short getFilter() {
return filter;
}
public void setFilter(Short filter) {
this.filter = filter;
}
public UUID getUserId() {
return userId;
}
public void setUserId(UUID userId) {
this.userId = userId;
}
public boolean getFinalized() {
return finalized;
}
public void setFinalized(boolean finalized) {
this.finalized = finalized;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public List<UUID> getIds() {
return ids;
}
public void setIds(List<UUID> ids) {
this.ids = ids;
}
public Date getPeriodStart() {
return periodStart;
}
public void setPeriodStart(Date periodStart) {
this.periodStart = periodStart;
}
}

View File

@ -1,18 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.DescriptionTemplateEntity;
import java.util.UUID;
public class DatasetProfileWizardCriteria extends Criteria<DescriptionTemplateEntity> {
private UUID id;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
}

View File

@ -1,17 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.DmpEntity;
import eu.eudat.data.UserEntity;
public class DatasetWizardUserDmpCriteria extends Criteria<DmpEntity> {
private UserEntity userInfo;
public UserEntity getUserInfo() {
return userInfo;
}
public void setUserInfo(UserEntity userInfo) {
this.userInfo = userInfo;
}
}

View File

@ -1,51 +0,0 @@
package eu.eudat.data.dao.criteria;
import java.util.List;
/**
* Created by ikalyvas on 3/26/2018.
*/
public class DynamicFieldsCriteria extends Criteria {
public static class DynamicFieldDependencyCriteria {
private String property;
private String value;
public DynamicFieldDependencyCriteria() {
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
private String id;
private List<DynamicFieldDependencyCriteria> dynamicFields;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<DynamicFieldDependencyCriteria> getDynamicFields() {
return dynamicFields;
}
public void setDynamicFields(List<DynamicFieldDependencyCriteria> dynamicFields) {
this.dynamicFields = dynamicFields;
}
}

View File

@ -1,17 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.ReferenceEntity;
import java.util.UUID;
public class ReferenceCriteria extends Criteria<ReferenceEntity>{
private UUID creationUserId;
public UUID getCreationUserId() {
return creationUserId;
}
public void setCreationUserId(UUID creationUserId) {
this.creationUserId = creationUserId;
}
}

View File

@ -1,16 +0,0 @@
package eu.eudat.data.dao.criteria;
/**
* Created by ikalyvas on 3/26/2018.
*/
public class RequestItem<T> {
T criteria;
public T getCriteria() {
return criteria;
}
public void setCriteria(T criteria) {
this.criteria = criteria;
}
}

View File

@ -1,33 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.UserEntity;
import java.util.List;
public class UserInfoCriteria extends Criteria<UserEntity> {
private String email;
private List<Integer> appRoles;
private String collaboratorLike;
public List<Integer> getAppRoles() {
return appRoles;
}
public void setAppRoles(List<Integer> appRoles) {
this.appRoles = appRoles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCollaboratorLike() {
return collaboratorLike;
}
public void setCollaboratorLike(String collaboratorLike) {
this.collaboratorLike = collaboratorLike;
}
}

View File

@ -1,20 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.UserRoleEntity;
import java.util.List;
/**
* Created by ikalyvas on 2/1/2018.
*/
public class UserRoleCriteria extends Criteria<UserRoleEntity> {
private List<Integer> appRoles;
public List<Integer> getAppRoles() {
return appRoles;
}
public void setAppRoles(List<Integer> appRoles) {
this.appRoles = appRoles;
}
}

View File

@ -1,49 +0,0 @@
package eu.eudat.data.dao.databaselayer.context;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.jpa.hibernatequeryablelist.QueryableHibernateList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContext;
@Repository("databaseCtx")
public class DatabaseContext<T> {
@PersistenceContext
private EntityManager entityManager;
@Autowired
public DatabaseContext(EntityManagerFactory entityManagerFactory) {
this.entityManager = entityManagerFactory.createEntityManager();
}
public QueryableList<T> getQueryable(Class<T> type) {
return new QueryableHibernateList<>(this.entityManager, type).setEntity(type);
}
@Transactional
public T createOrUpdate(T item, Class<T> type) {
EntityManager entityManager = this.entityManager;
// if (item.getKeys() != null) {
// T oldItem = entityManager.find(type, item.getKeys());
// if (oldItem != null) {
// oldItem.update(item);
// entityManager.merge(oldItem);
// return oldItem;
// } else {
// entityManager.persist(item);
// }
// } else
entityManager.persist(item);
return item;
}
public void delete(T item) {
this.entityManager.remove(item);
}
}

View File

@ -1,40 +0,0 @@
package eu.eudat.data.dao.databaselayer.service;
import eu.eudat.data.dao.databaselayer.context.DatabaseContext;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Set;
@Service("databaseService")
public class DatabaseService<T> {
private DatabaseContext<T> databaseCtx;
@Autowired
public DatabaseService(DatabaseContext<T> databaseCtx) {
this.databaseCtx = databaseCtx;
}
public QueryableList<T> getQueryable(Class<T> tClass) {
return this.databaseCtx.getQueryable(tClass);
}
public QueryableList<T> getQueryable(Set<String> hints, Class<T> tClass) {
return this.databaseCtx.getQueryable(tClass);
}
@Transactional
public T createOrUpdate(T item, Class<T> tClass) {
return this.databaseCtx.createOrUpdate(item, tClass);
}
public void delete(T item) {
this.databaseCtx.delete(item);
}
}

View File

@ -1,6 +1,5 @@
package eu.eudat.data.query.definition; package eu.eudat.data.query.definition;
import eu.eudat.data.dao.criteria.Criteria; import eu.eudat.data.dao.criteria.Criteria;
import eu.eudat.data.query.definition.helpers.ColumnOrderings; import eu.eudat.data.query.definition.helpers.ColumnOrderings;
import eu.eudat.data.query.definition.helpers.SelectionFields; import eu.eudat.data.query.definition.helpers.SelectionFields;

View File

@ -1,40 +0,0 @@
package eu.eudat.data.query.items.table.dataset;
import eu.eudat.commons.enums.DescriptionStatus;
import eu.eudat.data.dao.criteria.DatasetCriteria;
import eu.eudat.data.DescriptionEntity;
import eu.eudat.data.query.definition.TableQuery;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;
import java.util.Arrays;
import java.util.UUID;
public class DatasetTableRequest extends TableQuery<DatasetCriteria, DescriptionEntity, UUID> {
@Override
public QueryableList<DescriptionEntity> applyCriteria() {
QueryableList<DescriptionEntity> query = this.getQuery();
if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty())
query.where((builder, root) -> builder.or(
builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"),
builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%")));
if (this.getCriteria().getStatus() != null)
query.where((builder, root) -> builder.equal(root.get("status"), this.getCriteria().getStatus()));
if (this.getCriteria().getPeriodEnd() != null)
query.where((builder, root) -> builder.lessThan(root.get("created"), this.getCriteria().getPeriodEnd()));
if (this.getCriteria().getPeriodStart() != null)
query.where((builder, root) -> builder.greaterThan(root.get("created"), this.getCriteria().getPeriodStart()));
if (!this.getCriteria().getAllVersions())
query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), query.<String>subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class)));
if (this.getCriteria().getDmpIds() != null && !this.getCriteria().getDmpIds().isEmpty())
query.where((builder, root) -> root.get("dmp").get("id").in(this.getCriteria().getDmpIds()));
query.where((builder, root) -> builder.equal(root.get("status"), DescriptionStatus.Finalized));
return query;
}
@Override
public QueryableList<DescriptionEntity> applyPaging(QueryableList<DescriptionEntity> items) {
return null;
}
}

View File

@ -1,18 +0,0 @@
package eu.eudat.controllers;
import eu.eudat.logic.services.ApiContext;
public abstract class BaseController {
private ApiContext apiContext;
public ApiContext getApiContext() {
return apiContext;
}
public BaseController(ApiContext apiContext) {
this.apiContext = apiContext;
}
}

View File

@ -1,8 +1,8 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.logic.managers.LocalFetchManager; import eu.eudat.logic.managers.LocalFetchManager;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.old.helpers.responses.ResponseItem;
import eu.eudat.models.data.local.LocalFetchModel; import eu.eudat.models.old.local.LocalFetchModel;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;

View File

@ -2,28 +2,28 @@ package eu.eudat.controllers;
import eu.eudat.authorization.Permission; import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DatasetProfileManager; import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.services.ApiContext; import eu.eudat.models.old.helpers.responses.ResponseItem;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.transaction.Transactional; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping(value = {"/api/management/"}) @RequestMapping(value = {"/api/management/"})
public class ManagementController extends BaseController { public class ManagementController{
private final DatasetProfileManager datasetProfileManager; private final DatasetProfileManager datasetProfileManager;
private final AuthorizationService authorizationService; private final AuthorizationService authorizationService;
@Autowired @Autowired
public ManagementController(ApiContext apiContext, DatasetProfileManager datasetProfileManager, AuthorizationService authorizationService){ public ManagementController(DatasetProfileManager datasetProfileManager, AuthorizationService authorizationService){
super(apiContext);
this.datasetProfileManager = datasetProfileManager; this.datasetProfileManager = datasetProfileManager;
this.authorizationService = authorizationService; this.authorizationService = authorizationService;
} }

View File

@ -3,8 +3,7 @@ package eu.eudat.controllers;
import eu.eudat.authorization.Permission; import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.ValidationManager; import eu.eudat.logic.managers.ValidationManager;
import eu.eudat.commons.exceptions.HugeResultSetException; import eu.eudat.commons.exceptions.HugeResultSetException;
import eu.eudat.logic.services.ApiContext; import eu.eudat.models.old.helpers.responses.ResponseItem;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.exception.MyNotFoundException; import gr.cite.tools.exception.MyNotFoundException;
@ -16,14 +15,13 @@ import org.springframework.web.bind.annotation.*;
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping(value = {"/api"}) @RequestMapping(value = {"/api"})
public class Validation extends BaseController { public class Validation {
private ValidationManager validationManager; private ValidationManager validationManager;
private final AuthorizationService authorizationService; private final AuthorizationService authorizationService;
@Autowired @Autowired
public Validation(ApiContext apiContext, ValidationManager validationManager, AuthorizationService authorizationService) { public Validation(ValidationManager validationManager, AuthorizationService authorizationService) {
super(apiContext);
this.validationManager = validationManager; this.validationManager = validationManager;
this.authorizationService = authorizationService; this.authorizationService = authorizationService;
} }

View File

@ -2,11 +2,9 @@ package eu.eudat.controllers.publicapi;
import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.IsActive;
import eu.eudat.controllers.BaseController;
import eu.eudat.controllers.publicapi.request.dataset.DatasetPublicTableRequest; import eu.eudat.controllers.publicapi.request.dataset.DatasetPublicTableRequest;
import eu.eudat.controllers.publicapi.response.DataTableData; import eu.eudat.controllers.publicapi.response.DataTableData;
import eu.eudat.data.DescriptionEntity; import eu.eudat.data.DescriptionEntity;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.model.*; import eu.eudat.model.*;
import eu.eudat.model.builder.DescriptionBuilder; import eu.eudat.model.builder.DescriptionBuilder;
import eu.eudat.model.builder.DmpBuilder; import eu.eudat.model.builder.DmpBuilder;
@ -17,7 +15,7 @@ import eu.eudat.model.mapper.publicapi.DescriptionToPublicApiDatasetMapper;
import eu.eudat.model.mapper.publicapi.DmpToPublicApiDmpListingMapper; import eu.eudat.model.mapper.publicapi.DmpToPublicApiDmpListingMapper;
import eu.eudat.model.publicapi.listingmodels.DatasetPublicListingModel; import eu.eudat.model.publicapi.listingmodels.DatasetPublicListingModel;
import eu.eudat.model.publicapi.overviewmodels.DatasetPublicModel; import eu.eudat.model.publicapi.overviewmodels.DatasetPublicModel;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.old.helpers.responses.ResponseItem;
import eu.eudat.query.DescriptionQuery; import eu.eudat.query.DescriptionQuery;
import eu.eudat.query.DmpQuery; import eu.eudat.query.DmpQuery;
import eu.eudat.query.lookup.DescriptionLookup; import eu.eudat.query.lookup.DescriptionLookup;
@ -55,7 +53,7 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping(value = {"/api/public/datasets/"}) @RequestMapping(value = {"/api/public/datasets/"})
public class PublicDatasetsDescriptionDocumentation extends BaseController { public class PublicDatasetsDescriptionDocumentation {
private static final Logger logger = LoggerFactory.getLogger(PublicDatasetsDescriptionDocumentation.class); private static final Logger logger = LoggerFactory.getLogger(PublicDatasetsDescriptionDocumentation.class);
@ -73,13 +71,11 @@ public class PublicDatasetsDescriptionDocumentation extends BaseController {
@Autowired @Autowired
public PublicDatasetsDescriptionDocumentation( public PublicDatasetsDescriptionDocumentation(
ApiContext apiContext,
QueryFactory queryFactory, QueryFactory queryFactory,
BuilderFactory builderFactory, BuilderFactory builderFactory,
MessageSource messageSource, MessageSource messageSource,
DescriptionToPublicApiDatasetMapper descriptionToPublicApiDatasetMapper, DescriptionToPublicApiDatasetMapper descriptionToPublicApiDatasetMapper,
DescriptionToPublicApiDatasetListingMapper descriptionToPublicApiDatasetListingMapper, DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper) { DescriptionToPublicApiDatasetListingMapper descriptionToPublicApiDatasetListingMapper, DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper) {
super(apiContext);
this.queryFactory = queryFactory; this.queryFactory = queryFactory;
this.builderFactory = builderFactory; this.builderFactory = builderFactory;
this.messageSource = messageSource; this.messageSource = messageSource;

View File

@ -2,11 +2,9 @@ package eu.eudat.controllers.publicapi;
import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.IsActive;
import eu.eudat.controllers.BaseController;
import eu.eudat.controllers.publicapi.request.dmp.DataManagmentPlanPublicTableRequest; import eu.eudat.controllers.publicapi.request.dmp.DataManagmentPlanPublicTableRequest;
import eu.eudat.controllers.publicapi.response.DataTableData; import eu.eudat.controllers.publicapi.response.DataTableData;
import eu.eudat.data.DmpEntity; import eu.eudat.data.DmpEntity;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.model.*; import eu.eudat.model.*;
import eu.eudat.model.builder.DmpBuilder; import eu.eudat.model.builder.DmpBuilder;
import eu.eudat.model.builder.DmpDescriptionTemplateBuilder; import eu.eudat.model.builder.DmpDescriptionTemplateBuilder;
@ -17,7 +15,7 @@ import eu.eudat.model.publicapi.listingmodels.DataManagementPlanPublicListingMod
import eu.eudat.model.publicapi.overviewmodels.DataManagementPlanPublicModel; import eu.eudat.model.publicapi.overviewmodels.DataManagementPlanPublicModel;
import eu.eudat.model.referencedefinition.Definition; import eu.eudat.model.referencedefinition.Definition;
import eu.eudat.model.referencedefinition.Field; import eu.eudat.model.referencedefinition.Field;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.old.helpers.responses.ResponseItem;
import eu.eudat.query.DmpDescriptionTemplateQuery; import eu.eudat.query.DmpDescriptionTemplateQuery;
import eu.eudat.query.DmpQuery; import eu.eudat.query.DmpQuery;
import eu.eudat.query.EntityDoiQuery; import eu.eudat.query.EntityDoiQuery;
@ -55,7 +53,7 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping(value = {"/api/public/dmps"}) @RequestMapping(value = {"/api/public/dmps"})
public class PublicDmpsDocumentation extends BaseController { public class PublicDmpsDocumentation {
private static final Logger logger = LoggerFactory.getLogger(PublicDmpsDocumentation.class); private static final Logger logger = LoggerFactory.getLogger(PublicDmpsDocumentation.class);
@ -71,13 +69,11 @@ public class PublicDmpsDocumentation extends BaseController {
@Autowired @Autowired
public PublicDmpsDocumentation( public PublicDmpsDocumentation(
ApiContext apiContext,
QueryFactory queryFactory, QueryFactory queryFactory,
BuilderFactory builderFactory, BuilderFactory builderFactory,
MessageSource messageSource, MessageSource messageSource,
DmpToPublicApiDmpMapper dmpToPublicApiDmpMapper, DmpToPublicApiDmpMapper dmpToPublicApiDmpMapper,
DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper) { DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper) {
super(apiContext);
this.queryFactory = queryFactory; this.queryFactory = queryFactory;
this.builderFactory = builderFactory; this.builderFactory = builderFactory;
this.messageSource = messageSource; this.messageSource = messageSource;

View File

@ -2,8 +2,6 @@ package eu.eudat.controllers.v2;
import eu.eudat.audit.AuditableAction; import eu.eudat.audit.AuditableAction;
import gr.cite.tools.validation.ValidationFilterAnnotation; import gr.cite.tools.validation.ValidationFilterAnnotation;
import eu.eudat.controllers.BaseController;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.model.EntityDoi; import eu.eudat.model.EntityDoi;
import eu.eudat.model.censorship.EntityDoiCensor; import eu.eudat.model.censorship.EntityDoiCensor;
import eu.eudat.model.censorship.deposit.DepositConfigurationCensor; import eu.eudat.model.censorship.deposit.DepositConfigurationCensor;
@ -11,7 +9,6 @@ import eu.eudat.model.deposit.DepositConfiguration;
import eu.eudat.model.persist.deposit.DepositAuthenticateRequest; import eu.eudat.model.persist.deposit.DepositAuthenticateRequest;
import eu.eudat.model.persist.deposit.DepositRequest; import eu.eudat.model.persist.deposit.DepositRequest;
import eu.eudat.service.deposit.DepositService; import eu.eudat.service.deposit.DepositService;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.auditing.AuditService; import gr.cite.tools.auditing.AuditService;
import gr.cite.tools.data.censor.CensorFactory; import gr.cite.tools.data.censor.CensorFactory;
import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.fieldset.FieldSet;
@ -29,7 +26,7 @@ import java.util.Map;
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping(value = {"/api/deposit/"}) @RequestMapping(value = {"/api/deposit/"})
public class DepositController extends BaseController { public class DepositController {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DepositController.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DepositController.class));
@ -41,8 +38,7 @@ public class DepositController extends BaseController {
private final AuditService auditService; private final AuditService auditService;
@Autowired @Autowired
public DepositController(ApiContext apiContext, AuthorizationService authorizationService, DepositService depositService, CensorFactory censorFactory, AuditService auditService) { public DepositController(DepositService depositService, CensorFactory censorFactory, AuditService auditService) {
super(apiContext);
this.depositService = depositService; this.depositService = depositService;
this.censorFactory = censorFactory; this.censorFactory = censorFactory;
this.auditService = auditService; this.auditService = auditService;

View File

@ -3,7 +3,6 @@ package eu.eudat.controllers.v2;
import eu.eudat.audit.AuditableAction; import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.data.DescriptionTemplateTypeEntity; import eu.eudat.data.DescriptionTemplateTypeEntity;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.model.DescriptionTemplateType; import eu.eudat.model.DescriptionTemplateType;
import eu.eudat.model.builder.DescriptionTemplateTypeBuilder; import eu.eudat.model.builder.DescriptionTemplateTypeBuilder;
import eu.eudat.model.censorship.DescriptionTemplateTypeCensor; import eu.eudat.model.censorship.DescriptionTemplateTypeCensor;
@ -38,9 +37,6 @@ import java.util.*;
public class DescriptionTemplateTypeController { public class DescriptionTemplateTypeController {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeController.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeController.class));
@Autowired
private ApiContext apiContext;
private final BuilderFactory builderFactory; private final BuilderFactory builderFactory;
private final AuditService auditService; private final AuditService auditService;

View File

@ -1,24 +1,19 @@
package eu.eudat.controllers.v2; package eu.eudat.controllers.v2;
import com.fasterxml.jackson.core.JsonProcessingException;
import eu.eudat.audit.AuditableAction; import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.authorization.AuthorizationFlags;
import gr.cite.tools.validation.ValidationFilterAnnotation; import gr.cite.tools.validation.ValidationFilterAnnotation;
import eu.eudat.data.DmpEntity;
import eu.eudat.model.*; import eu.eudat.model.*;
import eu.eudat.model.builder.DmpBuilder; import eu.eudat.model.builder.DmpBuilder;
import eu.eudat.model.censorship.DmpCensor; import eu.eudat.model.censorship.DmpCensor;
import eu.eudat.model.censorship.PublicDescriptionCensor;
import eu.eudat.model.censorship.PublicDmpCensor; import eu.eudat.model.censorship.PublicDmpCensor;
import eu.eudat.model.persist.*; import eu.eudat.model.persist.*;
import eu.eudat.model.result.QueryResult; import eu.eudat.model.result.QueryResult;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.old.helpers.responses.ResponseItem;
import eu.eudat.query.DmpQuery; import eu.eudat.query.DmpQuery;
import eu.eudat.query.lookup.DescriptionLookup;
import eu.eudat.query.lookup.DmpLookup; import eu.eudat.query.lookup.DmpLookup;
import eu.eudat.service.dmp.DmpService; import eu.eudat.service.dmp.DmpService;
import eu.eudat.service.elastic.ElasticQueryHelperService; import eu.eudat.service.elastic.ElasticQueryHelperService;
import eu.eudat.service.transformer.FileTransformerService;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.tools.auditing.AuditService; import gr.cite.tools.auditing.AuditService;
import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.builder.BuilderFactory;

View File

@ -1,11 +1,9 @@
package eu.eudat.controllers.v2; package eu.eudat.controllers.v2;
import eu.eudat.authorization.Permission; import eu.eudat.authorization.Permission;
import eu.eudat.controllers.BaseController;
import eu.eudat.commons.exceptions.HugeResultSetException; import eu.eudat.commons.exceptions.HugeResultSetException;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.ExternalValidationService; import eu.eudat.logic.services.ExternalValidationService;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.old.helpers.responses.ResponseItem;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.exception.MyNotFoundException; import gr.cite.tools.exception.MyNotFoundException;
@ -16,14 +14,13 @@ import org.springframework.web.bind.annotation.*;
@RestController @RestController
@RequestMapping(path = {"api/validation"}) @RequestMapping(path = {"api/validation"})
public class ExternalValidationController extends BaseController { public class ExternalValidationController {
private ExternalValidationService externalValidationService; private ExternalValidationService externalValidationService;
private final AuthorizationService authorizationService; private final AuthorizationService authorizationService;
@Autowired @Autowired
public ExternalValidationController(ApiContext apiContext, ExternalValidationService externalValidationService, AuthorizationService authorizationService) { public ExternalValidationController(ExternalValidationService externalValidationService, AuthorizationService authorizationService) {
super(apiContext);
this.externalValidationService = externalValidationService; this.externalValidationService = externalValidationService;
this.authorizationService = authorizationService; this.authorizationService = authorizationService;
} }

View File

@ -1,9 +1,7 @@
package eu.eudat.controllers.v2; package eu.eudat.controllers.v2;
import eu.eudat.audit.AuditableAction; import eu.eudat.audit.AuditableAction;
import eu.eudat.controllers.BaseController;
import eu.eudat.file.transformer.models.misc.FileFormat; import eu.eudat.file.transformer.models.misc.FileFormat;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.model.file.ExportRequestModel; import eu.eudat.model.file.ExportRequestModel;
import eu.eudat.model.file.FileEnvelope; import eu.eudat.model.file.FileEnvelope;
import eu.eudat.service.transformer.FileTransformerService; import eu.eudat.service.transformer.FileTransformerService;
@ -24,26 +22,20 @@ import javax.management.InvalidApplicationException;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.List; import java.util.List;
import java.util.UUID;
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping(value = {"/api/file-transformer/"}) @RequestMapping(value = {"/api/file-transformer/"})
public class FileTransformerController extends BaseController { public class FileTransformerController {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FileTransformerController.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FileTransformerController.class));
private final AuthorizationService authorizationService;
private final FileTransformerService fileTransformerService; private final FileTransformerService fileTransformerService;
private final CensorFactory censorFactory;
private final AuditService auditService; private final AuditService auditService;
@Autowired @Autowired
public FileTransformerController(ApiContext apiContext, AuthorizationService authorizationService, FileTransformerService fileTransformerService, CensorFactory censorFactory, AuditService auditService){ public FileTransformerController(FileTransformerService fileTransformerService, AuditService auditService){
super(apiContext);
this.authorizationService = authorizationService;
this.fileTransformerService = fileTransformerService; this.fileTransformerService = fileTransformerService;
this.censorFactory = censorFactory;
this.auditService = auditService; this.auditService = auditService;
} }

View File

@ -2,21 +2,14 @@ package eu.eudat.controllers.v2;
import eu.eudat.audit.AuditableAction; import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.Permission; import eu.eudat.authorization.Permission;
import eu.eudat.data.DescriptionEntity;
import eu.eudat.model.Lock;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.service.elastic.ElasticService; import eu.eudat.service.elastic.ElasticService;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.auditing.AuditService; import gr.cite.tools.auditing.AuditService;
import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.LoggerService;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@RestController @RestController

View File

@ -1,8 +1,8 @@
package eu.eudat.controllers.v2; package eu.eudat.controllers.v2;
import eu.eudat.audit.AuditableAction; import eu.eudat.audit.AuditableAction;
import eu.eudat.models.v2.Account; import eu.eudat.models.Account;
import eu.eudat.models.v2.AccountBuilder; import eu.eudat.models.AccountBuilder;
import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver;
import gr.cite.commons.web.oidc.principal.MyPrincipal; import gr.cite.commons.web.oidc.principal.MyPrincipal;
import gr.cite.tools.auditing.AuditService; import gr.cite.tools.auditing.AuditService;

View File

@ -3,25 +3,18 @@ package eu.eudat.controllers.v2;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import eu.eudat.audit.AuditableAction; import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.authorization.Permission;
import gr.cite.tools.validation.ValidationFilterAnnotation;
import eu.eudat.controllers.BaseController;
import eu.eudat.data.ReferenceEntity;
import eu.eudat.commons.exceptions.HugeResultSetException; import eu.eudat.commons.exceptions.HugeResultSetException;
import eu.eudat.logic.services.ApiContext; import eu.eudat.data.ReferenceEntity;
import eu.eudat.service.reference.ReferenceService;
import eu.eudat.model.Reference; import eu.eudat.model.Reference;
import eu.eudat.model.builder.ReferenceBuilder; import eu.eudat.model.builder.ReferenceBuilder;
import eu.eudat.model.censorship.ReferenceCensor; import eu.eudat.model.censorship.ReferenceCensor;
import eu.eudat.model.persist.ReferencePersist; import eu.eudat.model.persist.ReferencePersist;
import eu.eudat.model.result.QueryResult; import eu.eudat.model.result.QueryResult;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.query.ReferenceQuery; import eu.eudat.query.ReferenceQuery;
import eu.eudat.query.lookup.ReferenceDefinitionSearchLookup; import eu.eudat.query.lookup.ReferenceDefinitionSearchLookup;
import eu.eudat.query.lookup.ReferenceLookup; import eu.eudat.query.lookup.ReferenceLookup;
import eu.eudat.query.lookup.ReferenceSearchLookup; import eu.eudat.query.lookup.ReferenceSearchLookup;
import eu.eudat.types.ApiMessageCode; import eu.eudat.service.reference.ReferenceService;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.auditing.AuditService; import gr.cite.tools.auditing.AuditService;
import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.censor.CensorFactory; import gr.cite.tools.data.censor.CensorFactory;
@ -32,14 +25,13 @@ import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.logging.MapLogEntry;
import gr.cite.tools.validation.ValidationFilterAnnotation;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.JAXBException;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException; import javax.management.InvalidApplicationException;
@ -52,7 +44,7 @@ import java.util.UUID;
@RestController @RestController
@RequestMapping(path = {"api/reference"}) @RequestMapping(path = {"api/reference"})
public class ReferenceController extends BaseController { public class ReferenceController {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceController.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceController.class));
@ -71,14 +63,12 @@ public class ReferenceController extends BaseController {
@Autowired @Autowired
public ReferenceController( public ReferenceController(
ApiContext apiContext,
BuilderFactory builderFactory, BuilderFactory builderFactory,
ReferenceService referenceService, ReferenceService referenceService,
AuditService auditService, AuditService auditService,
CensorFactory censorFactory, CensorFactory censorFactory,
QueryFactory queryFactory, QueryFactory queryFactory,
MessageSource messageSource) { MessageSource messageSource) {
super(apiContext);
this.builderFactory = builderFactory; this.builderFactory = builderFactory;
this.referenceService = referenceService; this.referenceService = referenceService;
this.auditService = auditService; this.auditService = auditService;

View File

@ -4,9 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import eu.eudat.audit.AuditableAction; import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.authorization.AuthorizationFlags;
import gr.cite.tools.validation.ValidationFilterAnnotation; import gr.cite.tools.validation.ValidationFilterAnnotation;
import eu.eudat.controllers.BaseController;
import eu.eudat.data.ReferenceTypeEntity; import eu.eudat.data.ReferenceTypeEntity;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.model.Reference; import eu.eudat.model.Reference;
import eu.eudat.model.ReferenceType; import eu.eudat.model.ReferenceType;
import eu.eudat.model.builder.ReferenceTypeBuilder; import eu.eudat.model.builder.ReferenceTypeBuilder;
@ -43,7 +41,7 @@ import java.util.UUID;
@RestController @RestController
@RequestMapping(path = {"api/reference-type"}) @RequestMapping(path = {"api/reference-type"})
public class ReferenceTypeController extends BaseController { public class ReferenceTypeController{
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceTypeController.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceTypeController.class));
@ -63,13 +61,11 @@ public class ReferenceTypeController extends BaseController {
@Autowired @Autowired
public ReferenceTypeController( public ReferenceTypeController(
ApiContext apiContext,
BuilderFactory builderFactory, BuilderFactory builderFactory,
AuditService auditService, AuditService auditService,
CensorFactory censorFactory, CensorFactory censorFactory,
QueryFactory queryFactory, QueryFactory queryFactory,
MessageSource messageSource, AuthorizationService authorizationService, ReferenceTypeService referenceTypeService) { MessageSource messageSource, AuthorizationService authorizationService, ReferenceTypeService referenceTypeService) {
super(apiContext);
this.builderFactory = builderFactory; this.builderFactory = builderFactory;
this.auditService = auditService; this.auditService = auditService;
this.censorFactory = censorFactory; this.censorFactory = censorFactory;

View File

@ -4,7 +4,6 @@ import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.authorization.AuthorizationFlags;
import gr.cite.tools.validation.ValidationFilterAnnotation; import gr.cite.tools.validation.ValidationFilterAnnotation;
import eu.eudat.data.TagEntity; import eu.eudat.data.TagEntity;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.model.Tag; import eu.eudat.model.Tag;
import eu.eudat.model.builder.TagBuilder; import eu.eudat.model.builder.TagBuilder;
import eu.eudat.model.censorship.TagCensor; import eu.eudat.model.censorship.TagCensor;
@ -39,9 +38,6 @@ public class TagController {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TagController.class)); private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TagController.class));
@Autowired
private ApiContext apiContext;
private final BuilderFactory builderFactory; private final BuilderFactory builderFactory;
private final AuditService auditService; private final AuditService auditService;

View File

@ -1,59 +0,0 @@
package eu.eudat.criteria;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import eu.eudat.criteria.entities.Criteria;
import java.io.IOException;
import java.util.*;
public class DatasetCriteria {
private Criteria<UUID> id;
private Criteria<String> label;
public Criteria<UUID> getId() {
return id;
}
public void setId(JsonNode jsonNode) throws IOException {
if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) {
Criteria<UUID> criteria = new Criteria<>();
criteria.setAs(jsonNode.asText());
this.id = criteria;
} else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) {
ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Criteria<UUID>>() {
});
this.id = reader.readValue(jsonNode);
}
}
public Criteria<String> getLabel() {
return label;
}
public void setLabel(JsonNode jsonNode) throws IOException {
if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) {
Criteria<String> criteria = new Criteria<>();
criteria.setAs(jsonNode.asText());
this.label = criteria;
} else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) {
ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Criteria<String>>() {
});
this.label = reader.readValue(jsonNode);
}
}
protected List<String> buildFields(String path) {
Set<String> fields = new HashSet<>();
path = path != null && !path.isEmpty() ? path + "." : "";
if (this.id != null) fields.add(path + this.id.getAs());
if (this.label != null) fields.add(path + this.label.getAs());
if (!fields.contains(path + "id")) fields.add(path + "id");
return new LinkedList<>(fields);
}
}

View File

@ -1,31 +0,0 @@
package eu.eudat.criteria;
public class RecentActivityCriteria {
private String like;
private String order;
private Integer status;
public String getLike() {
return like;
}
public void setLike(String like) {
this.like = like;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}

View File

@ -1,36 +0,0 @@
package eu.eudat.criteria.entities;
enum BaseCriteriaType implements CriteriaType {
EQUALS,
NOT_EQUALS
}
public class Criteria<T> {
private String as;
private BaseCriteriaType type;
private T value;
public String getAs() {
return as;
}
public void setAs(String as) {
this.as = as;
}
public CriteriaType getType() {
return type;
}
public void setType(BaseCriteriaType type) {
this.type = type;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}

View File

@ -1,4 +0,0 @@
package eu.eudat.criteria.entities;
public interface CriteriaType {
}

View File

@ -1,32 +0,0 @@
package eu.eudat.criteria.entities;
import java.util.Date;
enum DateCriteriaType implements CriteriaType {
EQUALS,
NOT_EQUALS,
BEFORE,
BETWEEN,
AFTER
}
public class DateCriteria extends Criteria<Date> {
private Date values;
private CriteriaType type;
public Date getValues() {
return values;
}
public void setValues(Date values) {
this.values = values;
}
public CriteriaType getType() {
return type;
}
public void setType(DateCriteriaType type) {
this.type = type;
}
}

View File

@ -1,41 +0,0 @@
package eu.eudat.criteria.serialzier;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import eu.eudat.criteria.entities.Criteria;
import java.io.IOException;
public class CriteriaSerializer extends JsonDeserializer<Criteria<?>> implements ContextualDeserializer {
private JavaType valueType;
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
JavaType wrapperType = property.getType();
JavaType valueType = wrapperType.containedType(0);
CriteriaSerializer deserializer = new CriteriaSerializer();
deserializer.valueType = valueType;
return deserializer;
}
@Override
public Criteria<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode jsonNode = oc.readTree(jp);
if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) {
Criteria<?> criteria = new Criteria<>();
criteria.setAs(jsonNode.asText());
return criteria;
} else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) {
ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Criteria<?>>() {
});
return reader.readValue(jsonNode);
}
return null;
}
}

View File

@ -1,8 +0,0 @@
package eu.eudat.exceptions.datamanagementplan;
public class DMPNewVersionException extends RuntimeException {
public DMPNewVersionException(String message) {
super(message);
}
}

View File

@ -1,22 +0,0 @@
package eu.eudat.exceptions.datamanagementplan;
/**
* Created by ikalyvas on 2/5/2018.
*/
public class DMPWithDatasetsDeleteException extends RuntimeException {
public DMPWithDatasetsDeleteException() {
super();
}
public DMPWithDatasetsDeleteException(String message, Throwable cause) {
super(message, cause);
}
public DMPWithDatasetsDeleteException(String message) {
super(message);
}
public DMPWithDatasetsDeleteException(Throwable cause) {
super(cause);
}
}

View File

@ -1,22 +0,0 @@
package eu.eudat.exceptions.datasetwizard;
/**
* Created by ikalyvas on 10/12/2018.
*/
public class DatasetWizardCannotUnlockException extends RuntimeException {
public DatasetWizardCannotUnlockException() {
super();
}
public DatasetWizardCannotUnlockException(String message, Throwable cause) {
super(message, cause);
}
public DatasetWizardCannotUnlockException(String message) {
super(message);
}
public DatasetWizardCannotUnlockException(Throwable cause) {
super(cause);
}
}

View File

@ -1,8 +0,0 @@
package eu.eudat.exceptions.emailconfirmation;
public class HasConfirmedEmailException extends Exception {
public HasConfirmedEmailException(String msg) {
super(msg);
}
}

View File

@ -1,8 +0,0 @@
package eu.eudat.exceptions.emailconfirmation;
public class TokenExpiredException extends Exception {
public TokenExpiredException(String msg) {
super(msg);
}
}

View File

@ -1,19 +0,0 @@
package eu.eudat.exceptions.security;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.FORBIDDEN)
public class ForbiddenException extends RuntimeException {
public ForbiddenException() {
super();
}
public ForbiddenException(String message) {
super(message);
}
public ForbiddenException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -1,24 +0,0 @@
package eu.eudat.exceptions.security;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class UnauthorisedException extends RuntimeException {
public UnauthorisedException() {
super();
}
public UnauthorisedException(String message, Throwable cause) {
super(message, cause);
}
public UnauthorisedException(String message) {
super(message);
}
public UnauthorisedException(Throwable cause) {
super(cause);
}
}

View File

@ -1,8 +0,0 @@
package eu.eudat.logic.builders;
/**
* Created by ikalyvas on 2/15/2018.
*/
public abstract class Builder<T> {
public abstract T build();
}

View File

@ -1,8 +0,0 @@
package eu.eudat.logic.builders;
/**
* Created by ikalyvas on 2/15/2018.
*/
public interface BuilderFactory {
<T extends Builder> T getBuilder(Class<T> tClass);
}

View File

@ -1,20 +0,0 @@
package eu.eudat.logic.builders;
import eu.eudat.logic.builders.entity.*;
import eu.eudat.logic.builders.model.models.*;
import org.springframework.stereotype.Service;
@Service
public class BuilderFactoryImpl implements BuilderFactory {
public <T extends Builder> T getBuilder(Class<T> tClass) {
if (tClass.equals(DatasetProfileBuilder.class)) return (T) new DatasetProfileBuilder();
if (tClass.equals(DataTableDataBuilder.class)) return (T) new DataTableDataBuilder<>();
if (tClass.equals(UserInfoBuilder.class)) return (T) new UserInfoBuilder();
if (tClass.equals(UserRoleBuilder.class)) return (T) new UserRoleBuilder();
if (tClass.equals(RecentActivityDataBuilder.class)) return (T) new RecentActivityDataBuilder();
return null;
}
}

View File

@ -1,100 +0,0 @@
package eu.eudat.logic.builders.entity;
import eu.eudat.commons.enums.DescriptionTemplateStatus;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.logic.builders.Builder;
import java.time.Instant;
import java.util.UUID;
/**
* Created by ikalyvas on 2/15/2018.
*/
public class DatasetProfileBuilder extends Builder<DescriptionTemplateEntity> {
private UUID id;
private String label;
private UUID type;
// private Set<Dataset> dataset;
private String definition;
private DescriptionTemplateStatus status;
private Instant created;
private Instant modified = Instant.now();
private String description;
private String language;
public DatasetProfileBuilder id(UUID id) {
this.id = id;
return this;
}
public DatasetProfileBuilder label(String label) {
this.label = label;
return this;
}
public DatasetProfileBuilder type(UUID type) {
this.type = type;
return this;
}
// public DatasetProfileBuilder dataset(Set<Dataset> dataset) {
// this.dataset = dataset;
// return this;
// }
public DatasetProfileBuilder definition(String definition) {
this.definition = definition;
return this;
}
public DatasetProfileBuilder status(DescriptionTemplateStatus status) {
this.status = status;
return this;
}
public DatasetProfileBuilder created(Instant created) {
this.created = created;
return this;
}
public DatasetProfileBuilder modified(Instant modified) {
this.modified = modified;
return this;
}
public DatasetProfileBuilder description(String description) {
this.description = description;
return this;
}
public DatasetProfileBuilder language(String language) {
this.language = language;
return this;
}
@Override
public DescriptionTemplateEntity build() {
DescriptionTemplateEntity descriptionTemplateEntity = new DescriptionTemplateEntity();
descriptionTemplateEntity.setCreatedAt(created);
descriptionTemplateEntity.setStatus(status);
descriptionTemplateEntity.setId(id);
// descriptionTemplate.setDataset(dataset);
descriptionTemplateEntity.setDefinition(definition);
descriptionTemplateEntity.setDescription(description);
descriptionTemplateEntity.setUpdatedAt(modified);
descriptionTemplateEntity.setLabel(label);
descriptionTemplateEntity.setLanguage(language);
descriptionTemplateEntity.setTypeId(type);
return descriptionTemplateEntity;
}
}

View File

@ -1,90 +0,0 @@
package eu.eudat.logic.builders.entity;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.data.UserCredentialEntity;
import eu.eudat.data.DmpEntity;
import eu.eudat.logic.builders.Builder;
import eu.eudat.data.UserEntity;
import eu.eudat.data.UserRoleEntity;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* Created by ikalyvas on 2/15/2018.
*/
public class UserInfoBuilder extends Builder<UserEntity> {
private UUID id;
private String name = null;
private Instant created = null;
private String additionalinfo;
private Set<DmpEntity> dmps;
private Set<UserCredentialEntity> credentials = new HashSet<>();
private Set<UserRoleEntity> userRoles = new HashSet<>();
private IsActive userStatus;
public UserInfoBuilder id(UUID id) {
this.id = id;
return this;
}
public UserInfoBuilder name(String name) {
this.name = name;
return this;
}
public UserInfoBuilder created(Instant created) {
this.created = created;
return this;
}
public UserInfoBuilder additionalinfo(String additionalinfo) {
this.additionalinfo = additionalinfo;
return this;
}
public UserInfoBuilder dmps(Set<DmpEntity> dmps) {
this.dmps = dmps;
return this;
}
public UserInfoBuilder credentials(Set<UserCredentialEntity> credentials) {
this.credentials = credentials;
return this;
}
public UserInfoBuilder userRoles(Set<UserRoleEntity> userRoles) {
this.userRoles = userRoles;
return this;
}
public UserInfoBuilder userStatus(IsActive userStatus) {
this.userStatus = userStatus;
return this;
}
@Override
public UserEntity build() {
UserEntity userInfo = new UserEntity();
userInfo.setId(id);
userInfo.setCreatedAt(created);
userInfo.setName(name);
userInfo.setAdditionalInfo(additionalinfo);
// userInfo.setUserRoles(userRoles);
// userInfo.setCredentials(credentials);
// userInfo.setDmps(dmps); //TODO
userInfo.setIsActive(userStatus);
return userInfo;
}
}

View File

@ -1,43 +0,0 @@
package eu.eudat.logic.builders.entity;
import eu.eudat.logic.builders.Builder;
import eu.eudat.data.UserEntity;
import eu.eudat.data.UserRoleEntity;
import java.util.UUID;
/**
* Created by ikalyvas on 2/15/2018.
*/
public class UserRoleBuilder extends Builder<UserRoleEntity> {
private UUID id;
private String role;
private UUID userId;
public UserRoleBuilder id(UUID id) {
this.id = id;
return this;
}
public UserRoleBuilder role(String role) {
this.role = role;
return this;
}
public UserRoleBuilder userInfo(UserEntity userInfo) {
this.userId = userInfo.getId();
return this;
}
@Override
public UserRoleEntity build() {
UserRoleEntity userRole = new UserRoleEntity();
userRole.setUserId(userId);
userRole.setRole(role);
userRole.setId(id);
return userRole;
}
}

View File

@ -1,8 +0,0 @@
package eu.eudat.logic.builders.helpers;
/**
* Created by ikalyvas on 3/15/2018.
*/
public interface BuilderApplier<T> {
void apply(T builder);
}

View File

@ -1,33 +0,0 @@
package eu.eudat.logic.builders.model.models;
import eu.eudat.logic.builders.Builder;
import eu.eudat.models.data.helpers.common.DataTableData;
import java.util.List;
/**
* Created by ikalyvas on 2/15/2018.
*/
public class DataTableDataBuilder<T> extends Builder<DataTableData<T>> {
private Long totalCount;
private List<T> data;
public DataTableDataBuilder<T> totalCount(Long totalCount) {
this.totalCount = totalCount;
return this;
}
public DataTableDataBuilder<T> data(List<T> data) {
this.data = data;
return this;
}
@Override
public DataTableData<T> build() {
DataTableData<T> dataTableData = new DataTableData<>();
dataTableData.setTotalCount(totalCount);
dataTableData.setData(data);
return dataTableData;
}
}

View File

@ -1,52 +0,0 @@
package eu.eudat.logic.builders.model.models;
import eu.eudat.logic.builders.Builder;
import eu.eudat.models.data.dashboard.recent.RecentActivityData;
import java.util.Date;
/**
* Created by ikalyvas on 3/14/2018.
*/
public class RecentActivityDataBuilder extends Builder<RecentActivityData> {
private String label;
private String id;
private Date timestamp;
public String getLabel() {
return label;
}
public RecentActivityDataBuilder label(String label) {
this.label = label;
return this;
}
public String getId() {
return id;
}
public RecentActivityDataBuilder id(String id) {
this.id = id;
return this;
}
public Date getTimestamp() {
return timestamp;
}
public RecentActivityDataBuilder timestamp(Date timestamp) {
this.timestamp = timestamp;
return this;
}
@Override
public RecentActivityData build() {
RecentActivityData recentActivityData = new RecentActivityData();
recentActivityData.setLabel(label);
recentActivityData.setTimestamp(timestamp);
recentActivityData.setId(id);
return recentActivityData;
}
}

View File

@ -1,29 +0,0 @@
package eu.eudat.logic.managers;
import eu.eudat.models.data.externalurl.ExternalSourcesConfiguration;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.service.remotefetcher.ExternalUrlConfigProvider;
import java.util.stream.Collectors;
/**
* Created by ikalyvas on 5/17/2018.
*/
public class CommonsManager {
public static ExternalSourcesConfiguration getExternalSourcesConfiguration(ConfigLoader configLoader, ExternalUrlConfigProvider externalUrlConfigProvider){
ExternalSourcesConfiguration externalSourcesConfiguration = new ExternalSourcesConfiguration();
externalSourcesConfiguration.setDataRepositories(externalUrlConfigProvider.getExternalUrls().getRepositories().getUrls().stream()
.map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList()));
externalSourcesConfiguration.setExternalDatasets(externalUrlConfigProvider.getExternalUrls().getDatasets().getUrls().stream()
.map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList()));
externalSourcesConfiguration.setRegistries(externalUrlConfigProvider.getExternalUrls().getRegistries().getUrls().stream()
.map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList()));
externalSourcesConfiguration.setServices(externalUrlConfigProvider.getExternalUrls().getServices().getUrls().stream()
.map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList()));
/*externalSourcesConfiguration.setTags(configLoader.getExternalUrls().getTags().getUrls().stream()
.map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList()));*/
return externalSourcesConfiguration;
}
}

View File

@ -1,34 +1,15 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import eu.eudat.commons.types.descriptiontemplate.FieldEntity;
import eu.eudat.commons.types.descriptiontemplate.fielddata.ExternalSelectDataEntity;
import eu.eudat.logic.xml.XmlBuilder;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader; import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.service.remotefetcher.config.entities.GeneralUrls;
import eu.eudat.service.remotefetcher.RemoteFetcherService; import eu.eudat.service.remotefetcher.RemoteFetcherService;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.service.remotefetcher.models.ExternalAutocompleteFieldResult;
import eu.eudat.service.remotefetcher.config.AuthenticationConfiguration;
import eu.eudat.service.remotefetcher.config.DataFieldsUrlConfiguration;
import eu.eudat.service.remotefetcher.config.DataUrlConfiguration;
import eu.eudat.service.remotefetcher.config.UrlConfiguration;
import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria;
import eu.eudat.service.remotefetcher.criteria.FetchStrategy;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.management.InvalidApplicationException; import javax.management.InvalidApplicationException;
import javax.xml.xpath.*; import javax.xml.xpath.XPathExpressionException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -42,156 +23,10 @@ public class DatasetProfileManager {
private final RemoteFetcherService remoteFetcherService; private final RemoteFetcherService remoteFetcherService;
@Autowired @Autowired
public DatasetProfileManager(ApiContext apiContext, ConfigLoader configLoader, RemoteFetcherService remoteFetcherService) { public DatasetProfileManager(ConfigLoader configLoader, RemoteFetcherService remoteFetcherService) {
this.configLoader = configLoader; this.configLoader = configLoader;
this.remoteFetcherService = remoteFetcherService; this.remoteFetcherService = remoteFetcherService;
} }
public FieldEntity queryForField(String xml, String fieldId) throws XPathExpressionException {
FieldEntity fieldEntity = new FieldEntity();
Document document = XmlBuilder.fromXml(xml);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
XPathExpression expr =
xpath.compile("//field[@id='" + fieldId + "']");
Element name = (Element) expr.evaluate(document, XPathConstants.NODE);
// fieldEntity.fromXml(name);
return fieldEntity;
}
public List<ExternalAutocompleteFieldResult> getAutocomplete(ExternalSelectDataEntity data, String like) {
/*List<ExternalAutocompleteFieldModel> result = new LinkedList<>();
SimpleClientHttpRequestFactory simpleFactory = new SimpleClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(simpleFactory);
HttpHeaders headers = new HttpHeaders();
DocumentContext jsonContext = null;
HttpEntity<String> entity;
ResponseEntity response;
List<Map<String, String>> jsonItems;
int i = 0;
for (AutoCompleteData.AutoCompleteSingleData singleData: data.getAutoCompleteSingleDataList()) {
switch (AutoCompleteData.AutocompleteType.fromValue(singleData.getAutocompleteType())) {
case UNCACHED:
String url = singleData.getUrl();
String mediaType = "";
if (url.contains("openaire") || url.contains("zenodo")) {
mediaType = "application/json; charset=utf-8";
if (url.contains("zenodo")) {
url = url.replace("?", "/?");
}
url = url.replace("{like}", like.equals("") ? "*" : like);
url = url.replace("%20", " ");
url = url.replace("%22", "\"");
url = url.replace("&amp;", "&");
} else {
mediaType = "application/vnd.api+json; charset=utf-8";
url += "?search=" + like;
}
if (!url.contains("zenodo")) {
headers.setAccept(Collections.singletonList(MediaType.valueOf(mediaType)));
}
headers.setContentType(MediaType.APPLICATION_JSON);
entity = new HttpEntity<>("parameters", headers);
response = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
jsonContext = JsonPath.parse(response.getBody());
jsonItems = jsonContext.read(singleData.getOptionsRoot() + "['" + singleData.getAutoCompleteOptions().getLabel() + "','" + singleData.getAutoCompleteOptions().getValue() + "','" + singleData.getAutoCompleteOptions().getSource() + "','" + "uri" + "']");
jsonItems.forEach(item -> result.add(new ExternalAutocompleteFieldModel(parseItem(item.get(singleData.getAutoCompleteOptions().getValue())), parseItem(item.get(singleData.getAutoCompleteOptions().getLabel())), item.get(singleData.getAutoCompleteOptions().getSource()) != null ? parseItem(item.get(singleData.getAutoCompleteOptions().getSource())) : singleData.getAutoCompleteOptions().getSource(), parseItem(item.get("uri")))));
break;
case CACHED:
headers.setAccept(Collections.singletonList(MediaType.valueOf("text/plain; charset=utf-8")));
headers.setContentType(MediaType.TEXT_PLAIN);
entity = new HttpEntity<>("parameters", headers);
if (cache.size() <= i) {
response = restTemplate.exchange(singleData.getUrl(), HttpMethod.GET, entity, String.class);
cache.add((String) response.getBody());
}
jsonContext = JsonPath.parse(cache.get(i));
jsonItems = jsonContext.read(singleData.getOptionsRoot() + "['" + singleData.getAutoCompleteOptions().getLabel() + "','" + singleData.getAutoCompleteOptions().getValue() + "','" + singleData.getAutoCompleteOptions().getSource() + "','" + "uri" + "']");
jsonItems.stream().filter(item -> item.get(singleData.getAutoCompleteOptions().getLabel()).toLowerCase().contains(like.toLowerCase()))
.forEach(item -> result.add(new ExternalAutocompleteFieldModel(item.get(singleData.getAutoCompleteOptions().getValue()), item.get(singleData.getAutoCompleteOptions().getLabel()), item.get(singleData.getAutoCompleteOptions().getSource()) != null ? item.get(singleData.getAutoCompleteOptions().getSource()) : singleData.getAutoCompleteOptions().getSource(), item.get("uri"))));
i++;
break;
}
}
return result.stream().sorted(Comparator.comparing(ExternalAutocompleteFieldModel::getLabel)).collect(Collectors.toList());
*/
List<ExternalAutocompleteFieldResult> result = new LinkedList<>();
ExternalReferenceCriteria urlCriteria = new ExternalReferenceCriteria();
GeneralUrls genericUrls = new GeneralUrls();
int ordinal = 1;
List<Map<String, String>> rawResults = new ArrayList<>();
genericUrls.setFetchMode(FetchStrategy.FIRST);
urlCriteria.setLike(like);
for (ExternalSelectDataEntity.ExternalSelectSourceEntity singleData : data.getSources()) {
UrlConfiguration urlConfiguration = new UrlConfiguration();
try {
URI uri;
if (singleData.getUrl().contains("?")) {
uri = new URI(singleData.getUrl().substring(0, singleData.getUrl().lastIndexOf("?")));
} else {
uri = new URI(singleData.getUrl());
}
String source = singleData.getSourceBinding().getSource();
source = source != null && !source.isEmpty() ? source : uri.getHost();
// String uriString = singleData.getSourceBinding().getUri();
// uriString = uriString != null && !uriString.isEmpty() ? uriString : "uri";
String uriString = "uri";
String parsedUrl = singleData.getUrl();
parsedUrl = parsedUrl.replace("%20", " ");
parsedUrl = parsedUrl.replace("%22", "\"");
while (parsedUrl.contains("&amp;")) {
parsedUrl = parsedUrl.replace("&amp;", "&");
}
urlConfiguration.setUrl(parsedUrl);
urlConfiguration.setOrdinal(ordinal);
urlConfiguration.setType("External");
urlConfiguration.setContentType(MediaType.APPLICATION_JSON_VALUE);
urlConfiguration.setFirstpage("1");
urlConfiguration.setRequestType(singleData.getMethod() != null ? singleData.getMethod() : "GET");
DataUrlConfiguration dataUrlConfiguration = new DataUrlConfiguration();
dataUrlConfiguration.setPath(singleData.getOptionsRoot());
DataFieldsUrlConfiguration fieldsUrlConfiguration = new DataFieldsUrlConfiguration();
fieldsUrlConfiguration.setId(singleData.getSourceBinding().getValue());
fieldsUrlConfiguration.setName(singleData.getSourceBinding().getLabel());
fieldsUrlConfiguration.setSource(singleData.getSourceBinding().getSource().isEmpty()? null : singleData.getSourceBinding().getSource());
fieldsUrlConfiguration.setUri(uriString);
dataUrlConfiguration.setFieldsUrlConfiguration(fieldsUrlConfiguration);
urlConfiguration.setKey(source);
urlConfiguration.setLabel(source);
urlConfiguration.setData(dataUrlConfiguration);
if (singleData.getHasAuth()) {
AuthenticationConfiguration authenticationConfiguration = new AuthenticationConfiguration();
authenticationConfiguration.setAuthUrl(singleData.getAuth().getUrl());
authenticationConfiguration.setAuthMethod(singleData.getAuth().getMethod());
authenticationConfiguration.setAuthTokenPath(singleData.getAuth().getPath());
authenticationConfiguration.setAuthRequestBody(singleData.getAuth().getBody());
authenticationConfiguration.setType(singleData.getAuth().getType());
urlConfiguration.setAuth(authenticationConfiguration);
}
genericUrls.getUrls().add(urlConfiguration);
List<Map<String, String>> singleResults = this.remoteFetcherService.getExternalGeneric(urlCriteria, genericUrls);
if (!singleResults.isEmpty() && !singleResults.get(0).containsKey("source") && !singleData.getSourceBinding().getSource().isEmpty()) {
singleResults.forEach(singleResult -> singleResult.put("source", singleData.getSourceBinding().getSource()));
}
rawResults.addAll(singleResults);
genericUrls.getUrls().clear();
} catch (URISyntaxException e) {
logger.error(e.getMessage(), e);
}
}
rawResults.forEach(item -> result.add(new ExternalAutocompleteFieldResult(parseItem(item.get("pid")), parseItem(item.get("name")), parseItem(item.get("source")), parseItem(item.get("uri")))));
return result;
}
private static String parseItem(Object item) { private static String parseItem(Object item) {
if (item instanceof String) { if (item instanceof String) {
return (String) item; return (String) item;
@ -249,26 +84,6 @@ public class DatasetProfileManager {
// } // }
// } // }
// this.updateDatasetProfileXml(document, descriptionTemplateEntity); // this.updateDatasetProfileXml(document, descriptionTemplateEntity);
// }
}
private void updateDatasetProfileXml(Document document, DescriptionTemplateEntity descriptionTemplateEntity) {
// try {
// DOMSource domSource = new DOMSource(document);
// StringWriter writer = new StringWriter();
// StreamResult result = new StreamResult(writer);
// TransformerFactory tf = TransformerFactory.newInstance();
// Transformer transformer = tf.newTransformer();
// transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// transformer.transform(domSource, result);
// String newDefinition = writer.toString();
// if(newDefinition != null){
// descriptionTemplateEntity.setDefinition(newDefinition);
// this.databaseRepository.getDatasetProfileDao().createOrUpdate(descriptionTemplateEntity);
// }
// }
// catch(TransformerException ex) {
// logger.error(ex.getMessage(), ex);
// } // }
} }
} }

View File

@ -2,7 +2,7 @@ package eu.eudat.logic.managers;
import eu.eudat.logic.proxy.fetching.LocalFetcher; import eu.eudat.logic.proxy.fetching.LocalFetcher;
import eu.eudat.utilities.helpers.StreamDistinctBy; import eu.eudat.utilities.helpers.StreamDistinctBy;
import eu.eudat.models.data.local.LocalFetchModel; import eu.eudat.models.old.local.LocalFetchModel;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;

View File

@ -1,51 +0,0 @@
package eu.eudat.logic.managers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Component
public class MaterialManager {
@Autowired
public MaterialManager(){}
public ResponseEntity<byte[]> getResponseEntity(String lang, Stream<Path> paths) throws IOException {
List<String> result = paths.filter(Files::isRegularFile)
.map(Path::toString).collect(Collectors.toList());
String fileName = result.stream().filter(about -> about.contains("_" + lang)).findFirst().orElse(null);
if (fileName == null) {
fileName = result.stream().filter(about -> about.contains("_en")).findFirst().get();
}
InputStream is = new FileInputStream(fileName);
Path path = Paths.get(fileName);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(is.available());
responseHeaders.setContentType(MediaType.TEXT_HTML);
responseHeaders.set("Content-Disposition", "attachment;filename=" + path.getFileName().toString());
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = new byte[is.available()];
is.read(content);
is.close();
return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK);
}
}

View File

@ -1,32 +1,25 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import eu.eudat.commons.enums.DescriptionTemplateStatus; import eu.eudat.commons.enums.DescriptionTemplateStatus;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.data.dao.criteria.*;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.query.DmpDescriptionTemplateQuery;
import eu.eudat.types.MetricNames; import eu.eudat.types.MetricNames;
import gr.cite.tools.data.query.QueryFactory;
import io.micrometer.prometheus.PrometheusMeterRegistry; import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.Gauge; import io.prometheus.client.Gauge;
import jakarta.annotation.PostConstruct;
import jakarta.transaction.Transactional;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException; import javax.management.InvalidApplicationException;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.*; import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -77,15 +70,9 @@ public class MetricsManager {
} }
} }
private final ApiContext apiContext;
private final Environment environment;
private final QueryFactory queryFactory;
@Autowired @Autowired
public MetricsManager(ApiContext apiContext, Environment environment, PrometheusMeterRegistry registry, QueryFactory queryFactory) { public MetricsManager(PrometheusMeterRegistry registry) {
this.apiContext = apiContext;
this.environment = environment;
this.queryFactory = queryFactory;
registry.clear(); registry.clear();
this.gauges = Stream.of( new Object[][]{ this.gauges = Stream.of( new Object[][]{
{MetricNames.DMP, Gauge.build().name(MetricNames.DMP).help("Number of managed DMPs").labelNames("status").register(registry.getPrometheusRegistry())}, {MetricNames.DMP, Gauge.build().name(MetricNames.DMP).help("Number of managed DMPs").labelNames("status").register(registry.getPrometheusRegistry())},
@ -207,9 +194,9 @@ public class MetricsManager {
} }
private long countAllDraftDMPs(boolean countNexus) throws InvalidApplicationException { private long countAllDraftDMPs(boolean countNexus) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setStatus(0); // criteria.setStatus(0);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count();
return 0; return 0;
} }
@ -219,9 +206,9 @@ public class MetricsManager {
} }
private long countAllFinalizedDMPs(boolean countNexus) throws InvalidApplicationException { private long countAllFinalizedDMPs(boolean countNexus) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setStatus(1); // criteria.setStatus(1);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count();
return 0; return 0;
} }
@ -231,10 +218,10 @@ public class MetricsManager {
} }
private long countAllPublishedDMPs(boolean countNexus) throws InvalidApplicationException { private long countAllPublishedDMPs(boolean countNexus) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setIsPublic(true); // criteria.setIsPublic(true);
criteria.setOnlyPublic(true); // criteria.setOnlyPublic(true);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count();
return 0; return 0;
} }
@ -244,9 +231,9 @@ public class MetricsManager {
} }
private long countAllDoiedDMPs(boolean countNexus) throws InvalidApplicationException { private long countAllDoiedDMPs(boolean countNexus) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setHasDoi(true); // criteria.setHasDoi(true);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count();
return 0; return 0;
} }
@ -256,9 +243,9 @@ public class MetricsManager {
} }
private long countAllDraftDMPsWithGrantId(boolean countNexus) throws InvalidApplicationException { private long countAllDraftDMPsWithGrantId(boolean countNexus) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setStatus(0); // criteria.setStatus(0);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count();
return 0; return 0;
} }
@ -268,9 +255,9 @@ public class MetricsManager {
} }
private long countAllFinalizedDMPsWithGrantId(boolean countNexus) throws InvalidApplicationException { private long countAllFinalizedDMPsWithGrantId(boolean countNexus) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setStatus(1); // criteria.setStatus(1);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count();
return 0; return 0;
} }
@ -280,10 +267,10 @@ public class MetricsManager {
} }
private long countAllPublishedDMPsWithGrantId(boolean countNexus) throws InvalidApplicationException { private long countAllPublishedDMPsWithGrantId(boolean countNexus) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setIsPublic(true); // criteria.setIsPublic(true);
criteria.setOnlyPublic(true); // criteria.setOnlyPublic(true);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count();
return 0; return 0;
} }
@ -293,9 +280,9 @@ public class MetricsManager {
} }
private long countAllDoiedDMPsWithGrantId(boolean countNexus) throws InvalidApplicationException { private long countAllDoiedDMPsWithGrantId(boolean countNexus) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setHasDoi(true); // criteria.setHasDoi(true);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count();
return 0; return 0;
} }
@ -349,9 +336,9 @@ public class MetricsManager {
} }
public long countAllDraftDatasets(boolean countNexus) throws InvalidApplicationException { public long countAllDraftDatasets(boolean countNexus) throws InvalidApplicationException {
eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria(); // eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria();
criteria.setStatus(0); // criteria.setStatus(0);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count();
return 0; return 0;
} }
@ -361,9 +348,9 @@ public class MetricsManager {
} }
public long countAllFinalizedDatasets(boolean countNexus) throws InvalidApplicationException { public long countAllFinalizedDatasets(boolean countNexus) throws InvalidApplicationException {
eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria(); // eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria();
criteria.setStatus(1); // criteria.setStatus(1);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count();
return 0; return 0;
} }
@ -373,9 +360,9 @@ public class MetricsManager {
} }
public long countAllPublicDatasets(boolean countNexus) throws InvalidApplicationException { public long countAllPublicDatasets(boolean countNexus) throws InvalidApplicationException {
eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria(); // eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria();
criteria.setIsPublic(true); // criteria.setIsPublic(true);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count();
return 0; return 0;
} }
@ -385,9 +372,9 @@ public class MetricsManager {
} }
public long countAllDatasetsWithDoi(boolean countNexus) throws InvalidApplicationException { public long countAllDatasetsWithDoi(boolean countNexus) throws InvalidApplicationException {
eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria(); // eu.eudat.data.dao.criteria.DatasetCriteria criteria = new eu.eudat.data.dao.criteria.DatasetCriteria();
criteria.setHasDoi(true); // criteria.setHasDoi(true);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count();
return 0; return 0;
} }
@ -397,9 +384,9 @@ public class MetricsManager {
} }
public long countAllDraftTemplates(boolean countNexus) throws InvalidApplicationException { public long countAllDraftTemplates(boolean countNexus) throws InvalidApplicationException {
DatasetProfileCriteria criteria = new DatasetProfileCriteria(); // DatasetProfileCriteria criteria = new DatasetProfileCriteria();
criteria.setStatus(0); // criteria.setStatus(0);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
return 0; return 0;
//return apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).count(); //return apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).count();
} }
@ -409,9 +396,9 @@ public class MetricsManager {
} }
public long countAllFinalizedTemplates(boolean countNexus) throws InvalidApplicationException { public long countAllFinalizedTemplates(boolean countNexus) throws InvalidApplicationException {
DatasetProfileCriteria criteria = new DatasetProfileCriteria(); // DatasetProfileCriteria criteria = new DatasetProfileCriteria();
criteria.setStatus(1); // criteria.setStatus(1);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
return 0; return 0;
// return apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).count(); // return apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).count();
} }
@ -423,10 +410,10 @@ public class MetricsManager {
@Transactional @Transactional
public long countAllUsedTemplates(boolean countNexus) throws InvalidApplicationException { public long countAllUsedTemplates(boolean countNexus) throws InvalidApplicationException {
DatasetProfileCriteria criteria = new DatasetProfileCriteria(); // DatasetProfileCriteria criteria = new DatasetProfileCriteria();
criteria.setStatus(1); // criteria.setStatus(1);
criteria.setAllVersions(false); // criteria.setAllVersions(false);
if (countNexus) criteria.setPeriodStart(getNexusDate()); // if (countNexus) criteria.setPeriodStart(getNexusDate());
// List<DescriptionTemplateEntity> descriptionTemplateEntities = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).withFields(Collections.singletonList("id")).toList(); // List<DescriptionTemplateEntity> descriptionTemplateEntities = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).withFields(Collections.singletonList("id")).toList();
// DatasetCriteria datasetCriteria = new DatasetCriteria(); // DatasetCriteria datasetCriteria = new DatasetCriteria();
// datasetCriteria.setDatasetTemplates(descriptionTemplateEntities.stream().map(DescriptionTemplateEntity::getId).collect(Collectors.toList())); // datasetCriteria.setDatasetTemplates(descriptionTemplateEntities.stream().map(DescriptionTemplateEntity::getId).collect(Collectors.toList()));

View File

@ -1,50 +0,0 @@
package eu.eudat.logic.managers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.DmpEntity;
import eu.eudat.models.rda.Dmp;
import eu.eudat.models.rda.RDAModel;
import eu.eudat.models.rda.mapper.DmpRDAMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.text.SimpleDateFormat;
@Component
public class RDAManager {
private DmpRDAMapper dmpRDAMapper;
@Autowired
public RDAManager(DmpRDAMapper dmpRDAMapper) {
this.dmpRDAMapper = dmpRDAMapper;
}
@Transactional
public String convertToRDA(DmpEntity dmp) throws JsonProcessingException, InvalidApplicationException {
String result = "";
Dmp rdaDmp = dmpRDAMapper.toRDA(dmp);
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
RDAModel model = new RDAModel();
model.setDmp(rdaDmp);
result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(model);
return result;
}
public DmpEntity convertToEntity(String json, String[] profiles) throws IOException, InvalidApplicationException {
ObjectMapper mapper = new ObjectMapper();
Dmp rda = mapper.readValue(json, RDAModel.class).getDmp();
return dmpRDAMapper.toEntity(rda, profiles);
}
}

View File

@ -1,64 +0,0 @@
package eu.eudat.logic.proxy;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
@RestController
@CrossOrigin
public class Proxy {
private String allowedHost;
public Proxy(String allowedHost) throws MalformedURLException {
this.allowedHost = new URL(allowedHost).getHost();
}
public Proxy() {
}
@RequestMapping(method = RequestMethod.GET, value = {"/eu/eudat/logic/proxy"}, produces = "application/json")
public @ResponseBody
ResponseEntity<Object> proxy(@RequestParam("url") String remoteUrl) {
StringBuffer response = new StringBuffer();
URL url;
try {
URL tempUrl = new URL(remoteUrl);
// URI uri = new URI(scheme, userInfo, host, port, path, query, fragment);
URI uri = new URI(tempUrl.getProtocol(), null, tempUrl.getHost(), tempUrl.getPort(), tempUrl.getPath(), (tempUrl.getQuery() != null) ? URLEncoder.encode(tempUrl.getQuery()) : null, tempUrl.getRef());
url = uri.toURL();
if (!url.getHost().equals(allowedHost))
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{'reason': 'You are not allowed to eu.eudat.logic.proxy -> " + url.getHost() + "'}");
//if allowed, proceed
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/vnd.api+json; charset=utf-8");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return ResponseEntity.status(HttpStatus.OK).body(response.toString());
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{'reason': 'Remote server responded with: " + responseCode + "'}");
}
} catch (IOException | URISyntaxException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{'reason': 'Could not eu.eudat.logic.proxy to given host'}");
}
}
}

View File

@ -1,23 +0,0 @@
package eu.eudat.logic.proxy.config;
public enum AuthType {
;
private final String name;
AuthType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static AuthType fromName(String name) {
for (AuthType authType : AuthType.values()) {
if (authType.getName().equals(name)) {
return authType;
}
}
throw new IllegalArgumentException("AuthType [" + name + "] is not supported");
}
}

View File

@ -1,24 +0,0 @@
package eu.eudat.logic.proxy.config;
import jakarta.xml.bind.annotation.XmlElement;
public class DataSearchConfiguration {
private String type;
private String queryParam;
public String getType() {
return type;
}
@XmlElement(name = "type")
public void setType(String type) {
this.type = type;
}
public String getQueryParam() {
return queryParam;
}
@XmlElement(name = "queryparam")
public void setQueryParam(String queryParam) {
this.queryParam = queryParam;
}
}

View File

@ -1,13 +1,8 @@
package eu.eudat.logic.proxy.config.configloaders; package eu.eudat.logic.proxy.config.configloaders;
import eu.eudat.models.data.pid.PidLinks;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.util.Map;
public interface ConfigLoader { public interface ConfigLoader {
XWPFDocument getDocument(); XWPFDocument getDocument();
XWPFDocument getDatasetDocument();
PidLinks getPidLinks();
Map<String, String> getKeyToSourceMap();
} }

View File

@ -1,8 +1,6 @@
package eu.eudat.logic.proxy.config.configloaders; package eu.eudat.logic.proxy.config.configloaders;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.models.data.pid.PidLinks;
import eu.eudat.service.storage.StorageFileService; import eu.eudat.service.storage.StorageFileService;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -12,18 +10,14 @@ import org.springframework.stereotype.Service;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactory;
import java.io.*; import java.io.ByteArrayInputStream;
import java.util.*; import java.util.LinkedList;
import java.util.stream.Collectors; import java.util.List;
@Service("configLoader") @Service("configLoader")
public class DefaultConfigLoader implements ConfigLoader { public class DefaultConfigLoader implements ConfigLoader {
@ -31,9 +25,6 @@ public class DefaultConfigLoader implements ConfigLoader {
private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectMapper mapper = new ObjectMapper();
private XWPFDocument document; private XWPFDocument document;
private XWPFDocument datasetDocument;
private PidLinks pidLinks;
private Map<String, String> keyToSourceMap;
@Autowired @Autowired
private StorageFileService storageFileService; private StorageFileService storageFileService;
@ -48,107 +39,11 @@ public class DefaultConfigLoader implements ConfigLoader {
} }
} }
private void setDatasetDocument() {
byte[] bytes = this.storageFileService.getH2020DescriptionTemplateFile();
try {
this.datasetDocument = new XWPFDocument(new ByteArrayInputStream(bytes));
} catch (Exception ex) {
logger.error("Cannot find resource", ex);
}
}
private void setPidLinks() {
byte[] bytes = this.storageFileService.getPidLinksFile();
try {
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.pidLinks = mapper.readValue(new ByteArrayInputStream(bytes), PidLinks.class);
} catch (Exception ex) {
logger.error("Cannot find resource", ex);
}
}
private void setKeyToSourceMap() {
byte[] bytes = this.storageFileService.getExternalUrlsFile();
try {
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.pidLinks = mapper.readValue(new ByteArrayInputStream(bytes), PidLinks.class);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(new ByteArrayInputStream(bytes));
if (doc == null) {
this.keyToSourceMap = null;
return;
}
String xpathExpression = "//key";
Map<String, String> keysToSourceMap = new HashMap<>();
List<String> keys = getXmlValuesFromXPath(doc, xpathExpression);
keys = keys.stream().distinct().collect(Collectors.toList());
for (String key : keys) {
String sourceExpression = String.format("//urlConfig[key='%s']/label", key);
List<String> sources = getXmlValuesFromXPath(doc, sourceExpression);
if (sources.size() != 0) {
keysToSourceMap.put(key, sources.get(0));
}
}
this.keyToSourceMap = keysToSourceMap;
} catch (Exception ex) {
logger.error("Cannot find resource", ex);
}
}
public XWPFDocument getDocument() { public XWPFDocument getDocument() {
this.setDocument(); this.setDocument();
return document; return document;
} }
public XWPFDocument getDatasetDocument() {
this.setDatasetDocument();
return datasetDocument;
}
public PidLinks getPidLinks() {
if (pidLinks == null) {
pidLinks = new PidLinks();
this.setPidLinks();
}
return pidLinks;
}
public Map<String, String> getKeyToSourceMap() {
if (keyToSourceMap == null) {
keyToSourceMap = new HashMap<>();
this.setKeyToSourceMap();
}
return keyToSourceMap;
}
private Document getXmlDocumentFromFilePath(String filePath) {
InputStream is = null;
Document doc;
try {
is = getStreamFromPath(filePath);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
doc = documentBuilder.parse(is);
return doc;
} catch (IOException | ParserConfigurationException | SAXException | NullPointerException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e);
}
}
return null;
}
private List<String> getXmlValuesFromXPath(Document doc, String expression) { private List<String> getXmlValuesFromXPath(Document doc, String expression) {
XPath xPath = XPathFactory.newInstance().newXPath(); XPath xPath = XPathFactory.newInstance().newXPath();
@ -169,13 +64,4 @@ public class DefaultConfigLoader implements ConfigLoader {
} }
return values; return values;
} }
private InputStream getStreamFromPath(String filePath) {
try {
return new FileInputStream(filePath);
} catch (FileNotFoundException e) {
logger.info("loading from classpath");
return getClass().getClassLoader().getResourceAsStream(filePath);
}
}
} }

View File

@ -1,240 +0,0 @@
/*package eu.eudat.logic.proxy.config.configloaders;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.logic.proxy.config.ExternalUrls;
import eu.eudat.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProviders;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service("configLoader")
@Profile({ "production", "staging" })
public class ProductionConfigLoader implements ConfigLoader {
private static final Logger logger = LoggerFactory.getLogger(ProductionConfigLoader.class);
private ExternalUrls externalUrls;
private List<String> rdaProperties;
private XWPFDocument document;
private ConfigurableProviders configurableProviders;
private Map<String, String> keyToSourceMap;
@Autowired
private Environment environment;
private void setExternalUrls() {
String fileUrl = this.environment.getProperty("configuration.externalUrls");
logger.info("Loaded also config file: " + fileUrl);
String current = null;
InputStream is = null;
try {
current = new java.io.File(".").getCanonicalPath();
JAXBContext jaxbContext = JAXBContext.newInstance(ExternalUrls.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
is = new URL(Paths.get(fileUrl).toUri().toURL().toString()).openStream();
externalUrls = (ExternalUrls) jaxbUnmarshaller.unmarshal(is);
} catch (Exception ex) {
logger.error("Cannot find in folder" + current, ex);
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e);
}
}
}
private void setRdaProperties() {
String filePath = environment.getProperty("configuration.rda");
BufferedReader reader;
List<String> rdaList = new LinkedList<>();
for (int i = 0; i < 2; i++) {
try {
if (i == 0) {
reader = new BufferedReader(new FileReader(filePath));
} else {
reader = new BufferedReader(new FileReader(getClass().getClassLoader().getResource(filePath).getFile()));
}
String line = reader.readLine();
while (line != null) {
rdaList.add(line);
line = reader.readLine();
}
reader.close();
break;
} catch (IOException e) {
if (i == 1) {
logger.error(e.getMessage(), e);
}
}
}
rdaProperties = rdaList;
}
private void setDocument() {
String filePath = environment.getProperty("configuration.h2020template");
InputStream is = null;
for (int i = 0; i < 2; i++) {
try {
if (i == 0) {
is = new URL(Paths.get(filePath).toUri().toURL().toString()).openStream();
} else {
is = getClass().getClassLoader().getResource(filePath).openStream();
}
this.document = new XWPFDocument(is);
is.close();
is = null;
break;
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e);
}
}
}
}
private void setConfigurableProviders() {
String filePath = environment.getProperty("configuration.configurable_login_providers");
InputStream is = null;
try {
File tempFile = new File(filePath);
if (tempFile.exists()) {
is = new URL(Paths.get(filePath).toUri().toURL().toString()).openStream();
} else {
is = getClass().getClassLoader().getResource(filePath).openStream();
}
ObjectMapper objectMapper = new ObjectMapper();
this.configurableProviders = objectMapper.readValue(is, ConfigurableProviders.class);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e);
}
}
}
private void setKeyToSourceMap() {
String filePath = this.environment.getProperty("configuration.externalUrls");
logger.info("Loaded also config file: " + filePath);
Document doc = getXmlDocumentFromFilePath(filePath);
if (doc == null) {
this.keyToSourceMap = null;
return;
}
String xpathExpression = "//key";
Map<String, String> keysToSourceMap = new HashMap<>();
List<String> keys = getXmlValuesFromXPath(doc, xpathExpression);
keys = keys.stream().distinct().collect(Collectors.toList());
for (String key : keys) {
String sourceExpression = String.format("//urlConfig[key='%s']/label", key);
List<String> sources = getXmlValuesFromXPath(doc, sourceExpression);
if (sources.size() != 0) {
keysToSourceMap.put(key, sources.get(0));
}
}
this.keyToSourceMap = keysToSourceMap;
}
public ExternalUrls getExternalUrls() {
this.setExternalUrls();
return externalUrls;
}
public List<String> getRdaProperties() {
this.setRdaProperties();
return rdaProperties;
}
public XWPFDocument getDocument() {
this.setDocument();
return document;
}
public ConfigurableProviders getConfigurableProviders() {
this.setConfigurableProviders();
return configurableProviders;
}
public Map<String, String> getKeyToSourceMap() {
this.setKeyToSourceMap();
return keyToSourceMap;
}
private Document getXmlDocumentFromFilePath(String filePath) {
InputStream is = null;
Document doc;
try {
System.out.println(filePath);
is = new URL(Paths.get(filePath).toUri().toURL().toString()).openStream();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
doc = documentBuilder.parse(is);
return doc;
} catch (IOException | ParserConfigurationException | SAXException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e);
}
}
return null;
}
private List<String> getXmlValuesFromXPath(Document doc, String expression) {
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = null;
List<String> values = new LinkedList<>();
try {
nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
logger.error(e.getMessage(), e);
}
if (nodeList != null) {
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.hasChildNodes()) {
values.add(nodeList.item(i).getChildNodes().item(0).getNodeValue());
}
}
}
return values;
}
}*/

View File

@ -1,12 +0,0 @@
package eu.eudat.logic.services;
import eu.eudat.logic.services.helpers.HelpersService;
import eu.eudat.logic.services.operations.OperationsContext;
public interface ApiContext {
HelpersService getHelpersService();
OperationsContext getOperationsContext();
}

View File

@ -1,31 +0,0 @@
package eu.eudat.logic.services;
import eu.eudat.logic.services.helpers.HelpersService;
import eu.eudat.logic.services.operations.OperationsContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("apiContext")
public class ApiContextImpl implements ApiContext {
private OperationsContext operationsContext;
private HelpersService helpersService;
@Autowired
public ApiContextImpl(OperationsContext operationsContext, HelpersService helpersService) {
this.operationsContext = operationsContext;
this.helpersService = helpersService;
}
@Override
public OperationsContext getOperationsContext() {
return operationsContext;
}
@Override
public HelpersService getHelpersService() {
return helpersService;
}
}

View File

@ -1,45 +0,0 @@
package eu.eudat.logic.services.forms;
import eu.eudat.models.data.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

@ -1,27 +0,0 @@
package eu.eudat.logic.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

@ -1,17 +0,0 @@
package eu.eudat.logic.services.forms;
import eu.eudat.models.data.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

@ -1,60 +0,0 @@
package eu.eudat.logic.services.forms;
import eu.eudat.models.data.user.components.commons.Rule;
import java.util.*;
/**
* Created by ikalyvas on 3/5/2018.
*/
public class VisibilityRuleServiceImpl implements VisibilityRuleService {
private final Map<String, Boolean> elementVisibility = new HashMap<>();
private Map<String, Object> properties;
public boolean isElementVisible(String id) {
return !this.elementVisibility.containsKey(id) || this.elementVisibility.get(id);
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
this.properties.entrySet().stream()
.filter(stringObjectEntry -> stringObjectEntry.getValue() instanceof String && ((String) stringObjectEntry.getValue()).startsWith("[")
&& ((String) stringObjectEntry.getValue()).endsWith("]"))
.forEach(stringObjectEntry -> stringObjectEntry.setValue(parseArray((String) stringObjectEntry.getValue())));
}
private List<String> parseArray(String original) {
String parsed = original.replace("[", "").replace("\"", "").replace("]", "");
return Arrays.asList(parsed.split(","));
}
public void buildVisibilityContext(List<Rule> sources) {
VisibilityContext visibilityContext = new VisibilityContext();
visibilityContext.buildVisibilityContext(sources);
visibilityContext.getVisibilityRules().forEach(this::evaluateVisibility);
}
private void evaluateVisibility(VisibilityRule rule) {
List<VisibilityRuleSource> sources = rule.getVisibilityRuleSources();
for(VisibilityRuleSource source: sources){
if (properties.containsKey(source.getVisibilityRuleSourceId())
&& isContained(properties.get(source.getVisibilityRuleSourceId()), source.getVisibilityRuleSourceValue())) {
this.elementVisibility.put(rule.getVisibilityRuleTargetId(), true);
} else {
this.elementVisibility.put(rule.getVisibilityRuleTargetId(),
this.elementVisibility.getOrDefault(rule.getVisibilityRuleTargetId(), false));
}
}
}
private Boolean isContained(Object values, String source) {
if (values instanceof List) {
return ((Collection<?>) values).contains(source);
} else {
if (values != null) {
return values.equals(source);
}
return false;
}
}
}

View File

@ -1,25 +0,0 @@
package eu.eudat.logic.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

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

View File

@ -1,31 +0,0 @@
package eu.eudat.logic.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

@ -1,12 +0,0 @@
package eu.eudat.logic.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

@ -1,21 +0,0 @@
package eu.eudat.logic.services.operations;
import eu.eudat.logic.builders.BuilderFactory;
import eu.eudat.service.remotefetcher.RemoteFetcherService;
import org.springframework.context.ApplicationContext;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface OperationsContext {
ApplicationContext getApplicationContext();
BuilderFactory getBuilderFactory();
RemoteFetcherService getRemoteFetcher();
// FileStorageService getFileStorageService();
// ElasticRepository getElasticRepository();
}

View File

@ -1,55 +0,0 @@
package eu.eudat.logic.services.operations;
import eu.eudat.logic.builders.BuilderFactory;
import eu.eudat.service.remotefetcher.RemoteFetcherService;
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 final ApplicationContext applicationContext;
private final RemoteFetcherService remoteFetcherService;
private final BuilderFactory builderFactory;
// private final FileStorageService fileStorageService;
// private final ElasticRepository elasticRepository;
@Autowired
public OperationsContextImpl(ApplicationContext applicationContext, RemoteFetcherService remoteFetcherService
, BuilderFactory builderFactory/*FileStorageService fileStorageService, ElasticRepository elasticRepository*/) {
this.applicationContext = applicationContext;
this.remoteFetcherService = remoteFetcherService;
this.builderFactory = builderFactory;
// this.fileStorageService = fileStorageService;
// this.elasticRepository = elasticRepository;
}
@Override
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public RemoteFetcherService getRemoteFetcher() {
return remoteFetcherService;
}
@Override
public BuilderFactory getBuilderFactory() {
return builderFactory;
}
// @Override
// public FileStorageService getFileStorageService() {
// return fileStorageService;
// }
// @Override
// public ElasticRepository getElasticRepository() {
// return elasticRepository;
// }
}

View File

@ -1,49 +0,0 @@
package eu.eudat.logic.utilities.documents.types;
/**
* Created by ikalyvas on 2/26/2018.
*/
public enum ParagraphStyle {
TEXT(0), HEADER1(1), HEADER2(2), HEADER3(3), HEADER4(4), TITLE(5), FOOTER(6), COMMENT(7), HEADER5(8), HEADER6(9), HTML(10), IMAGE(11);
private Integer value;
private ParagraphStyle(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
public static ParagraphStyle fromInteger(Integer value) {
switch (value) {
case 0:
return TEXT;
case 1:
return HEADER1;
case 2:
return HEADER2;
case 3:
return HEADER3;
case 4:
return HEADER4;
case 5:
return TITLE;
case 6:
return FOOTER;
case 7:
return COMMENT;
case 8:
return HEADER5;
case 9:
return HEADER6;
case 10:
return HTML;
case 11:
return IMAGE;
default:
throw new RuntimeException("Unsupported ParagraphStyle Code");
}
}
}

View File

@ -1,31 +0,0 @@
package eu.eudat.logic.utilities.documents.types;
/**
* Created by ikalyvas on 2/27/2018.
*/
public enum TextStyle {
ITALIC(0), BOLD(1), CAPS(2);
private Integer value;
private TextStyle(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
public static TextStyle fromInteger(Integer value) {
switch (value) {
case 0:
return ITALIC;
case 1:
return BOLD;
case 2:
return CAPS;
default:
throw new RuntimeException("Unsupported TextStyle Code");
}
}
}

View File

@ -1,289 +0,0 @@
package eu.eudat.logic.utilities.documents.word;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.math.BigInteger;
import java.util.*;
public class HtmlToWorldBuilder implements NodeVisitor {
private final Map<String, Boolean> properties = new LinkedHashMap<>();
private XWPFParagraph paragraph;
private XWPFRun run;
private Boolean dumpRun;
private final float indentation;
private Boolean isIdentationUsed;
private XWPFNumbering numbering;
private Queue<BigInteger> abstractNumId;
private BigInteger numberingLevel;
private XmlCursor cursor;
public static HtmlToWorldBuilder convertInTable(XWPFTableCell document, Document htmlDocument, float indentation) {
XWPFParagraph paragraph = document.addParagraph();
paragraph.setIndentFromLeft(Math.round(400 * indentation));
HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(paragraph, indentation, null);
NodeTraversor.traverse(htmlToWorldBuilder, htmlDocument);
return htmlToWorldBuilder;
}
public static HtmlToWorldBuilder convert(XWPFDocument document, Document htmlDocument, float indentation) {
XWPFParagraph paragraph = document.createParagraph();
paragraph.setIndentFromLeft(Math.round(400 * indentation));
HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(paragraph, indentation, null);
NodeTraversor.traverse(htmlToWorldBuilder, htmlDocument);
return htmlToWorldBuilder;
}
public HtmlToWorldBuilder(XWPFParagraph paragraph, float indentation, XmlCursor cursor) {
this.paragraph = paragraph;
this.run = this.paragraph.createRun();
this.dumpRun = false;
this.indentation = indentation;
this.isIdentationUsed = false;
this.run.setFontSize(11);
this.abstractNumId = new ArrayDeque<>();
this.numberingLevel = BigInteger.valueOf(-1);
this.setDefaultIndentation();
this.cursor = cursor;
}
@Override
public void head(Node node, int i) {
String name = node.nodeName();
if (name.equals("#text")) {
String text = ((TextNode)node).text();
this.run.setText(text);
this.dumpRun = true;
} else {
properties.put(name, true);
}
if (dumpRun) {
this.run = this.paragraph.createRun();
this.run.setFontSize(11);
this.dumpRun = false;
}
parseProperties(node);
properties.clear();
}
private void parseProperties(Node node) {
properties.entrySet().forEach(stringBooleanEntry -> {
switch (stringBooleanEntry.getKey()) {
case "i" :
case "em":
this.run.setItalic(stringBooleanEntry.getValue());
break;
case "b":
case "strong":
this.run.setBold(stringBooleanEntry.getValue());
break;
case "u":
case "ins":
this.run.setUnderline(stringBooleanEntry.getValue() ? UnderlinePatterns.SINGLE : UnderlinePatterns.NONE);
break;
case "small":
this.run.setFontSize(stringBooleanEntry.getValue() ? 8 : 11);
break;
case "del":
case "strike":
case "strikethrough":
case "s":
this.run.setStrikeThrough(stringBooleanEntry.getValue());
break;
case "mark":
this.run.setTextHighlightColor(stringBooleanEntry.getValue() ? STHighlightColor.YELLOW.toString() : STHighlightColor.NONE.toString());
break;
case "sub":
this.run.setSubscript(stringBooleanEntry.getValue() ? VerticalAlign.SUBSCRIPT : VerticalAlign.BASELINE);
break;
case "sup":
this.run.setSubscript(stringBooleanEntry.getValue() ? VerticalAlign.SUPERSCRIPT : VerticalAlign.BASELINE);
break;
case "div":
case "p":
if(this.cursor != null) {
this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor);
this.cursor = this.paragraph.getCTP().newCursor();
this.cursor.toNextSibling();
} else {
this.paragraph = this.paragraph.getDocument().createParagraph();
}
this.run = this.paragraph.createRun();
this.isIdentationUsed = false;
this.setDefaultIndentation();
if (stringBooleanEntry.getValue()) {
if (node.hasAttr("align")) {
String alignment = node.attr("align");
this.paragraph.setAlignment(ParagraphAlignment.valueOf(alignment.toUpperCase(Locale.ROOT)));
}
}
break;
case "blockquote":
if(this.cursor != null) {
this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor);
this.cursor = this.paragraph.getCTP().newCursor();
} else {
this.paragraph = this.paragraph.getDocument().createParagraph();
}
this.run = this.paragraph.createRun();
if (stringBooleanEntry.getValue()) {
this.paragraph.setIndentationLeft(400);
} else {
this.isIdentationUsed = false;
this.setDefaultIndentation();
}
break;
case "ul":
if (stringBooleanEntry.getValue()) {
createNumbering(STNumberFormat.BULLET);
} else {
if(this.cursor != null) {
this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor);
this.cursor = this.paragraph.getCTP().newCursor();
} else {
this.paragraph = this.paragraph.getDocument().createParagraph();
}
this.run = this.paragraph.createRun();
this.isIdentationUsed = false;
this.setDefaultIndentation();
this.numberingLevel = this.numberingLevel.subtract(BigInteger.ONE);
((ArrayDeque)this.abstractNumId).removeLast();
}
break;
case "ol":
if (stringBooleanEntry.getValue()) {
createNumbering(STNumberFormat.DECIMAL);
} else {
if(this.cursor != null) {
this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor);
this.cursor = this.paragraph.getCTP().newCursor();
} else {
this.paragraph = this.paragraph.getDocument().createParagraph();
}
this.run = this.paragraph.createRun();
this.isIdentationUsed = false;
this.setDefaultIndentation();
this.numberingLevel = this.numberingLevel.subtract(BigInteger.ONE);
((ArrayDeque)this.abstractNumId).removeLast();
}
break;
case "li":
if (stringBooleanEntry.getValue()) {
if(this.cursor != null) {
this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor);
this.cursor = this.paragraph.getCTP().newCursor();
} else {
this.paragraph = this.paragraph.getDocument().createParagraph();
}
// this.paragraph.setIndentationLeft(Math.round(indentation * 720) * (numberingLevel.intValue() + 1));
this.paragraph.setIndentFromLeft(Math.round(numberingLevel.intValue() * 400 + this.indentation*400));
this.run = this.paragraph.createRun();
this.paragraph.setNumID(((ArrayDeque<BigInteger>)abstractNumId).getLast());
}
break;
case "font":
if (stringBooleanEntry.getValue()) {
if (node.hasAttr("color")) {
this.run.setColor(node.attr("color").substring(1));
}
} else {
this.run.setColor("000000");
}
break;
case "a":
if (stringBooleanEntry.getValue()) {
if (node.hasAttr("href")) {
this.run = createHyperLinkRun(node.attr("href"));
this.run.setColor("0000FF");
this.run.setUnderline(UnderlinePatterns.SINGLE);
}
} else {
this.run = paragraph.createRun();
}
break;
case "br":
if (stringBooleanEntry.getValue()) {
this.run.addBreak();
}
break;
}
});
}
@Override
public void tail(Node node, int i) {
String name = node.nodeName();
properties.put(name, false);
parseProperties(node);
properties.clear();
}
//GK: This function creates one numbering.xml for the word document and adds a specific format.
//It imitates the numbering.xml that is usually generated by word editors like LibreOffice
private void createNumbering(STNumberFormat.Enum format) {
CTAbstractNum ctAbstractNum = CTAbstractNum.Factory.newInstance();
if (this.numbering == null) this.numbering = this.paragraph.getDocument().createNumbering();
BigInteger tempNumId = BigInteger.ONE;
boolean found = false;
while (!found) {
Object o = numbering.getAbstractNum(tempNumId);
found = (o == null);
if (!found) tempNumId = tempNumId.add(BigInteger.ONE);
}
ctAbstractNum.setAbstractNumId(tempNumId);
CTLvl ctLvl = ctAbstractNum.addNewLvl();
this.numberingLevel = numberingLevel.add(BigInteger.ONE);
ctLvl.setIlvl(numberingLevel);
ctLvl.addNewNumFmt().setVal(format);
ctLvl.addNewStart().setVal(BigInteger.ONE);
if (format == STNumberFormat.BULLET) {
ctLvl.addNewLvlJc().setVal(STJc.LEFT);
ctLvl.addNewLvlText().setVal("\u2022");
ctLvl.addNewRPr(); //Set the Symbol font
CTFonts f = ctLvl.getRPr().addNewRFonts();
f.setAscii("Symbol");
f.setHAnsi("Symbol");
f.setCs("Symbol");
f.setHint(STHint.DEFAULT);
} else {
ctLvl.addNewLvlText().setVal("%1.");
}
XWPFAbstractNum xwpfAbstractNum = new XWPFAbstractNum(ctAbstractNum);
this.abstractNumId.add(this.numbering.addAbstractNum(xwpfAbstractNum));
this.numbering.addNum(((ArrayDeque<BigInteger>)abstractNumId).getLast());
}
private XWPFHyperlinkRun createHyperLinkRun(String uri) {
String rId = this.paragraph.getDocument().getPackagePart().addExternalRelationship(uri, XWPFRelation.HYPERLINK.getRelation()).getId();
CTHyperlink cthyperLink=paragraph.getCTP().addNewHyperlink();
cthyperLink.setId(rId);
cthyperLink.addNewR();
return new XWPFHyperlinkRun(
cthyperLink,
cthyperLink.getRArray(0),
paragraph
);
}
private void setDefaultIndentation() {
if (!isIdentationUsed) {
// this.paragraph.setIndentationLeft(Math.round(indentation * 720.0F));
this.paragraph.setIndentFromLeft(Math.round(indentation * 400));
this.isIdentationUsed = true;
}
}
public XWPFParagraph getParagraph() {
return paragraph;
}
}

View File

@ -1,63 +0,0 @@
package eu.eudat.logic.utilities.documents.word;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.UUID;
public class XWPFHtmlDocument extends POIXMLDocumentPart {
private String html;
private String id;
public XWPFHtmlDocument(PackagePart pkg, String id) {
super(pkg);
this.html = "<!DOCTYPE html><html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"><style></style><title>HTML import</title></head><body><p></p></body>";
this.id = id;
}
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = this.html.replace("<p></p>", html);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
protected void commit() throws IOException {
PackagePart packagePart = getPackagePart();
OutputStream outputStream = packagePart.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(html);
writer.close();
outputStream.close();
}
public static XWPFHtmlDocument addHtmlDocument(XWPFDocument document) throws InvalidFormatException {
OPCPackage oPCPackage = document.getPackage();
String id = UUID.randomUUID().toString();
PackagePartName partName = PackagingURIHelper.createPartName("/word/" + id + ".html");
PackagePart part = oPCPackage.createPart(partName, "text/html");
XWPFHtmlDocument xWPFHtmlDocument = new XWPFHtmlDocument(part, id);
document.addRelation(xWPFHtmlDocument.getId(), new XWPFHtmlRelation(), xWPFHtmlDocument);
return xWPFHtmlDocument;
}
}

View File

@ -1,11 +0,0 @@
package eu.eudat.logic.utilities.documents.word;
import org.apache.poi.ooxml.POIXMLRelation;
public class XWPFHtmlRelation extends POIXMLRelation {
public XWPFHtmlRelation() {
super("text/html",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk",
"/word/htmlDoc#.html");
}
}

View File

@ -1,152 +0,0 @@
package eu.eudat.logic.utilities.documents.xml;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.xml.XmlBuilder;
import eu.eudat.commons.types.descriptiontemplate.fielddata.ExternalDatasetDataEntity;
import eu.eudat.models.data.user.components.datasetprofile.Field;
import eu.eudat.models.data.user.components.datasetprofile.FieldSet;
import eu.eudat.models.data.user.components.datasetprofile.Section;
import eu.eudat.models.data.user.composite.DatasetProfilePage;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import org.springframework.core.env.Environment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class ExportXmlBuilder {
public File build(PagedDatasetProfile pagedDatasetProfile, UUID datasetProfileId, VisibilityRuleService visibilityRuleService, Environment environment) throws IOException {
File xmlFile = new File(environment.getProperty("temp.temp") + UUID.randomUUID() + ".xml");
BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true));
Document xmlDoc = XmlBuilder.getDocument();
Element root = xmlDoc.createElement("root");
Element datasetProfile = xmlDoc.createElement("datasetProfileId");
datasetProfile.setTextContent(datasetProfileId.toString());
root.appendChild(datasetProfile);
root.appendChild(createPages(pagedDatasetProfile.getPages(), visibilityRuleService, xmlDoc));
xmlDoc.appendChild(root);
String xml = XmlBuilder.generateXml(xmlDoc);
writer.write(xml);
writer.close();
return xmlFile;
}
public Element createPages(List<DatasetProfilePage> datasetProfilePages, VisibilityRuleService visibilityRuleService, Document element) {
Element pages = element.createElement("pages");
datasetProfilePages.forEach(item -> {
Element page = element.createElement("page");
page.appendChild(createSections(item.getSections(), visibilityRuleService, element));
pages.appendChild(page);
});
return pages;
}
private Element createSections(List<Section> sections, VisibilityRuleService visibilityRuleService, Document element) {
Element elementSections = element.createElement("sections");
sections.forEach(section -> {
Element elementSection = element.createElement("section");
if (visibilityRuleService.isElementVisible(section.getId())) {
elementSection.appendChild(createSections(section.getSections(), visibilityRuleService, element));
elementSection.appendChild(createCompositeFields(section.getCompositeFields(), visibilityRuleService, element));
elementSections.appendChild(elementSection);
}
});
return elementSections;
}
private Element createCompositeFields(List<FieldSet> compositeFields, VisibilityRuleService visibilityRuleService, Document element) {
Element elementComposites = element.createElement("composite-fields");
compositeFields.forEach(compositeField -> {
if (visibilityRuleService.isElementVisible(compositeField.getId()) && hasVisibleFields(compositeField, visibilityRuleService)) {
Element composite = element.createElement("composite-field");
composite.setAttribute("id", compositeField.getId());
if (compositeField.getTitle() != null && !compositeField.getTitle().isEmpty()) {
Element title = element.createElement("title");
title.setTextContent(compositeField.getTitle());
composite.appendChild(title);
}
if (compositeField.getDescription() != null && !compositeField.getDescription().isEmpty()) {
Element title = element.createElement("description");
title.setTextContent(compositeField.getDescription());
composite.appendChild(title);
}
composite.appendChild(createFields(compositeField.getFields(), visibilityRuleService, element));
if(compositeField.getHasCommentField()){
Element comment = element.createElement("comment");
comment.setTextContent(compositeField.getCommentFieldValue());
composite.appendChild(comment);
}
elementComposites.appendChild(composite);
}
});
return elementComposites;
}
private Element createFields(List<Field> fields, VisibilityRuleService visibilityRuleService, Document element) {
Element elementFields = element.createElement("fields");
fields.forEach(field -> {
if (visibilityRuleService.isElementVisible(field.getId())) {
Element elementField = element.createElement("field");
elementField.setAttribute("id", field.getId());
if (field.getViewStyle().getFieldType().equals("externalDatasets")) {
elementField.setAttribute("type", ((ExternalDatasetDataEntity)field.getData()).getType().getValue());
}
if (field.getValue() != null) {
Element valueField = element.createElement("value");
ObjectMapper mapper = new ObjectMapper();
try {
List<Map<String, Object>> jsonArray = mapper.readValue(field.getValue().toString(), List.class);
// JSONArray jsonArray = new JSONArray(field.getValue().toString());
StringBuilder sb = new StringBuilder();
boolean firstTime = true;
for (Map<String, Object> jsonElement: jsonArray) {
if (!firstTime) {
sb.append(", ");
}
sb.append(jsonElement.get("label") != null ? jsonElement.get("label") : jsonElement.get("name"));
firstTime = false;
}
/*for (int i = 0; i < jsonArray.length(); i++) {
sb.append(jsonArray.getJSONObject(i).get("label").toString());
if (i != jsonArray.length() - 1) sb.append(", ");
}*/
valueField.setTextContent(sb.toString());
} catch (IOException ex) {
try {
Map<String, Object> jsonElement = mapper.readValue(field.getValue().toString(), Map.class);
valueField.setTextContent((jsonElement.get("label") != null ? jsonElement.get("label").toString() : jsonElement.get("name") != null ? jsonElement.get("name").toString() : ""));
} catch (IOException e) {
try {
valueField.setTextContent(DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(Instant.parse(field.getValue().toString())));
} catch (Exception exc) {
valueField.setTextContent(field.getValue().toString());
}
}
}
elementField.appendChild(valueField);
}
elementFields.appendChild(elementField);
}
});
return elementFields;
}
private boolean hasVisibleFields(FieldSet compositeFields, VisibilityRuleService visibilityRuleService) {
return compositeFields.getFields().stream().anyMatch(field -> visibilityRuleService.isElementVisible(field.getId()));
}
}

View File

@ -1,371 +0,0 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml;
import eu.eudat.commons.types.descriptiontemplate.fielddata.*;
import eu.eudat.models.data.admin.components.datasetprofile.Page;
import eu.eudat.models.data.user.components.datasetprofile.Field;
import eu.eudat.models.data.user.components.datasetprofile.FieldSet;
import eu.eudat.models.data.user.components.datasetprofile.Section;
import eu.eudat.logic.xml.XmlBuilder;
import org.springframework.core.env.Environment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
public class ExportXmlBuilderDatasetProfile {
public File build(eu.eudat.models.data.user.composite.DatasetProfile datasetProfile, Environment environment) throws IOException {
File xmlFile = new File(environment.getProperty("temp.temp") + UUID.randomUUID() + ".xml");
BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true));
Document xmlDoc = XmlBuilder.getDocument();
// Element root = xmlDoc.createElement("root");
// root.appendChild(createPages(datasetProfile.getPages(), datasetProfile.getSections(), xmlDoc));
xmlDoc.appendChild(createPages(datasetProfile.getPages(), datasetProfile.getSections(), xmlDoc));
Element pages = (Element)xmlDoc.getFirstChild();
pages.setAttribute("description", datasetProfile.getDescription());
pages.setAttribute("language", datasetProfile.getLanguage());
pages.setAttribute("type", datasetProfile.getType());
String xml = XmlBuilder.generateXml(xmlDoc);
writer.write(xml);
writer.close();
return xmlFile;
}
public Element createPages(List<Page> datasetProfilePages, List<Section> sections, Document element) {
Element pages = element.createElement("pages");
datasetProfilePages.forEach(item -> {
Element page = element.createElement("page");
page.setAttribute("id", "" + item.getId());
page.setAttribute("ordinal", "" + item.getOrdinal());
page.setAttribute("title", "" + item.getTitle());
sections.forEach(sectionFromLis -> {
if (sectionFromLis.getPage().equals(item.getId())) {
Element elementSections = element.createElement("sections");
page.appendChild(createSections(sectionFromLis, element, elementSections));
}
});
pages.appendChild(page);
});
return pages;
}
public Element createSections(Section sections, Document element, Element elementSections) {
// if (sections.getSections() != null) {
sections.getSections().forEach(sectionFor -> {
Element elementSectionsChild = element.createElement("section");
elementSections.appendChild(createSections(sectionFor, element, elementSectionsChild));
});
// }
elementSections.setAttribute("defaultVisibility", "" + sections.getDefaultVisibility());
elementSections.setAttribute("id", "" + sections.getId());
elementSections.setAttribute("ordinal", "" + sections.getOrdinal());
elementSections.setAttribute("page", "" + sections.getPage());
elementSections.setAttribute("page", "" + sections.getPage());
if (sections.getCompositeFields() != null) {
elementSections.appendChild(createFieldSet(sections.getCompositeFields(), element));
}
if (sections.getNumbering() != null) {
Element numbering = element.createElement("numbering");
numbering.setTextContent(sections.getNumbering());
elementSections.appendChild(numbering);
}
if (sections.getDescription() != null) {
Element description = element.createElement("description");
description.setTextContent(sections.getDescription());
elementSections.appendChild(description);
}
if (sections.getTitle() != null) {
Element title = element.createElement("title");
title.setTextContent(sections.getTitle());
elementSections.appendChild(title);
}
return elementSections;
}
public Element createFieldSet(List<FieldSet> fieldSet, Document element) {
Element elementFieldSets = element.createElement("field-Sets");
fieldSet.forEach(field -> {
Element composite = element.createElement("field-Set");
composite.setAttribute("id", field.getId());
composite.setAttribute("ordinal", "" + field.getOrdinal());
if (field.getNumbering() != null) {
Element numbering = element.createElement("numbering");
numbering.setTextContent(field.getNumbering());
composite.appendChild(numbering);
}
Element commentField = element.createElement("CommentField");
commentField.setTextContent("" + field.getHasCommentField());
composite.appendChild(commentField);
composite.appendChild(createFields(field.getFields(), element));
if (field.getMultiplicity() != null) {
Element multiplicity = element.createElement("multiplicity");
multiplicity.setAttribute("max", "" + field.getMultiplicity().getMax());
multiplicity.setAttribute("min", "" + field.getMultiplicity().getMin());
multiplicity.setAttribute("placeholder", field.getMultiplicity().getPlaceholder());
multiplicity.setAttribute("tableView", String.valueOf(field.getMultiplicity().getTableView()));
composite.appendChild(multiplicity);
}
if (field.getTitle() != null && !field.getTitle().isEmpty()) {
Element title = element.createElement("title");
title.setTextContent(field.getTitle());
composite.appendChild(title);
}
if (field.getDescription() != null && !field.getDescription().isEmpty()) {
Element title = element.createElement("description");
title.setTextContent(field.getDescription());
composite.appendChild(title);
}
if (field.getExtendedDescription() != null && !field.getExtendedDescription().isEmpty()) {
Element extendedDescription = element.createElement("extendedDescription");
extendedDescription.setTextContent(field.getExtendedDescription());
composite.appendChild(extendedDescription);
}
if (field.getAdditionalInformation() != null && !field.getAdditionalInformation().isEmpty()) {
Element additionalInformation = element.createElement("additionalInformation");
additionalInformation.setTextContent(field.getAdditionalInformation());
composite.appendChild(additionalInformation);
}
elementFieldSets.appendChild(composite);
});
return elementFieldSets;
}
public Element createFields(List<Field> fields, Document element) {
Element elementFields = element.createElement("fields");
fields.forEach(field -> {
Element elementField = element.createElement("field");
elementField.setAttribute("id", field.getId());
elementField.setAttribute("ordinal", "" + field.getOrdinal());
if (field.getNumbering() != null) {
Element numbering = element.createElement("numbering");
numbering.setTextContent(field.getNumbering());
elementField.appendChild(numbering);
}
if (field.getSchematics() != null) {
Element schematics = element.createElement("schematics");
field.getSchematics().forEach(schematic -> {
Element schematicChild = element.createElement("schematic");
schematicChild.setTextContent(schematic);
schematics.appendChild(schematicChild);
});
elementField.appendChild(schematics);
}
if (field.getValidations() != null) {
Element validations = element.createElement("validations");
field.getValidations().forEach(validation -> {
Element validationChild = element.createElement("validation");
validationChild.setAttribute("type", "" + validation);
validations.appendChild(validationChild);
});
elementField.appendChild(validations);
}
if (field.getDefaultValue() != null) {
Element defaultValue = element.createElement("defaultValue");
defaultValue.setAttribute("type", field.getDefaultValue().getType());
defaultValue.setAttribute("value", field.getDefaultValue().getValue());
elementField.appendChild(defaultValue);
}
if (field.getVisible() != null) {
Element visible = element.createElement("visible");
visible.setAttribute("style", "" + field.getVisible().getStyle());
field.getVisible().getRules().forEach(rule -> {
Element ruleChild = element.createElement("rule");
ruleChild.setAttribute("target", "" + rule.getTarget());
Element ruleChildValue = element.createElement("value");
ruleChildValue.setTextContent(rule.getValue());
ruleChild.appendChild(ruleChildValue);
visible.appendChild(ruleChild);
});
elementField.appendChild(visible);
}
if (field.getViewStyle() != null) {
Element viewStyle = element.createElement("viewStyle");
viewStyle.setAttribute("cssClass", field.getViewStyle().getCssClass());
viewStyle.setAttribute("renderStyle", field.getViewStyle().getFieldType().getValue());
elementField.appendChild(viewStyle);
}
if (field.getData() != null) {
Element dataOut = element.createElement("data");
switch (field.getViewStyle().getFieldType()) {
case SELECT:
case EXTERNAL_SELECT:
// ComboBoxDataEntity comboBoxDataEntityObject = (ComboBoxDataEntity) field.getData();
// if (comboBoxDataEntityObject.getFieldType().equals("wordlist")) {
// SelectDataEntity selectDataEntityObject = (SelectDataEntity) field.getData();
// dataOut.setAttribute("label", selectDataEntityObject.getLabel());
// dataOut.setAttribute("type", selectDataEntityObject.getFieldType().getValue());
// dataOut.setAttribute("multiList", selectDataEntityObject.getMultiList().toString());
// Element options = element.createElement("options");
// selectDataEntityObject.getOptions().forEach(optionChildFor -> {
// Element optionChild = element.createElement("option");
// optionChild.setAttribute("label", optionChildFor.getLabel());
// optionChild.setAttribute("value", optionChildFor.getValue());
// options.appendChild(optionChild);
// });
// dataOut.appendChild(options);
// } else if (comboBoxDataEntityObject.getFieldType().equals("autocomplete")) {
// ExternalSelectDataEntity externalSelectDataEntityObject = (ExternalSelectDataEntity) field.getData();
// dataOut.setAttribute("label", externalSelectDataEntityObject.getLabel());
// dataOut.setAttribute("type", externalSelectDataEntityObject.getFieldType().getValue());
// dataOut.setAttribute("multiAutoComplete", externalSelectDataEntityObject.getMultipleSelect().toString());
// for (ExternalSelectDataEntity.ExternalSelectSourceEntity singleData: externalSelectDataEntityObject.getSources()) {
// Element singleItem = element.createElement("autocompleteSingle");
// singleItem.setAttribute("optionsRoot", singleData.getOptionsRoot());
// singleItem.setAttribute("url", singleData.getUrl());
// singleItem.setAttribute("autoCompleteType", Integer.toString(singleData.getAutocompleteType().getValue()));
// if (singleData.getSourceBinding() != null) {
// Element optionChild = element.createElement("option");
// optionChild.setAttribute("label", singleData.getSourceBinding().getLabel());
// optionChild.setAttribute("value", singleData.getSourceBinding().getValue());
// singleItem.appendChild(optionChild);
// }
// dataOut.appendChild(singleItem);
// }
// }
break;
case UPLOAD:
UploadDataEntity uploadEntityObject = (UploadDataEntity) field.getData();
dataOut.setAttribute("label", uploadEntityObject.getLabel());
dataOut.setAttribute("maxFileSizeInMB", String.valueOf(uploadEntityObject.getMaxFileSizeInMB()));
Element types = element.createElement("types");
uploadEntityObject.getTypes().forEach(type -> {
Element optionChild = element.createElement("option");
optionChild.setAttribute("label", type.getLabel());
optionChild.setAttribute("value", type.getValue());
types.appendChild(optionChild);
});
dataOut.appendChild(types);
break;
case BOOLEAN_DECISION:
LabelAndMultiplicityDataEntity booleanDecisionDataEntityObject = (LabelAndMultiplicityDataEntity) field.getData();
dataOut.setAttribute("label", booleanDecisionDataEntityObject.getLabel());
break;
case RADIO_BOX:
RadioBoxDataEntity radioBoxDataEntityObject = (RadioBoxDataEntity) field.getData();
dataOut.setAttribute("label", radioBoxDataEntityObject.getLabel());
Element options = element.createElement("options");
radioBoxDataEntityObject.getOptions().forEach(optionChildFor -> {
Element optionChild = element.createElement("option");
optionChild.setAttribute("label", optionChildFor.getLabel());
optionChild.setAttribute("value", optionChildFor.getValue());
options.appendChild(optionChild);
});
dataOut.appendChild(options);
break;
case CHECK_BOX:
case FREE_TEXT:
case TEXT_AREA:
case RICH_TEXT_AREA:
case DATE_PICKER:
case DATASET_IDENTIFIER:
case CURRENCY:
case TAGS:
BaseFieldDataEntity baseFieldDataObject = (BaseFieldDataEntity) field.getData();
dataOut.setAttribute("label", baseFieldDataObject.getLabel());
break;
case INTERNAL_DMP_ENTRIES_RESEARCHERS:
case INTERNAL_ENTRIES_DESCRIPTIONS:
case INTERNAL_DMP_ENTRIES_DMPS:
// InternalDmpBaseDataEntity internalDmpEntitiesData = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", internalDmpEntitiesData.getLabel());
// dataOut.setAttribute("type", internalDmpEntitiesData.getFieldType().getValue());
// switch (internalDmpEntitiesData.getFieldType()) {
// case INTERNAL_DMP_ENTRIES_RESEARCHERS:
// InternalDmpBaseDataEntity researchersAutoCompleteData = (InternalDmpBaseDataEntity) internalDmpEntitiesData;
// dataOut.setAttribute("multiAutocomplete", researchersAutoCompleteData.getMultipleSelect().toString());
// break;
// case INTERNAL_DMP_ENTRIES_DATASETS:
// InternalDmpBaseDataEntity datasetAutoCompleteDataEntity = (InternalDmpBaseDataEntity) internalDmpEntitiesData;
// dataOut.setAttribute("multiAutocomplete", datasetAutoCompleteDataEntity.getMultipleSelect().toString());
// break;
// case INTERNAL_DMP_ENTRIES_DMPS:
// InternalDmpBaseDataEntity dmpAutoCompleteDataEntity = (InternalDmpBaseDataEntity) internalDmpEntitiesData;
// dataOut.setAttribute("multiAutocomplete", dmpAutoCompleteDataEntity.getMultipleSelect().toString());
// break;
// }
break;
case EXTERNAL_DATASETS:
ExternalDatasetDataEntity externalDatasetDataEntity = (ExternalDatasetDataEntity) field.getData();
dataOut.setAttribute("label", externalDatasetDataEntity.getLabel());
dataOut.setAttribute("multiAutocomplete", externalDatasetDataEntity.getMultipleSelect().toString());
dataOut.setAttribute("type", externalDatasetDataEntity.getType().getValue());
break;
case DATA_REPOSITORIES:
case JOURNAL_REPOSITORIES:
// case PUB_REPOSITORIES:
// InternalDmpBaseDataEntity dataRepositoryDataEntity = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", dataRepositoryDataEntity.getLabel());
// dataOut.setAttribute("multiAutocomplete", dataRepositoryDataEntity.getMultipleSelect().toString());
// break;
// case TAXONOMIES:
// InternalDmpBaseDataEntity taxonomyDataEntity = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", taxonomyDataEntity.getLabel());
// dataOut.setAttribute("multiAutocomplete", taxonomyDataEntity.getMultipleSelect().toString());
// break;
// case LICENSES:
// InternalDmpBaseDataEntity licensesData = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", licensesData.getLabel());
// dataOut.setAttribute("multiAutocomplete", licensesData.getMultipleSelect().toString());
// break;
// case PUBLICATIONS:
// InternalDmpBaseDataEntity publicationDataEntity = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", publicationDataEntity.getLabel());
// dataOut.setAttribute("multiAutocomplete", publicationDataEntity.getMultipleSelect().toString());
// break;
// case ORGANIZATIONS:
// InternalDmpBaseDataEntity organizationDataEntity = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", organizationDataEntity.getLabel());
// dataOut.setAttribute("multiAutocomplete", organizationDataEntity.getMultipleSelect().toString());
// break;
// case RESEARCHERS:
// InternalDmpBaseDataEntity researcherDataEntity = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", researcherDataEntity.getLabel());
// dataOut.setAttribute("multiAutocomplete", researcherDataEntity.getMultipleSelect().toString());
// break;
// case REGISTRIES:
// InternalDmpBaseDataEntity registriesEntity = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", registriesEntity.getLabel());
// dataOut.setAttribute("multiAutocomplete", registriesEntity.getMultipleSelect().toString());
// break;
// case SERVICES:
// InternalDmpBaseDataEntity serviceDataEntity = (InternalDmpBaseDataEntity) field.getData();
// dataOut.setAttribute("label", serviceDataEntity.getLabel());
// dataOut.setAttribute("multiAutocomplete", serviceDataEntity.getMultipleSelect().toString());
// break;
}
elementField.appendChild(dataOut);
}
elementFields.appendChild(elementField);
});
return elementFields;
}
}

View File

@ -1,29 +0,0 @@
package eu.eudat.logic.utilities.documents.xml.datasetProfileXml;
import eu.eudat.commons.types.descriptiontemplate.importexport.DescriptionTemplateImportExport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import java.io.*;
public class ImportXmlBuilderDatasetProfile {
private static final Logger logger = LoggerFactory.getLogger(ImportXmlBuilderDatasetProfile.class);
public DescriptionTemplateImportExport build(File xmlFile) throws IOException {
DescriptionTemplateImportExport descriptionTemplateImportXml = new DescriptionTemplateImportExport();
JAXBContext jaxbContext = null;
try {
jaxbContext = JAXBContext.newInstance(DescriptionTemplateImportExport.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
descriptionTemplateImportXml = (DescriptionTemplateImportExport) unmarshaller.unmarshal(xmlFile);
} catch (JAXBException e) {
logger.error(e.getMessage(), e);
}
return descriptionTemplateImportXml;
}
}

View File

@ -1,25 +0,0 @@
package eu.eudat.logic.utilities.helpers;
import java.util.List;
public class LabelBuilder {
private static <T extends LabelGenerator> String generateLabel(List<T> items) {
String label = "";
for (T item : items) {
if (items.indexOf(item) == 3) {
label += "...";
break;
}
if (items.indexOf(item) > 1) {
label += ", ";
}
label += item.generateLabel();
}
return label;
}
public static <T extends LabelGenerator> String getLabel(List<T> items) {
return generateLabel(items);
}
}

View File

@ -1,6 +0,0 @@
package eu.eudat.logic.utilities.helpers;
public interface LabelGenerator {
String generateLabel();
}

View File

@ -1,17 +0,0 @@
package eu.eudat.logic.utilities.helpers;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
@Component
public class ListHelper {
public <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}

View File

@ -1,46 +0,0 @@
package eu.eudat.logic.utilities.helpers;
import eu.eudat.commons.types.descriptiontemplate.RuleEntity;
import eu.eudat.commons.types.descriptiontemplate.SectionEntity;
import eu.eudat.models.data.user.components.commons.Rule;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class ModelBuilderCollector {
/**
* @param sectionEntities
* @return
*/
public static List<Rule> collectRules(List<SectionEntity> sectionEntities) {
List<Rule> rules = new LinkedList();
for (SectionEntity sectionEntity : sectionEntities) {
if (!sectionEntity.getSections().isEmpty()) {
rules.addAll(collectRules(sectionEntity.getSections()));
}
rules.addAll(
sectionEntity.getFieldSets().stream()
.map(fieldset -> fieldset.getFields())
.flatMap(List::stream)
.map(field -> getRulesFromField(field.getId(), field.getVisibilityRules()))
.flatMap(List::stream)
.collect(Collectors.toList()));
}
return rules;
}
private static List<Rule> getRulesFromField(String id, List<RuleEntity> rules) {
List<Rule> modelRules = new LinkedList();
for (RuleEntity rule : rules) {
Rule modelRule = new Rule().fromDefinitionRule(rule);
modelRule.setSourceField(id);
modelRules.add(modelRule);
}
return modelRules;
}
}

View File

@ -1,21 +0,0 @@
package eu.eudat.logic.utilities.helpers;
public class MyStringUtils {
public static int getFirstDifference(String s1, String s2) {
char[] s1ar = s1.toCharArray();
char[] s2ar = s2.toCharArray();
for(int i = 0; i < s1ar.length; i++) {
if (s2ar.length > i) {
if (s1ar[i] != s2ar[i]) {
return i;
}
} else {
return i;
}
}
return -1;
}
}

View File

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

View File

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

View File

@ -1,8 +0,0 @@
package eu.eudat.logic.utilities.interfaces;
/**
* Created by ikalyvas on 2/5/2018.
*/
public interface Cloneable<T> {
T clone();
}

View File

@ -1,9 +0,0 @@
package eu.eudat.logic.utilities.interfaces;
public interface ViewStyleDefinition<T> {
T toDatabaseDefinition(T item);
void fromDatabaseDefinition(T item);
}

View File

@ -1,13 +0,0 @@
package eu.eudat.logic.utilities.json;
public class JavaToJson {
public static String objectStringToJson(String object) {
String result = object.replaceAll("=", "\":\"")
.replaceAll("\\{", "{\"")
.replaceAll(", ", "\", \"")
.replaceAll("}", "\"}" )
.replaceAll("}\", \"\\{", "}, {");
return result;
}
}

View File

@ -1,81 +0,0 @@
package eu.eudat.logic.utilities.json;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class JsonSearcher {
public static List<JsonNode> findNodes(JsonNode root, String key, String value) {
return findNodes(root, key, value, false);
}
public static List<JsonNode> findNodes(JsonNode root, String key, String value, boolean parent) {
List<JsonNode> nodes = new ArrayList<>();
for (Iterator<JsonNode> it = root.elements(); it.hasNext(); ) {
JsonNode node = it.next();
int found = 0;
for (Iterator<String> iter = node.fieldNames(); iter.hasNext(); ) {
String fieldName = iter.next();
if (fieldName.equals(key)) {
if (node.get(fieldName).asText().equals(value) || node.get(fieldName).asText().startsWith(value)) {
if (parent) {
nodes.add(root);
} else {
nodes.add(node);
}
found++;
}
else if(node.get(fieldName).isArray()){
for(JsonNode item: node.get(fieldName)){
if(item.asText().equals(value) || item.asText().startsWith(value)){
if (parent) {
nodes.add(root);
} else {
nodes.add(node);
}
found++;
}
}
}
}
}
if (found == 0) {
nodes.addAll(findNodes(node, key, value, parent));
}
}
return nodes;
}
public static List<String> getParentValues(JsonNode root, String childValue, String key) {
List<String> values = new LinkedList<>();
for (Iterator<JsonNode> it = root.elements(); it.hasNext(); ) {
JsonNode node = it.next();
int found = 0;
for (Iterator<String> iter = node.fieldNames(); iter.hasNext(); ) {
String fieldName = iter.next();
if (fieldName.equals(key)) {
if (node.get(fieldName).asText().equals(childValue) || node.get(fieldName).asText().startsWith(childValue)) {
values.add(childValue);
found++;
}
}
}
if (found == 0) {
values.addAll(getParentValues(node, childValue, key));
if (!values.isEmpty() && node.has(key)) {
values.add(node.get(key).asText());
values.remove(childValue);
}
}
}
return values;
}
}

View File

@ -1,41 +0,0 @@
package eu.eudat.logic.utilities.json;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class MultiDateDeserializer extends StdDeserializer<Date> {
private static final List<String> DATE_FORMATS = Arrays.asList("yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.S");
public MultiDateDeserializer() {
super(Date.class);
}
protected MultiDateDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String text = p.getText();
for (String dateFormat: DATE_FORMATS) {
try {
return new SimpleDateFormat(dateFormat).parse(text);
} catch (ParseException ignored) {
}
}
throw new JsonParseException(p, "No supported Date format");
}
}

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