springdoc-openapi-ui doesn't read boolan values for some settings - spring

I use springdoc-openapi-ui 1.6.11 in combination with springdoc-openapi-data-rest 1.6.11. My problem is that these plugins don't care about some boolean settings when using the Swagger UI or creating the yaml.
For example:
#PostMapping(path = "/testpath")
#Operation(summary = "This does something", description = "It does this")
public BasicDto<BasicClass> doSomethingBasic(
#Parameter(description = "a description", required = false, in = ParameterIn.QUERY) String param){
}
It sets the parameter required anyway and I don't know why.
Another example:
#PostMapping(path = "/testpath")
#Operation(summary = "This does something", description = "It does this", responses = {
#ApiResponse(responseCode = "200", description = "Another discription", useReturnTypeSchema =
true, content = #Content(mediaType = "application/json"))
}
)
public BasicDto<BasicClass> doSomethingBasic(String param){
}
It does not use the return type as schema. But if I write it as in the next example, it uses the return type as schema.
#PostMapping(path = "/testpath")
#Operation(summary = "This does something", description = "It does this", responses = {
#ApiResponse(responseCode = "200", description = "Another discription", useReturnTypeSchema =
false)
}
)
public BasicDto<BasicClass> doSomethingBasic(String param){
}
Has anyone similar problems?

Related

Exceptions not captured in opencsv parsing

I'm trying to parse a csv file and map it onto a data class. I've setup some validations for the columns and I'm testing it by sending incorrect values for those columns. opencsv throws a generic exception
Basic instantiation of the given bean type (and subordinate beans created through recursion, if applicable) was determined to be impossible.
Code details
Data class:
data class UserInfo(
#CsvBindByName(column = "Id", required = true) val id: Long,
#CsvBindByName(column = "FirstName", required = true) val firstName: String,
#CsvBindByName(column = "LastName", required = true) val lastName: String,
#CsvBindByName(column = "Email", required = true) val email: String,
#CsvBindByName(column = "PhoneNumber", required = true) val phoneNumber: String,
#PreAssignmentValidator(
validator = MustMatchRegexExpression::class, paramString = "^[0-9]{10}$")
#CsvBindByName(column = "Age", required = true)
val age: Int
)
csv parsing logic
fun uploadCsvFile(file: MultipartFile): List<UserInfo> {
throwIfFileEmpty(file)
var fileReader: BufferedReader? = null
try {
fileReader = BufferedReader(InputStreamReader(file.inputStream))
val csvToBean = createCSVToBean(fileReader)
val mappingStrategy: HeaderColumnNameMappingStrategy<Any> =
HeaderColumnNameMappingStrategy<Any>()
mappingStrategy.type = UserInfo::class.java
val userInfos = csvToBean.parse()
userInfos.stream().forEach { user -> println("Parsed data:$user") }
csvToBean.capturedExceptions.stream().forEach { ex -> println(ex.message) }
return userInfos
} catch (ex: Exception) {
throw CsvImportException("Error during csv import")
} finally {
closeFileReader(fileReader)
}
}
private fun createCSVToBean(fileReader: BufferedReader?): CsvToBean<UserInfo> =
CsvToBeanBuilder<UserInfo>(fileReader)
.withType(UserInfo::class.java)
.withThrowExceptions(false)
.withIgnoreLeadingWhiteSpace(true)
.build()
I'm looking for the proper error message for the validation / missing field so that I can communicate it to the error response.

Kotlin iterator to check if payload list have an id/projectId or not, returning false when there is no attributes?

