diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/model/AbstractAuditingEntity.java b/simulator-starter/src/main/java/org/citrusframework/simulator/model/AbstractAuditingEntity.java index ed3a6fffa..9a7f970fb 100644 --- a/simulator-starter/src/main/java/org/citrusframework/simulator/model/AbstractAuditingEntity.java +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/model/AbstractAuditingEntity.java @@ -69,5 +69,9 @@ public B lastModifiedDate(Instant lastModifiedDate) { } protected abstract E getEntity(); + + public E build() { + return getEntity(); + } } } diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/model/Message.java b/simulator-starter/src/main/java/org/citrusframework/simulator/model/Message.java index 3d0c509d9..637265789 100644 --- a/simulator-starter/src/main/java/org/citrusframework/simulator/model/Message.java +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/model/Message.java @@ -196,10 +196,6 @@ public static class MessageBuilder extends AuditingEntityBuilder i @NotNull @ManyToOne(optional = false) @JoinColumn(nullable = false) - @JsonIgnoreProperties(value = { "headers", "scenarioExecution" }, allowSetters = true) + @JsonIgnoreProperties(value = {"headers", "scenarioExecution"}, allowSetters = true) private Message message; public MessageHeader() { // Hibernate constructor } - public MessageHeader(String name, String value) { + MessageHeader(String name, String value) { this.name = name; this.value = value; } + public static MessageHeaderBuilder builder() { + return new MessageHeaderBuilder(); + } + public Long getHeaderId() { return headerId; } + void setHeaderId(Long headerId) { + this.headerId = headerId; + } + public String getName() { return name; } @@ -95,13 +104,55 @@ public void setMessage(Message message) { this.message = message; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof MessageHeader messageHeader) { + return headerId != null && headerId.equals(messageHeader.headerId); + } + return false; + } + + @Override + public int hashCode() { + // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ + return getClass().hashCode(); + } + @Override public String toString() { return "MessageHeader{" + - "headerId='" + getHeaderId() + "'" + - ", createdDate='" + getCreatedDate() + "'" + - ", name='" + getName() + "'" + - ", value='" + getValue() + "'" + - "}"; + "headerId='" + getHeaderId() + "'" + + ", createdDate='" + getCreatedDate() + "'" + + ", name='" + getName() + "'" + + ", value='" + getValue() + "'" + + "}"; + } + + public static class MessageHeaderBuilder extends AuditingEntityBuilder { + + private final MessageHeader messageHeader = new MessageHeader(); + + public MessageHeaderBuilder name(String name) { + messageHeader.setName(name); + return this; + } + + public MessageHeaderBuilder value(String value) { + messageHeader.setValue(value); + return this; + } + + public MessageHeaderBuilder message(Message message) { + messageHeader.setMessage(message); + return this; + } + + @Override + protected MessageHeader getEntity() { + return messageHeader; + } } } diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/model/TestParameter.java b/simulator-starter/src/main/java/org/citrusframework/simulator/model/TestParameter.java index cb401ca00..df845955f 100644 --- a/simulator-starter/src/main/java/org/citrusframework/simulator/model/TestParameter.java +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/model/TestParameter.java @@ -196,10 +196,6 @@ public static class TestParameterBuilder extends AuditingEntityBuilder, JpaSpecificationExecutor { + default Optional findOneWithEagerRelationships(Long id) { + return this.findOneWithToOneRelationships(id); + } + + default List findAllWithEagerRelationships() { + return this.findAllWithToOneRelationships(); + } + + default Page findAllWithEagerRelationships(Pageable pageable) { + return this.findAllWithToOneRelationships(pageable); + } + + @Query( + value = "select messageHeader from MessageHeader messageHeader left join fetch messageHeader.message", + countQuery = "select count(messageHeader) from MessageHeader messageHeader" + ) + Page findAllWithToOneRelationships(Pageable pageable); + + @Query("select messageHeader from MessageHeader messageHeader left join fetch messageHeader.message") + List findAllWithToOneRelationships(); + + @Query("select messageHeader from MessageHeader messageHeader left join fetch messageHeader.message where messageHeader.id =:id") + Optional findOneWithToOneRelationships(@Param("id") Long id); +} diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageHeaderQueryService.java b/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageHeaderQueryService.java new file mode 100644 index 000000000..b88ce0031 --- /dev/null +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageHeaderQueryService.java @@ -0,0 +1,107 @@ +package org.citrusframework.simulator.service; + +import jakarta.persistence.criteria.JoinType; +import org.citrusframework.simulator.model.MessageHeader; +import org.citrusframework.simulator.model.MessageHeader_; +import org.citrusframework.simulator.model.Message_; +import org.citrusframework.simulator.repository.MessageHeaderRepository; +import org.citrusframework.simulator.service.criteria.MessageHeaderCriteria; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * Service for executing complex queries for {@link MessageHeader} entities in the database. + * The main input is a {@link MessageHeaderCriteria} which gets converted to {@link Specification}, + * in a way that all the filters must apply. + * It returns a {@link List} of {@link MessageHeader} or a {@link Page} of {@link MessageHeader} which fulfills the criteria. + */ +@Service +@Transactional(readOnly = true) +public class MessageHeaderQueryService extends QueryService { + + private final Logger log = LoggerFactory.getLogger(MessageHeaderQueryService.class); + + private final MessageHeaderRepository messageHeaderRepository; + + public MessageHeaderQueryService(MessageHeaderRepository messageHeaderRepository) { + this.messageHeaderRepository = messageHeaderRepository; + } + + /** + * Return a {@link List} of {@link MessageHeader} which matches the criteria from the database. + * @param criteria The object which holds all the filters, which the entities should match. + * @return the matching entities. + */ + @Transactional(readOnly = true) + public List findByCriteria(MessageHeaderCriteria criteria) { + log.debug("find by criteria : {}", criteria); + final Specification specification = createSpecification(criteria); + return messageHeaderRepository.findAll(specification); + } + + /** + * Return a {@link Page} of {@link MessageHeader} which matches the criteria from the database. + * @param criteria The object which holds all the filters, which the entities should match. + * @param page The page, which should be returned. + * @return the matching entities. + */ + @Transactional(readOnly = true) + public Page findByCriteria(MessageHeaderCriteria criteria, Pageable page) { + log.debug("find by criteria : {}, page: {}", criteria, page); + final Specification specification = createSpecification(criteria); + return messageHeaderRepository.findAll(specification, page); + } + + /** + * Return the number of matching entities in the database. + * @param criteria The object which holds all the filters, which the entities should match. + * @return the number of matching entities. + */ + @Transactional(readOnly = true) + public long countByCriteria(MessageHeaderCriteria criteria) { + log.debug("count by criteria : {}", criteria); + final Specification specification = createSpecification(criteria); + return messageHeaderRepository.count(specification); + } + + /** + * Function to convert {@link MessageHeaderCriteria} to a {@link Specification} + * @param criteria The object which holds all the filters, which the entities should match. + * @return the matching {@link Specification} of the entity. + */ + protected Specification createSpecification(MessageHeaderCriteria criteria) { + Specification specification = Specification.where(null); + if (criteria != null) { + // This has to be called first, because the distinct method returns null + if (criteria.getDistinct() != null) { + specification = specification.and(distinct(criteria.getDistinct())); + } + if (criteria.getHeaderId() != null) { + specification = specification.and(buildRangeSpecification(criteria.getHeaderId(), MessageHeader_.headerId)); + } + if (criteria.getName() != null) { + specification = specification.and(buildStringSpecification(criteria.getName(), MessageHeader_.name)); + } + if (criteria.getValue() != null) { + specification = specification.and(buildStringSpecification(criteria.getValue(), MessageHeader_.value)); + } + if (criteria.getMessageId() != null) { + specification = + specification.and( + buildSpecification( + criteria.getMessageId(), + root -> root.join(MessageHeader_.message, JoinType.LEFT).get(Message_.messageId) + ) + ); + } + } + return specification; + } +} diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageHeaderService.java b/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageHeaderService.java new file mode 100644 index 000000000..8c9770639 --- /dev/null +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageHeaderService.java @@ -0,0 +1,59 @@ +package org.citrusframework.simulator.service; + +import org.citrusframework.simulator.model.MessageHeader; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.Optional; + +/** + * Service Interface for managing {@link MessageHeader}. + */ +public interface MessageHeaderService { + /** + * Save a messageHeader. + * + * @param messageHeader the entity to save. + * @return the persisted entity. + */ + MessageHeader save(MessageHeader messageHeader); + + /** + * Updates a messageHeader. + * + * @param messageHeader the entity to update. + * @return the persisted entity. + */ + MessageHeader update(MessageHeader messageHeader); + + /** + * Get all the messageHeaders. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page findAll(Pageable pageable); + + /** + * Get all the messageHeaders with eager load of many-to-many relationships. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page findAllWithEagerRelationships(Pageable pageable); + + /** + * Get the "id" messageHeader. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" messageHeader. + * + * @param id the id of the entity. + */ + void delete(Long id); +} diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageQueryService.java b/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageQueryService.java index 14caed8d3..01f3b891f 100644 --- a/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageQueryService.java +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/service/MessageQueryService.java @@ -1,7 +1,5 @@ package org.citrusframework.simulator.service; -import jakarta.persistence.criteria.Expression; -import jakarta.persistence.criteria.Root; import org.citrusframework.simulator.model.Message; import org.citrusframework.simulator.model.Message_; import org.citrusframework.simulator.repository.MessageRepository; @@ -15,7 +13,6 @@ import org.springframework.transaction.annotation.Transactional; import java.util.List; -import java.util.function.Function; /** * Service for executing complex queries for {@link Message} entities in the database. diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/service/criteria/MessageHeaderCriteria.java b/simulator-starter/src/main/java/org/citrusframework/simulator/service/criteria/MessageHeaderCriteria.java new file mode 100644 index 000000000..63ee9df72 --- /dev/null +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/service/criteria/MessageHeaderCriteria.java @@ -0,0 +1,155 @@ +package org.citrusframework.simulator.service.criteria; + +import org.citrusframework.simulator.service.filter.LongFilter; +import org.citrusframework.simulator.service.filter.StringFilter; +import org.springdoc.core.annotations.ParameterObject; + +import java.io.Serializable; +import java.util.Objects; + +/** + * Criteria class for the {@link org.citrusframework.simulator.model.MessageHeader} entity. This class is used + * in {@link org.citrusframework.simulator.web.rest.MessageHeaderResource} to receive all the possible filtering options from + * the Http GET request parameters. + *

+ * For example the following could be a valid request: + * {@code /message-headers?id.greaterThan=5&attr1.contains=something&attr2.specified=false} + *

+ * As Spring is unable to properly convert the types, unless + * specific {@link org.citrusframework.simulator.service.filter.Filter} class are used, we need to use fix type specific + * filters. + */ +@ParameterObject +@SuppressWarnings("common-java:DuplicatedBlocks") +public class MessageHeaderCriteria implements Serializable, Criteria { + + private static final long serialVersionUID = 1L; + + private LongFilter headerId; + + private StringFilter name; + + private StringFilter value; + + private LongFilter messageId; + + private Boolean distinct; + + public MessageHeaderCriteria() {} + + public MessageHeaderCriteria(MessageHeaderCriteria other) { + this.headerId = other.headerId == null ? null : other.headerId.copy(); + this.name = other.name == null ? null : other.name.copy(); + this.value = other.value == null ? null : other.value.copy(); + this.messageId = other.messageId == null ? null : other.messageId.copy(); + this.distinct = other.distinct; + } + + @Override + public MessageHeaderCriteria copy() { + return new MessageHeaderCriteria(this); + } + + public LongFilter getHeaderId() { + return headerId; + } + + public LongFilter id() { + if (headerId == null) { + headerId = new LongFilter(); + } + return headerId; + } + + public void setHeaderId(LongFilter headerId) { + this.headerId = headerId; + } + + public StringFilter getName() { + return name; + } + + public StringFilter name() { + if (name == null) { + name = new StringFilter(); + } + return name; + } + + public void setName(StringFilter name) { + this.name = name; + } + + public StringFilter getValue() { + return value; + } + + public StringFilter value() { + if (value == null) { + value = new StringFilter(); + } + return value; + } + + public void setValue(StringFilter value) { + this.value = value; + } + + public LongFilter getMessageId() { + return messageId; + } + + public LongFilter messageId() { + if (messageId == null) { + messageId = new LongFilter(); + } + return messageId; + } + + public void setMessageId(LongFilter messageId) { + this.messageId = messageId; + } + + public Boolean getDistinct() { + return distinct; + } + + public void setDistinct(Boolean distinct) { + this.distinct = distinct; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final MessageHeaderCriteria that = (MessageHeaderCriteria) o; + return ( + Objects.equals(headerId, that.headerId) && + Objects.equals(name, that.name) && + Objects.equals(value, that.value) && + Objects.equals(messageId, that.messageId) && + Objects.equals(distinct, that.distinct) + ); + } + + @Override + public int hashCode() { + return Objects.hash(headerId, name, value, messageId, distinct); + } + + // prettier-ignore + @Override + public String toString() { + return "MessageHeaderCriteria{" + + (headerId != null ? "id=" + headerId + ", " : "") + + (name != null ? "name=" + name + ", " : "") + + (value != null ? "value=" + value + ", " : "") + + (messageId != null ? "messageId=" + messageId + ", " : "") + + (distinct != null ? "distinct=" + distinct + ", " : "") + + "}"; + } +} diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/service/impl/MessageHeaderServiceImpl.java b/simulator-starter/src/main/java/org/citrusframework/simulator/service/impl/MessageHeaderServiceImpl.java new file mode 100644 index 000000000..015803d42 --- /dev/null +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/service/impl/MessageHeaderServiceImpl.java @@ -0,0 +1,65 @@ +package org.citrusframework.simulator.service.impl; + +import org.citrusframework.simulator.model.MessageHeader; +import org.citrusframework.simulator.repository.MessageHeaderRepository; +import org.citrusframework.simulator.service.MessageHeaderService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +/** + * Service Implementation for managing {@link MessageHeader}. + */ +@Service +@Transactional +public class MessageHeaderServiceImpl implements MessageHeaderService { + + private final Logger log = LoggerFactory.getLogger(MessageHeaderServiceImpl.class); + + private final MessageHeaderRepository messageHeaderRepository; + + public MessageHeaderServiceImpl(MessageHeaderRepository messageHeaderRepository) { + this.messageHeaderRepository = messageHeaderRepository; + } + + @Override + public MessageHeader save(MessageHeader messageHeader) { + log.debug("Request to save MessageHeader : {}", messageHeader); + return messageHeaderRepository.save(messageHeader); + } + + @Override + public MessageHeader update(MessageHeader messageHeader) { + log.debug("Request to update MessageHeader : {}", messageHeader); + return messageHeaderRepository.save(messageHeader); + } + + @Override + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + log.debug("Request to get all MessageHeaders"); + return messageHeaderRepository.findAll(pageable); + } + + public Page findAllWithEagerRelationships(Pageable pageable) { + return messageHeaderRepository.findAllWithEagerRelationships(pageable); + } + + @Override + @Transactional(readOnly = true) + public Optional findOne(Long id) { + log.debug("Request to get MessageHeader : {}", id); + return messageHeaderRepository.findOneWithEagerRelationships(id); + } + + @Override + public void delete(Long id) { + log.debug("Request to delete MessageHeader : {}", id); + messageHeaderRepository.deleteById(id); + } +} diff --git a/simulator-starter/src/main/java/org/citrusframework/simulator/web/rest/MessageHeaderResource.java b/simulator-starter/src/main/java/org/citrusframework/simulator/web/rest/MessageHeaderResource.java new file mode 100644 index 000000000..aef544943 --- /dev/null +++ b/simulator-starter/src/main/java/org/citrusframework/simulator/web/rest/MessageHeaderResource.java @@ -0,0 +1,85 @@ +package org.citrusframework.simulator.web.rest; + +import org.citrusframework.simulator.model.MessageHeader; +import org.citrusframework.simulator.service.MessageHeaderQueryService; +import org.citrusframework.simulator.service.MessageHeaderService; +import org.citrusframework.simulator.service.criteria.MessageHeaderCriteria; +import org.citrusframework.simulator.web.util.PaginationUtil; +import org.citrusframework.simulator.web.util.ResponseUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.List; +import java.util.Optional; + +/** + * REST controller for managing {@link MessageHeader}. + */ +@RestController +@RequestMapping("/api") +public class MessageHeaderResource { + + private final Logger log = LoggerFactory.getLogger(MessageHeaderResource.class); + + private final MessageHeaderService messageHeaderService; + + private final MessageHeaderQueryService messageHeaderQueryService; + + public MessageHeaderResource(MessageHeaderService messageHeaderService, MessageHeaderQueryService messageHeaderQueryService) { + this.messageHeaderService = messageHeaderService; + this.messageHeaderQueryService = messageHeaderQueryService; + } + + /** + * {@code GET /message-headers} : get all the messageHeaders. + * + * @param pageable the pagination information. + * @param criteria the criteria which the requested entities should match. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of messageHeaders in body. + */ + @GetMapping("/message-headers") + public ResponseEntity> getAllMessageHeaders( + MessageHeaderCriteria criteria, + @org.springdoc.core.annotations.ParameterObject Pageable pageable + ) { + log.debug("REST request to get MessageHeaders by criteria: {}", criteria); + + Page page = messageHeaderQueryService.findByCriteria(criteria, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + + /** + * {@code GET /message-headers/count} : count all the messageHeaders. + * + * @param criteria the criteria which the requested entities should match. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body. + */ + @GetMapping("/message-headers/count") + public ResponseEntity countMessageHeaders(MessageHeaderCriteria criteria) { + log.debug("REST request to count MessageHeaders by criteria: {}", criteria); + return ResponseEntity.ok().body(messageHeaderQueryService.countByCriteria(criteria)); + } + + /** + * {@code GET /message-headers/:id} : get the "id" messageHeader. + * + * @param id the id of the messageHeader to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the messageHeader, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/message-headers/{id}") + public ResponseEntity getMessageHeader(@PathVariable Long id) { + log.debug("REST request to get MessageHeader : {}", id); + Optional messageHeader = messageHeaderService.findOne(id); + return ResponseUtil.wrapOrNotFound(messageHeader); + } +} diff --git a/simulator-starter/src/test/java/org/citrusframework/simulator/model/MessageHeaderTest.java b/simulator-starter/src/test/java/org/citrusframework/simulator/model/MessageHeaderTest.java new file mode 100644 index 000000000..4d5f16e5b --- /dev/null +++ b/simulator-starter/src/test/java/org/citrusframework/simulator/model/MessageHeaderTest.java @@ -0,0 +1,27 @@ +package org.citrusframework.simulator.model; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class MessageHeaderTest { + + @Test + void equalsVerifier() throws Exception { + EntityUtils.equalsVerifier(MessageHeader.class); + + MessageHeader messageHeader1 = new MessageHeader(); + messageHeader1.setHeaderId(1L); + + MessageHeader messageHeader2 = new MessageHeader(); + messageHeader2.setHeaderId(messageHeader1.getHeaderId()); + + assertThat(messageHeader1).isEqualTo(messageHeader2); + + messageHeader2.setHeaderId(2L); + assertThat(messageHeader1).isNotEqualTo(messageHeader2); + + messageHeader1.setHeaderId(null); + assertThat(messageHeader1).isNotEqualTo(messageHeader2); + } +} diff --git a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/MessageHeaderResourceIT.java b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/MessageHeaderResourceIT.java new file mode 100644 index 000000000..4b39c9b42 --- /dev/null +++ b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/MessageHeaderResourceIT.java @@ -0,0 +1,385 @@ +package org.citrusframework.simulator.web.rest; + +import jakarta.persistence.EntityManager; +import org.citrusframework.simulator.IntegrationTest; +import org.citrusframework.simulator.model.Message; +import org.citrusframework.simulator.model.MessageHeader; +import org.citrusframework.simulator.repository.MessageHeaderRepository; +import org.citrusframework.simulator.service.MessageHeaderService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; + +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Integration tests for the {@link MessageHeaderResource} REST controller. + */ +@IntegrationTest +@AutoConfigureMockMvc +@ExtendWith(MockitoExtension.class) +class MessageHeaderResourceIT { + + private static final String DEFAULT_NAME = "AAAAAAAAAA"; + private static final String UPDATED_NAME = "BBBBBBBBBB"; + + private static final String DEFAULT_VALUE = "AAAAAAAAAA"; + private static final String UPDATED_VALUE = "BBBBBBBBBB"; + + private static final String ENTITY_API_URL = "/api/message-headers"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; + + @Autowired + private MessageHeaderRepository messageHeaderRepository; + + @Mock + private MessageHeaderRepository messageHeaderRepositoryMock; + + @Mock + private MessageHeaderService messageHeaderServiceMock; + + @Autowired + private EntityManager entityManager; + + @Autowired + private MockMvc restMessageHeaderMockMvc; + + private MessageHeader messageHeader; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static MessageHeader createEntity(EntityManager entityManager) { + MessageHeader messageHeader = MessageHeader.builder() + .name(DEFAULT_NAME) + .value(DEFAULT_VALUE) + .build(); + // Add required entity + Message message; + if (TestUtil.findAll(entityManager, Message.class).isEmpty()) { + message = MessageResourceIT.createEntity(entityManager); + entityManager.persist(message); + entityManager.flush(); + } else { + message = TestUtil.findAll(entityManager, Message.class).get(0); + } + messageHeader.setMessage(message); + return messageHeader; + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static MessageHeader createUpdatedEntity(EntityManager entityManager) { + MessageHeader messageHeader = MessageHeader.builder() + .name(UPDATED_NAME) + .value(UPDATED_VALUE) + .build(); + // Add required entity + Message message; + if (TestUtil.findAll(entityManager, Message.class).isEmpty()) { + message = MessageResourceIT.createUpdatedEntity(entityManager); + entityManager.persist(message); + entityManager.flush(); + } else { + message = TestUtil.findAll(entityManager, Message.class).get(0); + } + messageHeader.setMessage(message); + return messageHeader; + } + + @BeforeEach + public void initTest() { + messageHeader = createEntity(entityManager); + } + + @Test + @Transactional + void getAllMessageHeaders() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList + restMessageHeaderMockMvc + .perform(get(ENTITY_API_URL + "?sort=headerId,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].headerId").value(hasItem(messageHeader.getHeaderId().intValue()))) + .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))) + .andExpect(jsonPath("$.[*].value").value(hasItem(DEFAULT_VALUE))); + } + + @SuppressWarnings({ "unchecked" }) + void getAllMessageHeadersWithEagerRelationshipsIsEnabled() throws Exception { + when(messageHeaderServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>())); + + restMessageHeaderMockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")).andExpect(status().isOk()); + + verify(messageHeaderServiceMock, times(1)).findAllWithEagerRelationships(any()); + } + + @SuppressWarnings({ "unchecked" }) + void getAllMessageHeadersWithEagerRelationshipsIsNotEnabled() throws Exception { + when(messageHeaderServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>())); + + restMessageHeaderMockMvc.perform(get(ENTITY_API_URL + "?eagerload=false")).andExpect(status().isOk()); + verify(messageHeaderRepositoryMock, times(1)).findAll(any(Pageable.class)); + } + + @Test + @Transactional + void getMessageHeader() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get the messageHeader + restMessageHeaderMockMvc + .perform(get(ENTITY_API_URL_ID, messageHeader.getHeaderId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.headerId").value(messageHeader.getHeaderId().intValue())) + .andExpect(jsonPath("$.name").value(DEFAULT_NAME)) + .andExpect(jsonPath("$.value").value(DEFAULT_VALUE)); + } + + @Test + @Transactional + void getMessageHeadersByIdFiltering() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + Long headerId = messageHeader.getHeaderId(); + + defaultMessageHeaderShouldBeFound("headerId.equals=" + headerId); + defaultMessageHeaderShouldNotBeFound("headerId.notEquals=" + headerId); + + defaultMessageHeaderShouldBeFound("headerId.greaterThanOrEqual=" + headerId); + defaultMessageHeaderShouldNotBeFound("headerId.greaterThan=" + headerId); + + defaultMessageHeaderShouldBeFound("headerId.lessThanOrEqual=" + headerId); + defaultMessageHeaderShouldNotBeFound("headerId.lessThan=" + headerId); + } + + @Test + @Transactional + void getAllMessageHeadersByNameIsEqualToSomething() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where name equals to DEFAULT_NAME + defaultMessageHeaderShouldBeFound("name.equals=" + DEFAULT_NAME); + + // Get all the messageHeaderList where name equals to UPDATED_NAME + defaultMessageHeaderShouldNotBeFound("name.equals=" + UPDATED_NAME); + } + + @Test + @Transactional + void getAllMessageHeadersByNameIsInShouldWork() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where name in DEFAULT_NAME or UPDATED_NAME + defaultMessageHeaderShouldBeFound("name.in=" + DEFAULT_NAME + "," + UPDATED_NAME); + + // Get all the messageHeaderList where name equals to UPDATED_NAME + defaultMessageHeaderShouldNotBeFound("name.in=" + UPDATED_NAME); + } + + @Test + @Transactional + void getAllMessageHeadersByNameIsNullOrNotNull() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where name is not null + defaultMessageHeaderShouldBeFound("name.specified=true"); + + // Get all the messageHeaderList where name is null + defaultMessageHeaderShouldNotBeFound("name.specified=false"); + } + + @Test + @Transactional + void getAllMessageHeadersByNameContainsSomething() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where name contains DEFAULT_NAME + defaultMessageHeaderShouldBeFound("name.contains=" + DEFAULT_NAME); + + // Get all the messageHeaderList where name contains UPDATED_NAME + defaultMessageHeaderShouldNotBeFound("name.contains=" + UPDATED_NAME); + } + + @Test + @Transactional + void getAllMessageHeadersByNameNotContainsSomething() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where name does not contain DEFAULT_NAME + defaultMessageHeaderShouldNotBeFound("name.doesNotContain=" + DEFAULT_NAME); + + // Get all the messageHeaderList where name does not contain UPDATED_NAME + defaultMessageHeaderShouldBeFound("name.doesNotContain=" + UPDATED_NAME); + } + + @Test + @Transactional + void getAllMessageHeadersByValueIsEqualToSomething() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where value equals to DEFAULT_VALUE + defaultMessageHeaderShouldBeFound("value.equals=" + DEFAULT_VALUE); + + // Get all the messageHeaderList where value equals to UPDATED_VALUE + defaultMessageHeaderShouldNotBeFound("value.equals=" + UPDATED_VALUE); + } + + @Test + @Transactional + void getAllMessageHeadersByValueIsInShouldWork() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where value in DEFAULT_VALUE or UPDATED_VALUE + defaultMessageHeaderShouldBeFound("value.in=" + DEFAULT_VALUE + "," + UPDATED_VALUE); + + // Get all the messageHeaderList where value equals to UPDATED_VALUE + defaultMessageHeaderShouldNotBeFound("value.in=" + UPDATED_VALUE); + } + + @Test + @Transactional + void getAllMessageHeadersByValueIsNullOrNotNull() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where value is not null + defaultMessageHeaderShouldBeFound("value.specified=true"); + + // Get all the messageHeaderList where value is null + defaultMessageHeaderShouldNotBeFound("value.specified=false"); + } + + @Test + @Transactional + void getAllMessageHeadersByValueContainsSomething() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where value contains DEFAULT_VALUE + defaultMessageHeaderShouldBeFound("value.contains=" + DEFAULT_VALUE); + + // Get all the messageHeaderList where value contains UPDATED_VALUE + defaultMessageHeaderShouldNotBeFound("value.contains=" + UPDATED_VALUE); + } + + @Test + @Transactional + void getAllMessageHeadersByValueNotContainsSomething() throws Exception { + // Initialize the database + messageHeaderRepository.saveAndFlush(messageHeader); + + // Get all the messageHeaderList where value does not contain DEFAULT_VALUE + defaultMessageHeaderShouldNotBeFound("value.doesNotContain=" + DEFAULT_VALUE); + + // Get all the messageHeaderList where value does not contain UPDATED_VALUE + defaultMessageHeaderShouldBeFound("value.doesNotContain=" + UPDATED_VALUE); + } + + @Test + @Transactional + void getAllMessageHeadersByMessageIsEqualToSomething() throws Exception { + Message message; + if (TestUtil.findAll(entityManager, Message.class).isEmpty()) { + messageHeaderRepository.saveAndFlush(messageHeader); + message = MessageResourceIT.createEntity(entityManager); + } else { + message = TestUtil.findAll(entityManager, Message.class).get(0); + } + entityManager.persist(message); + entityManager.flush(); + messageHeader.setMessage(message); + messageHeaderRepository.saveAndFlush(messageHeader); + Long messageId = message.getMessageId(); + // Get all the messageHeaderList where message equals to messageId + defaultMessageHeaderShouldBeFound("messageId.equals=" + messageId); + + // Get all the messageHeaderList where message equals to (messageId + 1) + defaultMessageHeaderShouldNotBeFound("messageId.equals=" + (messageId + 1)); + } + + /** + * Executes the search, and checks that the default entity is returned. + */ + private void defaultMessageHeaderShouldBeFound(String filter) throws Exception { + restMessageHeaderMockMvc + .perform(get(ENTITY_API_URL + "?sort=headerId,desc&" + filter)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].headerId").value(hasItem(messageHeader.getHeaderId().intValue()))) + .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))) + .andExpect(jsonPath("$.[*].value").value(hasItem(DEFAULT_VALUE))); + + // Check, that the count call also returns 1 + restMessageHeaderMockMvc + .perform(get(ENTITY_API_URL + "/count?sort=headerId,desc&" + filter)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().string("1")); + } + + /** + * Executes the search, and checks that the default entity is not returned. + */ + private void defaultMessageHeaderShouldNotBeFound(String filter) throws Exception { + restMessageHeaderMockMvc + .perform(get(ENTITY_API_URL + "?sort=headerId,desc&" + filter)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").isEmpty()); + + // Check, that the count call also returns 0 + restMessageHeaderMockMvc + .perform(get(ENTITY_API_URL + "/count?sort=headerId,desc&" + filter)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().string("0")); + } + + @Test + @Transactional + void getNonExistingMessageHeader() throws Exception { + // Get the messageHeader + restMessageHeaderMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } +} diff --git a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/MessageResourceIT.java b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/MessageResourceIT.java index ac171cc42..1f2b510ce 100644 --- a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/MessageResourceIT.java +++ b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/MessageResourceIT.java @@ -68,7 +68,7 @@ class MessageResourceIT { * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ - public static Message createEntity(EntityManager em) { + public static Message createEntity(EntityManager entityManager) { Message message = Message.builder() .direction(DEFAULT_DIRECTION) .payload(DEFAULT_PAYLOAD) @@ -85,7 +85,7 @@ public static Message createEntity(EntityManager em) { * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ - public static Message createUpdatedEntity(EntityManager em) { + public static Message createUpdatedEntity(EntityManager entityManager) { Message message = Message.builder() .direction(UPDATED_DIRECTION) .payload(UPDATED_PAYLOAD) @@ -145,16 +145,16 @@ void getMessagesByIdFiltering() throws Exception { // Initialize the database messageRepository.saveAndFlush(message); - Long id = message.getMessageId(); + Long messageId = message.getMessageId(); - defaultMessageShouldBeFound("messageId.equals=" + id); - defaultMessageShouldNotBeFound("messageId.notEquals=" + id); + defaultMessageShouldBeFound("messageId.equals=" + messageId); + defaultMessageShouldNotBeFound("messageId.notEquals=" + messageId); - defaultMessageShouldBeFound("messageId.greaterThanOrEqual=" + id); - defaultMessageShouldNotBeFound("messageId.greaterThan=" + id); + defaultMessageShouldBeFound("messageId.greaterThanOrEqual=" + messageId); + defaultMessageShouldNotBeFound("messageId.greaterThan=" + messageId); - defaultMessageShouldBeFound("messageId.lessThanOrEqual=" + id); - defaultMessageShouldNotBeFound("messageId.lessThan=" + id); + defaultMessageShouldBeFound("messageId.lessThanOrEqual=" + messageId); + defaultMessageShouldNotBeFound("messageId.lessThan=" + messageId); } @Test diff --git a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestParameterResourceIT.java b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestParameterResourceIT.java index 498dd44fa..757fbb22b 100644 --- a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestParameterResourceIT.java +++ b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestParameterResourceIT.java @@ -67,7 +67,7 @@ class TestParameterResourceIT { * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ - public static TestParameter createEntity(EntityManager em) { + public static TestParameter createEntity(EntityManager entityManager) { TestParameter testParameter = TestParameter.builder() .key(DEFAULT_KEY) .value(DEFAULT_VALUE) @@ -76,12 +76,12 @@ public static TestParameter createEntity(EntityManager em) { .build(); TestResult testResult; - if (findAll(em, TestResult.class).isEmpty()) { - testResult = TestResultResourceIT.createEntity(em); - em.persist(testResult); - em.flush(); + if (findAll(entityManager, TestResult.class).isEmpty()) { + testResult = TestResultResourceIT.createEntity(entityManager); + entityManager.persist(testResult); + entityManager.flush(); } else { - testResult = findAll(em, TestResult.class).get(0); + testResult = findAll(entityManager, TestResult.class).get(0); } testParameter.setTestResult(testResult); diff --git a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestResultResourceIT.java b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestResultResourceIT.java index a52a37842..d4c1a4e9e 100644 --- a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestResultResourceIT.java +++ b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestResultResourceIT.java @@ -78,7 +78,7 @@ class TestResultResourceIT { * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ - public static TestResult createEntity(EntityManager em) { + public static TestResult createEntity(EntityManager entityManager) { TestResult testResult = TestResult.builder() .status(DEFAULT_STATUS.getId()) .testName(DEFAULT_TEST_NAME) diff --git a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestUtil.java b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestUtil.java index 84d94d627..c975f7898 100644 --- a/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestUtil.java +++ b/simulator-starter/src/test/java/org/citrusframework/simulator/web/rest/TestUtil.java @@ -20,17 +20,17 @@ public class TestUtil { /** * Executes a query on the EntityManager finding all stored objects. * - * @param The type of objects to be searched - * @param em The instance of the EntityManager - * @param clazz The class type to be searched + * @param The type of objects to be searched + * @param entityManager The instance of the EntityManager + * @param clazz The class type to be searched * @return A list of all found objects */ - public static List findAll(EntityManager em, Class clazz) { - CriteriaBuilder cb = em.getCriteriaBuilder(); + public static List findAll(EntityManager entityManager, Class clazz) { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(clazz); Root rootEntry = cq.from(clazz); CriteriaQuery all = cq.select(rootEntry); - TypedQuery allQuery = em.createQuery(all); + TypedQuery allQuery = entityManager.createQuery(all); return allQuery.getResultList(); } diff --git a/simulator-ui/.jhipster/MessageHeader.json b/simulator-ui/.jhipster/MessageHeader.json new file mode 100644 index 000000000..fdf437a90 --- /dev/null +++ b/simulator-ui/.jhipster/MessageHeader.json @@ -0,0 +1,33 @@ +{ + "changelogDate": "20231018170659", + "dto": "no", + "entityTableName": "message_header", + "fields": [ + { + "fieldName": "name", + "fieldType": "String", + "fieldValidateRules": ["required"] + }, + { + "fieldName": "value", + "fieldType": "String", + "fieldValidateRules": ["required"] + } + ], + "jpaMetamodelFiltering": true, + "name": "MessageHeader", + "pagination": "pagination", + "readOnly": true, + "relationships": [ + { + "otherEntityField": "citrusMessageId", + "otherEntityName": "message", + "relationshipName": "message", + "relationshipSide": "left", + "relationshipType": "many-to-one", + "relationshipValidateRules": ["required"] + } + ], + "searchEngine": "no", + "service": "serviceImpl" +} diff --git a/simulator-ui/src/main/webapp/app/entities/entity-routing.module.ts b/simulator-ui/src/main/webapp/app/entities/entity-routing.module.ts index ed3ac2c43..6581c76d0 100644 --- a/simulator-ui/src/main/webapp/app/entities/entity-routing.module.ts +++ b/simulator-ui/src/main/webapp/app/entities/entity-routing.module.ts @@ -9,6 +9,11 @@ import { RouterModule } from '@angular/router'; data: { pageTitle: 'citrusSimulatorApp.message.home.title' }, loadChildren: () => import('./message/message.routes'), }, + { + path: 'message-header', + data: { pageTitle: 'citrusSimulatorApp.messageHeader.home.title' }, + loadChildren: () => import('./message-header/message-header.routes'), + }, { path: 'test-parameter', data: { pageTitle: 'citrusSimulatorApp.testParameter.home.title' }, diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.html b/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.html new file mode 100644 index 000000000..79ab6042f --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.html @@ -0,0 +1,40 @@ +

+
+
+

+ Message Header +

+ +
+ + + + + +
+
ID
+
+ {{ messageHeader.headerId }} +
+
Name
+
+ {{ messageHeader.name }} +
+
Value
+
+ {{ messageHeader.value }} +
+
Message
+
+ +
+
+ + +
+
+
diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.spec.ts b/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.spec.ts new file mode 100644 index 000000000..b705846f9 --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.spec.ts @@ -0,0 +1,38 @@ +import { TestBed } from '@angular/core/testing'; +import { provideRouter, withComponentInputBinding } from '@angular/router'; +import { RouterTestingHarness, RouterTestingModule } from '@angular/router/testing'; +import { of } from 'rxjs'; + +import { MessageHeaderDetailComponent } from './message-header-detail.component'; + +describe('MessageHeader Management Detail Component', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [MessageHeaderDetailComponent, RouterTestingModule.withRoutes([], { bindToComponentInputs: true })], + providers: [ + provideRouter( + [ + { + path: '**', + component: MessageHeaderDetailComponent, + resolve: { messageHeader: () => of({ headerId: 123 }) }, + }, + ], + withComponentInputBinding(), + ), + ], + }) + .overrideTemplate(MessageHeaderDetailComponent, '') + .compileComponents(); + }); + + describe('OnInit', () => { + it('Should load messageHeader on init', async () => { + const harness = await RouterTestingHarness.create(); + const instance = await harness.navigateByUrl('/', MessageHeaderDetailComponent); + + // THEN + expect(instance.messageHeader).toEqual(expect.objectContaining({ headerId: 123 })); + }); + }); +}); diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.ts b/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.ts new file mode 100644 index 000000000..bbfa90fdb --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/detail/message-header-detail.component.ts @@ -0,0 +1,22 @@ +import { Component, Input } from '@angular/core'; +import { ActivatedRoute, RouterModule } from '@angular/router'; + +import SharedModule from 'app/shared/shared.module'; +import { DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe } from 'app/shared/date'; +import { IMessageHeader } from '../message-header.model'; + +@Component({ + standalone: true, + selector: 'jhi-message-header-detail', + templateUrl: './message-header-detail.component.html', + imports: [SharedModule, RouterModule, DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe], +}) +export class MessageHeaderDetailComponent { + @Input() messageHeader: IMessageHeader | null = null; + + constructor(protected activatedRoute: ActivatedRoute) {} + + previousState(): void { + window.history.back(); + } +} diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.html b/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.html new file mode 100644 index 000000000..7b5555f8d --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.html @@ -0,0 +1,101 @@ +
+

+ Message Headers + +
+ +
+

+ + + + + + + +
+ No Message Headers found +
+ +
+ + + + + + + + + + + + + + + + + + + +
+
+ ID + +
+
+
+ Name + +
+
+
+ Value + +
+
+
+ Message + +
+
+ {{ messageHeader.headerId }} + {{ messageHeader.name }}{{ messageHeader.value }} + + +
+ +
+
+
+ +
+
+ +
+ +
+ +
+
+
diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.spec.ts b/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.spec.ts new file mode 100644 index 000000000..77e6421c0 --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.spec.ts @@ -0,0 +1,125 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { HttpClientTestingModule } from '@angular/common/http/testing'; +import { ActivatedRoute } from '@angular/router'; +import { RouterTestingModule } from '@angular/router/testing'; +import { of } from 'rxjs'; + +import { MessageHeaderService } from '../service/message-header.service'; + +import { MessageHeaderComponent } from './message-header.component'; +import SpyInstance = jest.SpyInstance; + +describe('MessageHeader Management Component', () => { + let comp: MessageHeaderComponent; + let fixture: ComponentFixture; + let service: MessageHeaderService; + let routerNavigateSpy: SpyInstance>; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + RouterTestingModule.withRoutes([{ path: 'message-header', component: MessageHeaderComponent }]), + HttpClientTestingModule, + MessageHeaderComponent, + ], + providers: [ + { + provide: ActivatedRoute, + useValue: { + data: of({ + defaultSort: 'headerId,asc', + }), + queryParamMap: of( + jest.requireActual('@angular/router').convertToParamMap({ + page: '1', + size: '1', + sort: 'headerId,desc', + 'filter[someId.in]': 'dc4279ea-cfb9-11ec-9d64-0242ac120002', + }), + ), + snapshot: { queryParams: {} }, + }, + }, + ], + }) + .overrideTemplate(MessageHeaderComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(MessageHeaderComponent); + comp = fixture.componentInstance; + service = TestBed.inject(MessageHeaderService); + routerNavigateSpy = jest.spyOn(comp.router, 'navigate'); + + const headers = new HttpHeaders(); + jest.spyOn(service, 'query').mockReturnValue( + of( + new HttpResponse({ + body: [{ headerId: 123 }], + headers, + }), + ), + ); + }); + + it('Should call load all on init', () => { + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.messageHeaders?.[0]).toEqual(expect.objectContaining({ headerId: 123 })); + }); + + describe('trackId', () => { + it('Should forward to messageHeaderService', () => { + const entity = { headerId: 123 }; + jest.spyOn(service, 'getMessageHeaderIdentifier'); + const headerId = comp.trackId(0, entity); + expect(service.getMessageHeaderIdentifier).toHaveBeenCalledWith(entity); + expect(headerId).toBe(entity.headerId); + }); + }); + + it('should load a page', () => { + // WHEN + comp.navigateToPage(1); + + // THEN + expect(routerNavigateSpy).toHaveBeenCalled(); + }); + + it('should calculate the sort attribute for a headerId', () => { + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenLastCalledWith(expect.objectContaining({ sort: ['headerId,desc'] })); + }); + + it('should calculate the sort attribute for a non-id attribute', () => { + // GIVEN + comp.predicate = 'name'; + + // WHEN + comp.navigateToWithComponentValues(); + + // THEN + expect(routerNavigateSpy).toHaveBeenLastCalledWith( + expect.anything(), + expect.objectContaining({ + queryParams: expect.objectContaining({ + sort: ['name,asc'], + }), + }), + ); + }); + + it('should calculate the filter attribute', () => { + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenLastCalledWith(expect.objectContaining({ 'someId.in': ['dc4279ea-cfb9-11ec-9d64-0242ac120002'] })); + }); +}); diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.ts b/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.ts new file mode 100644 index 000000000..5156e31e7 --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/list/message-header.component.ts @@ -0,0 +1,152 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpHeaders } from '@angular/common/http'; +import { ActivatedRoute, Data, ParamMap, Router, RouterModule } from '@angular/router'; +import { combineLatest, Observable, switchMap, tap } from 'rxjs'; + +import SharedModule from 'app/shared/shared.module'; +import { SortDirective, SortByDirective } from 'app/shared/sort'; +import { DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe } from 'app/shared/date'; +import { ItemCountComponent } from 'app/shared/pagination'; +import { FormsModule } from '@angular/forms'; + +import { ITEMS_PER_PAGE, PAGE_HEADER, TOTAL_COUNT_RESPONSE_HEADER } from 'app/config/pagination.constants'; +import { ASC, DESC, SORT, DEFAULT_SORT_DATA } from 'app/config/navigation.constants'; +import { FilterComponent, FilterOptions, IFilterOptions, IFilterOption } from 'app/shared/filter'; +import { EntityArrayResponseType, MessageHeaderService } from '../service/message-header.service'; +import { IMessageHeader } from '../message-header.model'; + +@Component({ + standalone: true, + selector: 'jhi-message-header', + templateUrl: './message-header.component.html', + imports: [ + RouterModule, + FormsModule, + SharedModule, + SortDirective, + SortByDirective, + DurationPipe, + FormatMediumDatetimePipe, + FormatMediumDatePipe, + FilterComponent, + ItemCountComponent, + ], +}) +export class MessageHeaderComponent implements OnInit { + messageHeaders?: IMessageHeader[]; + isLoading = false; + + predicate = 'headerId'; + ascending = true; + filters: IFilterOptions = new FilterOptions(); + + itemsPerPage = ITEMS_PER_PAGE; + totalItems = 0; + page = 1; + + constructor( + protected messageHeaderService: MessageHeaderService, + protected activatedRoute: ActivatedRoute, + public router: Router, + ) {} + + trackId = (_index: number, item: IMessageHeader): number => this.messageHeaderService.getMessageHeaderIdentifier(item); + + ngOnInit(): void { + this.load(); + + this.filters.filterChanges.subscribe(filterOptions => this.handleNavigation(1, this.predicate, this.ascending, filterOptions)); + } + + load(): void { + this.loadFromBackendWithRouteInformations().subscribe({ + next: (res: EntityArrayResponseType) => { + this.onResponseSuccess(res); + }, + }); + } + + navigateToWithComponentValues(): void { + this.handleNavigation(this.page, this.predicate, this.ascending, this.filters.filterOptions); + } + + navigateToPage(page = this.page): void { + this.handleNavigation(page, this.predicate, this.ascending, this.filters.filterOptions); + } + + protected loadFromBackendWithRouteInformations(): Observable { + return combineLatest([this.activatedRoute.queryParamMap, this.activatedRoute.data]).pipe( + tap(([params, data]) => this.fillComponentAttributeFromRoute(params, data)), + switchMap(() => this.queryBackend(this.page, this.predicate, this.ascending, this.filters.filterOptions)), + ); + } + + protected fillComponentAttributeFromRoute(params: ParamMap, data: Data): void { + const page = params.get(PAGE_HEADER); + this.page = +(page ?? 1); + const sort = (params.get(SORT) ?? data[DEFAULT_SORT_DATA]).split(','); + this.predicate = sort[0]; + this.ascending = sort[1] === ASC; + this.filters.initializeFromParams(params); + } + + protected onResponseSuccess(response: EntityArrayResponseType): void { + this.fillComponentAttributesFromResponseHeader(response.headers); + const dataFromBody = this.fillComponentAttributesFromResponseBody(response.body); + this.messageHeaders = dataFromBody; + } + + protected fillComponentAttributesFromResponseBody(data: IMessageHeader[] | null): IMessageHeader[] { + return data ?? []; + } + + protected fillComponentAttributesFromResponseHeader(headers: HttpHeaders): void { + this.totalItems = Number(headers.get(TOTAL_COUNT_RESPONSE_HEADER)); + } + + protected queryBackend( + page?: number, + predicate?: string, + ascending?: boolean, + filterOptions?: IFilterOption[], + ): Observable { + this.isLoading = true; + const pageToLoad: number = page ?? 1; + const queryObject: any = { + page: pageToLoad - 1, + size: this.itemsPerPage, + eagerload: true, + sort: this.getSortQueryParam(predicate, ascending), + }; + filterOptions?.forEach(filterOption => { + queryObject[filterOption.name] = filterOption.values; + }); + return this.messageHeaderService.query(queryObject).pipe(tap(() => (this.isLoading = false))); + } + + protected handleNavigation(page = this.page, predicate?: string, ascending?: boolean, filterOptions?: IFilterOption[]): void { + const queryParamsObj: any = { + page, + size: this.itemsPerPage, + sort: this.getSortQueryParam(predicate, ascending), + }; + + filterOptions?.forEach(filterOption => { + queryParamsObj[filterOption.nameAsQueryParam()] = filterOption.values; + }); + + this.router.navigate(['./'], { + relativeTo: this.activatedRoute, + queryParams: queryParamsObj, + }); + } + + protected getSortQueryParam(predicate = this.predicate, ascending = this.ascending): string[] { + const ascendingQueryParam = ascending ? ASC : DESC; + if (predicate === '') { + return []; + } else { + return [predicate + ',' + ascendingQueryParam]; + } + } +} diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/message-header.model.ts b/simulator-ui/src/main/webapp/app/entities/message-header/message-header.model.ts new file mode 100644 index 000000000..516d2fa9e --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/message-header.model.ts @@ -0,0 +1,10 @@ +import { IMessage } from 'app/entities/message/message.model'; + +export interface IMessageHeader { + headerId: number; + name?: string | null; + value?: string | null; + message?: Pick | null; +} + +export type NewMessageHeader = Omit & { headerId: null }; diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/message-header.routes.ts b/simulator-ui/src/main/webapp/app/entities/message-header/message-header.routes.ts new file mode 100644 index 000000000..ae8f410df --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/message-header.routes.ts @@ -0,0 +1,25 @@ +import { Routes } from '@angular/router'; + +import { ASC } from 'app/config/navigation.constants'; +import { MessageHeaderComponent } from './list/message-header.component'; +import { MessageHeaderDetailComponent } from './detail/message-header-detail.component'; +import MessageHeaderResolve from './route/message-header-routing-resolve.service'; + +const messageHeaderRoute: Routes = [ + { + path: '', + component: MessageHeaderComponent, + data: { + defaultSort: 'headerId,' + ASC, + } + }, + { + path: ':headerId/view', + component: MessageHeaderDetailComponent, + resolve: { + messageHeader: MessageHeaderResolve, + } + }, +]; + +export default messageHeaderRoute; diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/message-header.test-samples.ts b/simulator-ui/src/main/webapp/app/entities/message-header/message-header.test-samples.ts new file mode 100644 index 000000000..904361d87 --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/message-header.test-samples.ts @@ -0,0 +1,30 @@ +import { IMessageHeader, NewMessageHeader } from './message-header.model'; + +export const sampleWithRequiredData: IMessageHeader = { + headerId: 463, + name: 'knavishly', + value: 'however evenly', +}; + +export const sampleWithPartialData: IMessageHeader = { + headerId: 6641, + name: 'searchingly blah', + value: 'yesterday', +}; + +export const sampleWithFullData: IMessageHeader = { + headerId: 26555, + name: 'sheepishly mismanage ornery', + value: 'upbeat accomplish', +}; + +export const sampleWithNewData: NewMessageHeader = { + name: 'playground superior nimble', + value: 'fairly', + headerId: null, +}; + +Object.freeze(sampleWithNewData); +Object.freeze(sampleWithRequiredData); +Object.freeze(sampleWithPartialData); +Object.freeze(sampleWithFullData); diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/route/message-header-routing-resolve.service.spec.ts b/simulator-ui/src/main/webapp/app/entities/message-header/route/message-header-routing-resolve.service.spec.ts new file mode 100644 index 000000000..34b78e8ee --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/route/message-header-routing-resolve.service.spec.ts @@ -0,0 +1,99 @@ +import { TestBed } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { HttpClientTestingModule } from '@angular/common/http/testing'; +import { ActivatedRouteSnapshot, ActivatedRoute, Router, convertToParamMap } from '@angular/router'; +import { RouterTestingModule } from '@angular/router/testing'; +import { of } from 'rxjs'; + +import { IMessageHeader } from '../message-header.model'; +import { MessageHeaderService } from '../service/message-header.service'; + +import messageHeaderResolve from './message-header-routing-resolve.service'; + +describe('MessageHeader routing resolve service', () => { + let mockRouter: Router; + let mockActivatedRouteSnapshot: ActivatedRouteSnapshot; + let service: MessageHeaderService; + let resultMessageHeader: IMessageHeader | null | undefined; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([])], + providers: [ + { + provide: ActivatedRoute, + useValue: { + snapshot: { + paramMap: convertToParamMap({}), + }, + }, + }, + ], + }); + mockRouter = TestBed.inject(Router); + jest.spyOn(mockRouter, 'navigate').mockImplementation(() => Promise.resolve(true)); + mockActivatedRouteSnapshot = TestBed.inject(ActivatedRoute).snapshot; + service = TestBed.inject(MessageHeaderService); + resultMessageHeader = undefined; + }); + + describe('resolve', () => { + it('should return IMessageHeader returned by find', () => { + // GIVEN + service.find = jest.fn(headerId => of(new HttpResponse({ body: { headerId } }))); + mockActivatedRouteSnapshot.params = { headerId: 123 }; + + // WHEN + TestBed.runInInjectionContext(() => { + messageHeaderResolve(mockActivatedRouteSnapshot).subscribe({ + next(result) { + resultMessageHeader = result; + }, + }); + }); + + // THEN + expect(service.find).toBeCalledWith(123); + expect(resultMessageHeader).toEqual({ headerId: 123 }); + }); + + it('should return null if headerId is not provided', () => { + // GIVEN + service.find = jest.fn(); + mockActivatedRouteSnapshot.params = {}; + + // WHEN + TestBed.runInInjectionContext(() => { + messageHeaderResolve(mockActivatedRouteSnapshot).subscribe({ + next(result) { + resultMessageHeader = result; + }, + }); + }); + + // THEN + expect(service.find).not.toBeCalled(); + expect(resultMessageHeader).toEqual(null); + }); + + it('should route to 404 page if data not found in server', () => { + // GIVEN + jest.spyOn(service, 'find').mockReturnValue(of(new HttpResponse({ body: null }))); + mockActivatedRouteSnapshot.params = { headerId: 123 }; + + // WHEN + TestBed.runInInjectionContext(() => { + messageHeaderResolve(mockActivatedRouteSnapshot).subscribe({ + next(result) { + resultMessageHeader = result; + }, + }); + }); + + // THEN + expect(service.find).toBeCalledWith(123); + expect(resultMessageHeader).toEqual(undefined); + expect(mockRouter.navigate).toHaveBeenCalledWith(['404']); + }); + }); +}); diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/route/message-header-routing-resolve.service.ts b/simulator-ui/src/main/webapp/app/entities/message-header/route/message-header-routing-resolve.service.ts new file mode 100644 index 000000000..69fafb28b --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/route/message-header-routing-resolve.service.ts @@ -0,0 +1,29 @@ +import { inject } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { ActivatedRouteSnapshot, Router } from '@angular/router'; +import { of, EMPTY, Observable } from 'rxjs'; +import { mergeMap } from 'rxjs/operators'; + +import { IMessageHeader } from '../message-header.model'; +import { MessageHeaderService } from '../service/message-header.service'; + +export const messageHeaderResolve = (route: ActivatedRouteSnapshot): Observable => { + const headerId = route.params['headerId']; + if (headerId) { + return inject(MessageHeaderService) + .find(headerId) + .pipe( + mergeMap((messageHeader: HttpResponse) => { + if (messageHeader.body) { + return of(messageHeader.body); + } else { + inject(Router).navigate(['404']); + return EMPTY; + } + }), + ); + } + return of(null); +}; + +export default messageHeaderResolve; diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/service/message-header.service.spec.ts b/simulator-ui/src/main/webapp/app/entities/message-header/service/message-header.service.spec.ts new file mode 100644 index 000000000..a7ad42e6a --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/service/message-header.service.spec.ts @@ -0,0 +1,158 @@ +import { TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; + +import { IMessageHeader } from '../message-header.model'; +import { sampleWithRequiredData, sampleWithPartialData, sampleWithFullData } from '../message-header.test-samples'; + +import { MessageHeaderService } from './message-header.service'; + +const requireRestSample: IMessageHeader = { + ...sampleWithRequiredData, +}; + +describe('MessageHeader Service', () => { + let service: MessageHeaderService; + let httpMock: HttpTestingController; + let expectedResult: IMessageHeader | IMessageHeader[] | boolean | null; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + expectedResult = null; + service = TestBed.inject(MessageHeaderService); + httpMock = TestBed.inject(HttpTestingController); + }); + + describe('Service methods', () => { + it('should find an element', () => { + const returnedFromService = { ...requireRestSample }; + const expected = { ...sampleWithRequiredData }; + + service.find(123).subscribe(resp => (expectedResult = resp.body)); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject(expected); + }); + + it('should return a list of MessageHeader', () => { + const returnedFromService = { ...requireRestSample }; + + const expected = { ...sampleWithRequiredData }; + + service.query().subscribe(resp => (expectedResult = resp.body)); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush([returnedFromService]); + httpMock.verify(); + expect(expectedResult).toMatchObject([expected]); + }); + + describe('addMessageHeaderToCollectionIfMissing', () => { + it('should add a MessageHeader to an empty array', () => { + const messageHeader: IMessageHeader = sampleWithRequiredData; + expectedResult = service.addMessageHeaderToCollectionIfMissing([], messageHeader); + expect(expectedResult).toHaveLength(1); + expect(expectedResult).toContain(messageHeader); + }); + + it('should not add a MessageHeader to an array that contains it', () => { + const messageHeader: IMessageHeader = sampleWithRequiredData; + const messageHeaderCollection: IMessageHeader[] = [ + { + ...messageHeader, + }, + sampleWithPartialData, + ]; + expectedResult = service.addMessageHeaderToCollectionIfMissing(messageHeaderCollection, messageHeader); + expect(expectedResult).toHaveLength(2); + }); + + it("should add a MessageHeader to an array that doesn't contain it", () => { + const messageHeader: IMessageHeader = sampleWithRequiredData; + const messageHeaderCollection: IMessageHeader[] = [sampleWithPartialData]; + expectedResult = service.addMessageHeaderToCollectionIfMissing(messageHeaderCollection, messageHeader); + expect(expectedResult).toHaveLength(2); + expect(expectedResult).toContain(messageHeader); + }); + + it('should add only unique MessageHeader to an array', () => { + const messageHeaderArray: IMessageHeader[] = [sampleWithRequiredData, sampleWithPartialData, sampleWithFullData]; + const messageHeaderCollection: IMessageHeader[] = [sampleWithRequiredData]; + expectedResult = service.addMessageHeaderToCollectionIfMissing(messageHeaderCollection, ...messageHeaderArray); + expect(expectedResult).toHaveLength(3); + }); + + it('should accept varargs', () => { + const messageHeader: IMessageHeader = sampleWithRequiredData; + const messageHeader2: IMessageHeader = sampleWithPartialData; + expectedResult = service.addMessageHeaderToCollectionIfMissing([], messageHeader, messageHeader2); + expect(expectedResult).toHaveLength(2); + expect(expectedResult).toContain(messageHeader); + expect(expectedResult).toContain(messageHeader2); + }); + + it('should accept null and undefined values', () => { + const messageHeader: IMessageHeader = sampleWithRequiredData; + expectedResult = service.addMessageHeaderToCollectionIfMissing([], null, messageHeader, undefined); + expect(expectedResult).toHaveLength(1); + expect(expectedResult).toContain(messageHeader); + }); + + it('should return initial array if no MessageHeader is added', () => { + const messageHeaderCollection: IMessageHeader[] = [sampleWithRequiredData]; + expectedResult = service.addMessageHeaderToCollectionIfMissing(messageHeaderCollection, undefined, null); + expect(expectedResult).toEqual(messageHeaderCollection); + }); + }); + + describe('compareMessageHeader', () => { + it('Should return true if both entities are null', () => { + const entity1 = null; + const entity2 = null; + + const compareResult = service.compareMessageHeader(entity1, entity2); + + expect(compareResult).toEqual(true); + }); + + it('Should return false if one entity is null', () => { + const entity1 = { headerId: 123 }; + const entity2 = null; + + const compareResult1 = service.compareMessageHeader(entity1, entity2); + const compareResult2 = service.compareMessageHeader(entity2, entity1); + + expect(compareResult1).toEqual(false); + expect(compareResult2).toEqual(false); + }); + + it('Should return false if primaryKey differs', () => { + const entity1 = { headerId: 123 }; + const entity2 = { headerId: 456 }; + + const compareResult1 = service.compareMessageHeader(entity1, entity2); + const compareResult2 = service.compareMessageHeader(entity2, entity1); + + expect(compareResult1).toEqual(false); + expect(compareResult2).toEqual(false); + }); + + it('Should return false if primaryKey matches', () => { + const entity1 = { headerId: 123 }; + const entity2 = { headerId: 123 }; + + const compareResult1 = service.compareMessageHeader(entity1, entity2); + const compareResult2 = service.compareMessageHeader(entity2, entity1); + + expect(compareResult1).toEqual(true); + expect(compareResult2).toEqual(true); + }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/simulator-ui/src/main/webapp/app/entities/message-header/service/message-header.service.ts b/simulator-ui/src/main/webapp/app/entities/message-header/service/message-header.service.ts new file mode 100644 index 000000000..fb2f8399e --- /dev/null +++ b/simulator-ui/src/main/webapp/app/entities/message-header/service/message-header.service.ts @@ -0,0 +1,60 @@ +import { Injectable } from '@angular/core'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; + +import { isPresent } from 'app/core/util/operators'; +import { ApplicationConfigService } from 'app/core/config/application-config.service'; +import { createRequestOption } from 'app/core/request/request-util'; +import { IMessageHeader } from '../message-header.model'; + +export type EntityResponseType = HttpResponse; +export type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class MessageHeaderService { + protected resourceUrl = this.applicationConfigService.getEndpointFor('api/message-headers'); + + constructor( + protected http: HttpClient, + protected applicationConfigService: ApplicationConfigService, + ) {} + + find(headerId: number): Observable { + return this.http.get(`${this.resourceUrl}/${headerId}`, { observe: 'response' }); + } + + query(req?: any): Observable { + const options = createRequestOption(req); + return this.http.get(this.resourceUrl, { params: options, observe: 'response' }); + } + + getMessageHeaderIdentifier(messageHeader: Pick): number { + return messageHeader.headerId; + } + + compareMessageHeader(o1: Pick | null, o2: Pick | null): boolean { + return o1 && o2 ? this.getMessageHeaderIdentifier(o1) === this.getMessageHeaderIdentifier(o2) : o1 === o2; + } + + addMessageHeaderToCollectionIfMissing>( + messageHeaderCollection: Type[], + ...messageHeadersToCheck: (Type | null | undefined)[] + ): Type[] { + const messageHeaders: Type[] = messageHeadersToCheck.filter(isPresent); + if (messageHeaders.length > 0) { + const messageHeaderCollectionIdentifiers = messageHeaderCollection.map( + messageHeaderItem => this.getMessageHeaderIdentifier(messageHeaderItem)!, + ); + const messageHeadersToAdd = messageHeaders.filter(messageHeaderItem => { + const messageHeaderIdentifier = this.getMessageHeaderIdentifier(messageHeaderItem); + if (messageHeaderCollectionIdentifiers.includes(messageHeaderIdentifier)) { + return false; + } + messageHeaderCollectionIdentifiers.push(messageHeaderIdentifier); + return true; + }); + return [...messageHeadersToAdd, ...messageHeaderCollection]; + } + return messageHeaderCollection; + } +} diff --git a/simulator-ui/src/main/webapp/app/entities/message/service/message.service.ts b/simulator-ui/src/main/webapp/app/entities/message/service/message.service.ts index 0f240d70d..4bed681cc 100644 --- a/simulator-ui/src/main/webapp/app/entities/message/service/message.service.ts +++ b/simulator-ui/src/main/webapp/app/entities/message/service/message.service.ts @@ -11,8 +11,6 @@ import { ApplicationConfigService } from 'app/core/config/application-config.ser import { createRequestOption } from 'app/core/request/request-util'; import { IMessage, NewMessage } from '../message.model'; -export type PartialUpdateMessage = Partial & Pick; - type RestOf = Omit & { createdDate?: string | null; lastModifiedDate?: string | null; diff --git a/simulator-ui/src/main/webapp/app/layouts/navbar/navbar.component.html b/simulator-ui/src/main/webapp/app/layouts/navbar/navbar.component.html index 826dfabef..eed4195ca 100644 --- a/simulator-ui/src/main/webapp/app/layouts/navbar/navbar.component.html +++ b/simulator-ui/src/main/webapp/app/layouts/navbar/navbar.component.html @@ -54,6 +54,18 @@ Message +
  • + + + Message Header + +