Exclude parameter from RequestBody - Swagger - spring-boot

I have two methods in one controller with the same obejct as arguments:
#PostMapping("/pg-import")
public String importProcessGroup(#RequestBody NiFiArguments niFiArguments) {
log.info("Called method importFlow");
#PostMapping("/pg-change-version")
public String changeVersionProcessGroup(#RequestBody NiFiArguments niFiArguments) {
log.info("Called method importFlow");
Pojo object:
#Data
public class NiFiArguments {
private String bucketIdentifier;
private String flowIdentifier;
private String flowVersion;
private String baseUrl;
private String processGroupId;
}
I would like to exclude processGroupId attribute from importProcessGroup method. Is it possible?

One way to do that would be to Subclass NiFiArguments into a separate class.
#Data
public class NiFiArguments {
private String bucketIdentifier;
private String flowIdentifier;
private String flowVersion;
private String baseUrl;
}
#Data
public class NiFiArgumentsWithProcessGroup extends NiFiArguments {
private String processGroupId;
}
Then use the different objects in your two methods.

Related

CQEngine Query nested object using parser.retrieve

I have a nested object like
public class SQSMessage implements Serializable {
private String type;
private boolean isEntity;
private String eventType;
private SystemInfo systemInfo;
private DomainAttributes domainAttributes;
#Data
public static class SystemInfo implements Serializable {
private String identifier;
private String ownedBy;
private Payload payload;
private EntityTags entityTags;
private long createdOn;
private String createdBy;
private long version;
private long lastUpdatedOn;
private String lastUpdatedBy;
private String attrEncKeyName;
#Data
public static class Payload implements Serializable {
private String bucketName;
private String objName;
private String encKeyName;
private byte[] payloadBytes;
private byte[] decryptedBytes;
private byte[] sanitizedBytes;
}
#Data
public static class EntityTags implements Serializable {
private List<Tag> tags;
#Data
public static class Tag implements Serializable {
private String tagName;
private String tagValue;
}
}
}
#Data
public static class DomainAttributes implements Serializable {
private String updatedByAuthId;
private String saveType;
private String docName;
private String ceDataType;
private String year;
private String appId;
private String formSetId;
private String appSku;
private String deviceId;
private String deviceName;
}
}
I would like to query the collection of SQSObjects by applying a filter like
ResultSet<SQSMessage> results = parser.retrieve(indexedSQSMessage, "SELECT * FROM indexedSQSMessage WHERE type='income' and DomainAttributes.saveType in ('endSession', 'cancelled')or (DomainAttributes.countryCode is null or DomainAttributes.countryCode='US'");
Is that possible using CQEngine? if yes.. please send me the examples.
The reason why I want o make that as sql... where clause is dynamic for various use cases.
Your example is more complicated than it needs to be for the question, so I am just skimming it. (Read about SSCCE)
However generally this kind of thing should be possible. See this related question/answer for how to construct nested queries: Can CQEngine query an object inside another object
If you set up attributes like that, you should be able to use them in SQL queries as well as programmatically.

I don't know why the double values are displayed in postman. Is the my code correct?

This is my Book class:
#Entity
#Table(name="book")
public class Book {
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(targetEntity=Category.class,cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JoinColumn(name="CategoryId")
public Category category;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(length=10)
private int book_id;
#Column(length=128)
private String title;
#Column(length=64)
private String author;
#Column(length=200)
private String description;
#Column(length=10)
private int ISBN;
#Column(length=10)
private float price;
private Date published_Date;
#Lob
#Column
#Basic(fetch = FetchType.LAZY)
private byte[] icon;
//getter and setter
}
This is my Category class:
#Entity
#Table(name="category1")
public class Category {
#Id
#Column(length=12)
#GeneratedValue(strategy=GenerationType.AUTO)
public int CategoryId;
#Column(length=50)
public String CategoryName;
//#JsonBackReference
#OneToMany(mappedBy="category")
private List<Book> books = new ArrayList<Book>();
//getter and setter
}
The relationship between them is one to many.
This is my Category Service class
#Service
#Transactional
public class AdminServiceImpl implements AdminService {
#Autowired
private CategoryDao dao;
#Autowired
private BookDao dao1;
#Override
public List<Category> getAllCategory(){
return dao.findAll();
}
}
My Controller class
#RestController
#RequestMapping("/bookstore")
public class CategoryController {
#Autowired
private AdminService service;
#GetMapping("/GetAllCategory")
private ResponseEntity<List<Category>> getAllCategory() {
List<Category> catlist = service.getAllCategory();
return new ResponseEntity<List<Category>>(catlist, new HttpHeaders(), HttpStatus.OK);
}
}
My category table already has data.When i try to display them it is showing double values.
Displaying values using Postman
The Category table in the Database: Database table
Jackson's ObjectMapper uses the Java bean pattern and it expects the following
public class Foo {
public Object bar;
public Object getBar() {...}
public void setBar(Object bar) {...}
}
The getters and setters start with get and set, respectively, followed by the corresponding field name with its first letter capitalized.
Change
CategoryId to categoryId (first letter lowercase)
and
CategoryName to categoryName

Spring Validation Doesn't Work With Generic Types

In my code block, I just want to validate a controller method with Spring boot #Valid annotation for a generic Pair object. But the validation doesn't work for me.
My Controller method looks like this:
#RequestMapping(method = RequestMethod.POST, consumes = "application/json")
public void add(#RequestBody #Valid Pair<AddDto, AddUserDto> pair)
{
...
service.add(pair);
}
Pair object looks like:
public class Pair<F, S>
{
private F first;
private S second;
}
AddDto object looks like:
public class AddDto
{
#NotNull
private String name;
#NotEmpty
private List<String> actionList;
...getters, setters
}
AddUserDto object looks like:
public class AddUserDto
{
#NotNull
private String name;
#NotNull
private Long id;
...getters, setters
}
In this case, validation doesn't work for me. Is there any suggestion?
It has nothing to do with generics. The problem is that the Pair class does not define any validation rules. Try changing it to:
public class Pair<F, S>
{
#Valid
#NotNull
private F first;
#Valid
#NotNull
private S second;
}

Spring Data JPA Redis : Cannot write custom method based query

I have configured Spring Data JPA with Redis and using RedisRepositories with provides methods like find(), findAll() etc. All these methods seem to be working just fine, but I am not able to write my custom method like.
RedisEntity findByGenderAndGrade(String gender, String grade);
RedisEntity is a simple POJO Entity class. If you want any more info, please let me know in messages.
Following is my entity:
#Data
#RedisHash("test1")
public class RedisEntity implements Serializable {
#Id
#GeneratedValue
private String id;
private String name;
private String gender;
private Integer grade;
}
Repository:
#Repository
public interface TestRepository extends JpaRepository<RedisEntity, String> {
List<RedisEntity> findAllByGender(String gender);
List<RedisEntity> findAllByGrade(Integer grade);
}
Service/Controller:
#Override
public List<RedisEntity> getById(String id) {
return testRepository.findById(id); //returns data perfectly.
}
#Override
public List<RedisEntity> getAllByGender(String gender) {
return testRepository.findAllByGender(gender); //returns []
}
#Override
public void saveEntity(RedisEntity redisEntity) {
testRepository.save(redisEntity); // saves it in redis perfectly.
}
Also,
findByGender and findAllByGender both give [], although I can see data in my redis database and save it as well.
As requested by FrançoisDupire,
#Configuration
public class RedisConfig {
#Autowired
private DeploymentProperties deploymentProperties;
private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);
#Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
redisStandaloneConfiguration.setPassword(RedisPassword.of("root"));
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
#Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
Also, I had referred this article: Baeldung article on Spring data redis
As mentioned by #JoshJ and verified by myself and others,
The solution to the problem is:
Adding #Indexed annotation
to all those columns/fields which need to be used with all finds.
#Data
#RedisHash("EmployeeDetails")
public class RedisEntity {
#Id
private String employeeId;
private String firstName;
private String lastName;
#Indexed
private String gender;
#Indexed
private String grade;
}
We have the Spring Data Redis Library which provides the scope to write the custom method.Attaching Sample code.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.8.RELEASE</version>
</dependency>
Entity Definition
#Data
#RedisHash("EmployeeDetails")
public class RedisEntity {
#Id
private String employeeId;
private String firstName;
private String lastName;
private String gender;
private String grade;
}
Repository Definition
#Repository
public interface RedisEntityRepository extends CrudRepository<RedisEntity, String>{
List<RedisEntity> findAllByGenderAndGrade(String gender, String grade);
}
Implementation
#Component
public class RedisEntityImpl implements RedisEntityService {
#Autowired
private RedisEntityRepository redisEntityRepository;
#Override
public List<RedisEntity> getAllByGenderAndGrade(String gender, String grade) {
return redisEntityRepository.findAllByGenderAndGrade(gender,grade);
}
}
Properties
spring.cache.type = redis
spring.redis.host = localhost
spring.redis.port = 6379

Nested Mapping in Mapstruct

I am new to MapStruct API, can anyone say how to do nested Mapping.
I have two classes one is my actual purchaseOrder class, which is known my target class, the other is EDPurchaseOrder class which known as source file, here don't worry about the naming conventions I used, just go with source and target files.
Source Classes
Source class EDCustomerOrder and its reference classes
public class EDCustomerOrder{
private Integer orderID;
private String orderNumber;
private BigDecimal orderTotalQty;
private String UOM;
private PickupDTO pickupPoints;
private Integer supplierID;
private String supplierName;
private String supplierNature;
private EDAddress supplierEDAddress;
}
public class EDPickup{
private List<EDPOItem> items;
}
public class EDAddress{
private String addressLine1;
private String addressLine2;
private String addressLine3;
private String city;
private String state;
private string countryCode;
private String country;
private String postalCode;
}
public class EDPOItem{
private Integer itemID;
private String itemCode;
private String itemDescription;
private Integer itemQuantity;
}
Target classes
Here my target class CustomerOrder and its reference classes
public class CustomerOrder{
private Integer orderID;
private String orderNumber;
private List<Pickup> pickupPoints;
private Supplier supplierDetail;
}
public class Pickup{
private Integer pickupID;
private Integer pickupLocationNumber;
private List<POItem> items;
}
public class POItem{
private Integer itemID;
private String itemCode;
private String itemDescription;
private Integer itemQuantity;
}
public class Supplier{
private Integer supplierID;
private String supplierName;
private String supplierNature;
private Address supplierAddress;
}
public class Address{
private String addressLine1;
private String addressLine2;
private String addressLine3;
private String city;
private String state;
private string countryCode;
private String country;
private String postalCode;
}
So I suppose you have the same hierarchy of objects on the target side, e.g. a SongDTO, LibraryDTO and TrackDTO.
Then you'd have to declare a mapping method for each of those pairs of corresponding objects, configuring it via #Mapping as needed:
public interface MyMapper {
#Mapping(source="name", target="title")
SongDTO songToDto(Song song);
LibraryDTO libraryToDto(Library library);
TrackDTO trackToDto(Track track);
}
Then e.g. the generated implementation of songToDto() will invoke libraryToDto() in order to map the song's library into the song DTO's library DTO.
Also check out the reference guide to learn more.
#Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface CandidateProfessionalEntityAndDTOMapper {
#Mappings({
#Mapping(source = "company.companyId", target = "companyId"),
})
Clazz1
entityToReferencesMapping(Clazz2 entity);
}
public class Clazz2 {
private String companyName;
private Company company;
}
public class Company{
Integer companyId;
}
public class Clazz1 {
private String companyId;
private String companyName;
}

Resources