I have an issue where i have a method where i am checking the payload has the attributes or not. When i am sending my payload i want to check that the user dont have inserted attributes which not allowed in the payload.
My entity class:
#Entity
data class ProjectAssociated(
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(columnDefinition = "BINARY(16)")
var id: UUID? = null,
#Column(columnDefinition = "BINARY(16)")
var projectId: UUID? = null,
#Column(columnDefinition = "BINARY(16)")
var associatedProjectId: UUID? = null
)
My Service class:
fun addAssociatedProjectByProjectId(
projectId: UUID,
projectAssociatedList: MutableList<ProjectAssociated>
): MutableList<ProjectAssociated> {
if (projectAssociatedList.isNotEmpty()) {
println(projectAssociatedList)
if (!projectAssociatedList.map { it.id }.isNullOrEmpty()) {
val errorMessage = "Not allowed to provide parameter 'id' in this request"
throw UserInputValidationException(errorMessage)
}
if (!projectAssociatedList.map { it.projectId }.isNullOrEmpty()) {
val errorMessage = "Not allowed to provide parameter 'projectId' in this request"
throw UserInputValidationException(errorMessage)
}
val checkIds = projectAssociatedList.map {
projectRepository.existsById(it.associatedProjectId)
}
if (checkIds.contains(false)) {
val errorMessage = "One or more ID 'associatedProjectId' not exists"
throw UserInputValidationException(errorMessage)
}
}
return projectAssociatedList.map {
projectAssociatedRepository.save(
ProjectAssociated(
null,
projectId,
it.associatedProjectId
)
)
}.toMutableList()
}
My Controller class:
#ApiOperation("Add associated Projects to a specific Project")
#PostMapping(path = ["/project-associated"], consumes = [MediaType.APPLICATION_JSON_VALUE])
fun createAssociatedProjectList(
#ApiParam("The id of the Project", required = true)
#RequestParam("id")
id: UUID,
#ApiParam("JSON object representing the ProjectAssociated")
#RequestBody projectAssociated: MutableList<ProjectAssociated>
): ResponseEntity<WrappedResponse<MutableList<ProjectAssociated>>> {
val createdProjectAssociatedList = projectService.addAssociatedProjectByProjectId(id, projectAssociated)
return ResponseEntity
.status(201)
.location(URI.create("$id/project-associated"))
.body(
ResponseDto(
code = 201,
data = PageDto(list = mutableListOf(createdProjectAssociatedList))
).validated()
)
}
But when i try to send this payload with the project id in #RequestParam:
[
{
"associatedProjectId": "7fe40f90-5178-11ea-9136-1b65a920a5d9"
},
{
"associatedProjectId": "7fe8aaaa-5178-11ea-9136-1b65a920a5d9"
}
]
I have a custom exception where i tell the user if projectId or the id is in the payload that is now allowed to have it in the payload. When i try to POST the payload example above it tells me that projectId or id is in the request? How can that be?
I also printed out the list before if checks:
[ProjectAssociated(id=null, projectId=null, associatedProjectId=7fe40f90-5178-11ea-9136-1b65a920a5d9), ProjectAssociated(id=null, projectId=null, associatedProjectId=7fe8aaaa-5178-11ea-9136-1b65a920a5d9)]
What am I doing wrong?
Thanks for the help!
In the block projectAssociatedList.map { it.id } you are mapping your list to something like [null, null] and it is not null or empty.
So, the complete condition !projectAssociatedList.map { it.id }.isNullOrEmpty() returns true.
If you want to continue using the same logic, you should use !projectAssociatedList.mapNotNull { it.id }.isNullOrEmpty() instead.
The mapNotNull function will filter the null values and output a list just with the not null values. If there is only null values, the list will be empty.
But, a simpler and expressive way to check if there is any not null attribute in a list of objects could be projectAssociatedList.any { it.id != null }

Kotlin entered value not searching database

We have worked on this code to error trap a value entered in a Edit Text field
When the value is entered correctly we are informed that the entered value does not match
BUT if we select the value from a recycler view list and populate the Edit Text field with the value the search tells us we have a match
Here is the code for the search in the DBHelper
fun getOneName(id: Int): Contact? {
val db = this.writableDatabase
val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $colId = ?"
db.rawQuery(selectQuery, arrayOf(id.toString())).use { // .use requires API 16
if (it.moveToFirst()) {
val result = Contact(id = 0,name ="")
result.id = it.getInt(it.getColumnIndex(colId))
result.name = it.getString(it.getColumnIndex(colName))
return result
}
}
return null
}
We used this for the Model Class our first time using data class as just plain class
data class Contact (
var id: Int,
var name: String
)
And here is the button click that manages the search
btnGetID.setOnClickListener {
if(etPerson.text.toString().trim().isNullOrEmpty()){
message("Enter Contact Name")
return#setOnClickListener
}
var numeric = true
var string = etPerson.text.toString().trim()
numeric = string.matches(".*\\d+.*".toRegex())
if(numeric){
message("No NUMBERS")
return#setOnClickListener
}
val dbManager = DBHelper(this)
var name = etPerson.text.toString()
//val contact = dbManager.getOneName(name)
val contact = dbManager.getOneName(id.toInt())
if(contact?.name.equals(name)){
println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contact ID= "+contact)
etPerson.setText("The contact name is $name the ID is "+contact?.id.toString())
}else{
etPerson.setText("Name NOT = to $name and the ID is "+contact?.id.toString())
}
}
We know the name Sally is in the DB if we type Sally in the else statement shows Name NOT = bla
If we select Sally from the Recyclerview List the first statement shows The contact name bla bla
Kotlin 1.2.71 API 27
Our question is why is the hand typed name failing if it mataches?
HERE IS THE CORRECT CODE FOR THE DBHelper
fun getOneName(name: String): Contact? {
val db = this.writableDatabase
val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $colName = ?"
db.rawQuery(selectQuery, arrayOf(name)).use { // .use requires API 16
if (it.moveToFirst()) {
val result = Contact(id = 0,name ="")
result.id = it.getInt(it.getColumnIndex(colId))
result.name = it.getString(it.getColumnIndex(colName))
return result
}
}
return null
}

Best way for store data into client

My Put method is as follows:
public void Post([FromBody]RavenUserView view)
{
if (ModelState.IsValid)
{
var request = new CreateUserRequest();
request.ID = view.ID;
request.Name = view.Name;
request.UserName = view.UserName;
request.Password = EncryptionDecryption.EncryptString(view.Password);//Encrypt The Password
request.Email = view.Email;
request.Phone = view.Phone;
request.Country = "x";
request.Note = "y";
request.IsActive = view.IsActive;
request.Creator = view.Creator;
request.CreationDate = DateTime.UtcNow;
request.ModificationDate = DateTime.UtcNow;
request.Remarks = "z";
var response = _facade.CreateUser(request);
SaveUserDetailsToCookie(response.RavenUser.ID, response.RavenUser.UserName, EncryptionDecryption.DecryptString(response.RavenUser.Password));//Cookie should be stored Decrypted Format
HttpContext.Current.Session[SessionDataKey.UserId.ToString()] = response.RavenUser.ID.ToString();
HttpContext.Current.Session[SessionDataKey.UserName.ToString()] = response.RavenUser.UserName;
}
}
But When I run my project and try to save my information then it throw me an exception "Object Reference is not set to the reference of an object"
I am using Web Api as my controller class.
After reading various documents I found that Api is stateless. Now how can I store my user information for further use.
Use:
public void Post([Bind(Include = "ID,Name,UserName,....")] CreateUserRequest request)
{
if(ModelState.IsValid)
{
var response = _facade.CreateUser(request);
SaveUserDetailsToCookie(response.RavenUser.ID, response.RavenUser.UserName, EncryptionDecryption.DecryptString(response.RavenUser.Password));//Cookie should be stored Decrypted Format
HttpContext.Current.Session[SessionDataKey.UserId.ToString()] = response.RavenUser.ID.ToString();
HttpContext.Current.Session[SessionDataKey.UserName.ToString()] = response.RavenUser.UserName;
}
}

How to Get the Array of data from json array using WEB API in mvc3?

I have create web services using Web Api in mvc3,in this i want get the data from json. Json Result like this
{"order": {
"locationid": "1",
"deviceidentifier": "XXXXXXXXXXXXXXXXXXXXXXX",
"ordercontactname": "XXXXXXXXXXXXXXXXXXXXXXX",
"ordercontactphone": "XXXXXXXXXXXXXXXXXXXXXXX",
"ordercontactemail": "XXXXXXXXXXXXXXXXXXXXXXX",
"shipaddress1": "17 Brookfield",
"shipaddress2": "Suite 17",
"shipcity": "Irvine",
"shipstate": "CA",
"shipzipcode": "92604",
"shipphonenumber": "9493742114",
"shipemail": "Info#mail.com",
"shipmethod": "pickup",
"billingfirstname":"Tester",
"billinglastname":"test",
"billingmiddleinitial":"S",
"billingaddress":"field",
"billingcity":"Sample",
"billingstate":"SM",
"billingzipcode":"523201",
"billingphonenumber": "1234567891",
"billingemail": "",
"paytype":"creditcard",
"amount"="10.50",
"acctno"="123456789987",
"exproute"="0114",
"coupon"="X2323",
"notes"="",
"items": [
{"itemid":"1","quantity":"1","price":"2.5","notes":"make it spicy"},
{"itemid":"4","quantity":"2","price":"4.5","notes":""},
{"itemid":"3","quantity":"1","price":"1.5","notes":""}
]
}}
for this i have create Poco class and i get Order data using poco class, but i can't get the items array data how can i get items data
Here is my code
public List<Message> PlaceOrder(PlaceOrder order)
{
// List<PlaceOrder> entities = (List<PlaceOrder>)JavaScriptConvert.DeserializeObject(json, typeof(List<PlaceOrder>));
int PayOrderID = 0;
List<Message> Result;
Result = new List<Message>();
try
{
Order objOrder = new Order();
PayHist objPayhis = new PayHist();
objOrder.LocationId = order.LocationId;
objOrder.DeviceIdentifier = order.DeviceIdentifier;
objOrder.OrderContactName = order.OrderContactName;
objOrder.OrderContactPhone = order.OrderContactPhone;
objOrder.OrderContactEmail = order.OrderContactEmail;
string guid = Guid.NewGuid().ToString();
objOrder.ShipMethod = order.ShipMethod;
objOrder.ShippingDate = Convert.ToDateTime(order.PickupDate);
objOrder.OrderGuid = guid;
entities.AddObject("Orders", objOrder);
entities.SaveChanges();
int orderId = objOrder.OrderId;
PayOrderID = orderId;
objPayhis.OrderId = orderId;
objPayhis.PayType = order.ShipMethod;
objPayhis.Amount = float.Parse(order.Amount);
entities.AddObject("PayHists", objPayhis);
entities.SaveChanges();
JavaScriptSerializer ser = new JavaScriptSerializer();
// Order foo = ser.Deserialize<Order>(json);
Message objMessage = new Message();
objMessage.Messagevalue = "Sucess";
Result.Add(objMessage);
return Result;
}
Please help me..
Try this (you need to fix your Json by replacing the "=" signs by ":" signs" before):
[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(JsonValue json) {
JsonValue order = json["order"];
JsonArray items = (JsonArray) order["items"];
JsonValue item1 = items[0];
var notes1 = item1["notes"];
return new HttpResponseMessage(HttpStatusCode.OK);
}

Resources