How to pass varargs in Spring shell with kotlin - spring

I am trying to write a spring shell app and pass some var args. Basicaly I want to pass
fetch FA-207542 FA-207984 FA-211258 FA-202298
Documentation here is still TBD
#ShellMethod(value = "fetches all pic related data for processing")
fun fetch(vararg tickets: String) {
println("number of tickets is ${tickets.size}")
}
results
shell:>fetch FA-207542 FA-207984 FA-211258 FA-202298
number of tickets is 1
I've tried using a StringArray and I get an error:
fun fetch(tickets: StringArray) {
println("number of tickets is ${tickets.size()}")
}
error:
shell:>fetch FA-207542 FA-207984 FA-211258 FA-202298
Parameter specified as non-null is null: method FetchCommand.fetch, parameter tickets
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

With java (sry), I got this working:
#ShellComponent
public class MyCommands {
#ShellMethod
public String fetch(String... tickets) {
return String.format("Number of tickets is %d.", tickets.length);
}
}
then:
shell:>fetch --tickets FA-207542 FA-207984 FA-211258 FA-202298
Number of tickets is 4.
shell:>
Same results achieved with: #ShellCommand(arity = -1) resp. arity = Integer.MAX_VALUE.#

Related

How to pass 2 or more variables using #PathParam in spring mvc? and suppose if I want to test it out using postman how to do that?

I'm trying to fetch value from db using JPA repository method
product findByIdNumberOrCifNumber(String idNumber , String cifNumber);
service class logic:-
public ResponseModel FindByCivIDOrCifNumber(String idNumber,String cifNumber) {
ResponseModel responseModel = new ResponseModel();
Optional<product> civId = Optional.ofNullable(productRepos.findByIdNumber(idNumber));
if (civId.isPresent()) {
responseModel.setResponse(productRepos.findByIdNumberOrCifNumber(idNumber,cifNumber));
} else {
errorModel errorModel1 = new errorModel();
enter image description here errorModel1.setErrorCode(productConstant.INVALID_REQUEST);
errorModel1.setErrorDescription("Requested Civil Id or CifNUmber is not present");
responseModel.setErrorModel(errorModel1);
}
return responseModel;
}
controller class:-
#GetMapping("/getByCifNoOrGetByIdNo")
public ResponseModel getProductByCifNoOrGetByIdNo(#RequestParam String idNumber,#RequestParam String cifNumber ) {
return productService.FindByCivIDOrCifNumber(idNumber,cifNumber);
}
post man:-
kindly help me out how to make it work:)
If you are looking for an answer to pass two or more path variables and test it with postman, you can try this.
#GetMapping("/api/mapping-name/{variable1}/{variable2}")
Here you will be getting two path variables which you can access by the syntax
#PathVariable("variable1") datatype variableName
Now in postman request url you can simply give the respective url, lets say:
https://localhost8080/api/mapping-name/:variable1/:variable2
which automaticaly will give you a key value section in the path variables section in the params with prepopulated key names as per the name you have given. In this case variable1 & variable2.
Give the respective value and it should work.

Unable to cast object of type ‘System.String’ to type ‘AuthBotES.ReturnIntents’

Currently I had integrate LUIS with Bot Framework v4.
When I search for result match with Intent,
the Bot return me with this Error:
Error : Unable to cast object of type ‘System.String’ to type ‘AuthBotES.ReturnIntents’.
My Source code as below:
if (stepContext.Result != null)
{
var result = (ReturnIntents)stepContext.Result;
var msg = $"{result}";
await stepContext.Context.SendActivityAsync(MessageFactory.Text(msg), cancellationToken);
}
and my ReturnIntents classes.
public class ReturnIntents
{
public string Intent { get; set; }
public double Score { get; set; }
public string Entities { get; set; }
}
A few issues here:
The first code block you posted looks to be for handling the result of a dialog, not for processing a LUIS result.
The cast from string to ReturnIntents will always fail.
Even if your cast of stepContext.Result to ReturnIntents did work, your msg variable would only contain namespace.to.class.ReturnIntents (the string representation of the object type, not the string representation of the objects properties.
Your msg variable is redundant.
I will address these in the order that they occur.
1 - Incorrect code block
This block of code looks suspiciously like code used to process a dialog and here e.g.:
var result = (bool)stepContext.Result;
Rather than the code for handling a LUIS result e.g.:
var dispatchResult = await cognitiveModels.DispatchService.RecognizeAsync(dc.Context, CancellationToken.None);
2 - Casting error
The error is telling you that it doesn't know how to convert a string object to a ReturnIntents object. To convert the string to your object you could use a couple of methods:
Use the NewtonSoft.Json NuGet package to allow you to turn the JSON string into your object as explained here.
2) A user defined type conversion as detailed in the official docs here and explained in this answer.
This error is a red herring in terms of your solution because I believe you're accidentally copied in the wrong block of code.
3 - Incorrect ToString behaviour
To get the string value of a ReturnIntents you will need to override the ToString method for the class and write your own custom implementation.
4 - Redundant cast
This:
// We know that this cast fails, and that stepContext.Result is a string
var result = (ReturnIntents)stepContext.Result;
// This will only return <namespace.path>.ReturnIntents (if the cast above works)
var msg = $"{result}";
// Passing in message msg isn't required, we can just pass in stepContext.Result
await stepContext.Context.SendActivityAsync(MessageFactory.Text(msg), cancellationToken);
Becomes:
var result = stepContext.Result;
await stepContext.Context.SendActivityAsync(MessageFactory.Text(result), cancellationToken);
So what I actually think you actually want is the following:
var dispatchResult = await cognitiveModels.DispatchService.RecognizeAsync<ReturnIntents>(dc.Context, CancellationToken.None);
Which will send the user's input off to LUIS, and deserialize the response into a ReturnIntents object.
Edit to provide solution to the OP
The ExecuteLuisQuery method called here, and defined here returns a ReturnIntents object.
This object is passed as an option to the ReturnIntentDialog here. Because this comes through as an instance of the object type you have a few options inside your FinalStepAsync method here to turn your options object into a ReturnIntents object.:
Casting
ReturnIntents returnIntents = null;
if (stepContext.Options is ReturnIntents)
{
returnIntents = (ReturnIntents)stepContext.Options;
}
Deserializing
using Newtonsoft.Json;
ReturnIntents returnIntents = null;
if (stepContext.Options is ReturnIntents)
{
returnIntents = JsonConvert.DeserializeObject<ReturnIntents>(JsonConvert.SerializeObject(stepContext.Options));
}

How to search exact record by asp.net web api with help of lamda expresion

I am facing a problem in searching a exact record by LINQ query method in ASP.NET Web API my controller. This is my code:
[HttpGet]
[Route("api/tblProducts/AllProductbySearch/{SearchText}")]
[ResponseType(typeof(IEnumerable<tblProduct>))]
public IHttpActionResult AllProductbySearch(string SearchText)
{
IEnumerable<tblProduct> tblProduct = db.tblProducts.Where(x=>x.PrdKeyword.Contains(SearchText)).AsEnumerable();
if (tblProduct == null)
{
return NotFound();
}
return Ok(tblProduct);
}
In this I am searching the record with value have keyword column and getting the result but problem is that it is not giving exact result for example if in database two record have keyword column value like shirt and another have Tshirt
Then if I pass shirt in SearchText or pass tshirt in SearchText it is giving both record while I want one record which exact match with SearchText. Please help me
My updated action method code is:
[HttpGet]
[Route("api/tblProducts/AllProductbySearch/{SearchText}")]
[ResponseType(typeof(IEnumerable<tblProduct>))]
public IHttpActionResult AllProductbySearch(string SearchText)
{
IEnumerable<tblProduct> tblProduct = db.tblProducts.Where(x => CheckWord(x.PrdKeyword, SearchText)).AsEnumerable();
if (tblProduct == null)
{
return NotFound();
}
return Ok(tblProduct);
}
private bool CheckWord(string source, string searchWord)
{
var punctuation = source.Where(Char.IsPunctuation).Distinct().ToArray();
var words = source.Split().Select(x => x.Trim(punctuation));
return words.Contains(searchWord, StringComparer.OrdinalIgnoreCase);
}
But is throwing the same error - http 500
EDITED 2
Added ToList() - db.tblProducts.ToList().... In this case we retrieve all data from Data Base and filter them in memory. If we don't retrieve all data before filtering .Net tries to create request to SQL with filtration and can't because there are .Net methods as CheckWord().
I think we can get required data without retrieving all table into memory, but don't know how. As variant we should write specific Stored Procedure and use it. Get all into memory is a simplest way (but not faster)
Please, look at this post Get only Whole Words from a .Contains() statement
Actually, for your case solution can be:
IEnumerable<tblProduct> tblProduct = db.tblProducts.ToList()
.Where(x => Regex.Match(x.PrdKeyword, $#"\b{SearchText}\b", RegexOptions.IgnoreCase).Success)
.AsEnumerable();
Option 2. Without regexp:
public static bool CheckWord(string source, string searchWord)
{
if (source == null)
return false;
var punctuation = source.Where(Char.IsPunctuation).Distinct().ToArray();
var words = source.Split().Select(x => x.Trim(punctuation));
return words.Contains(searchWord, StringComparer.OrdinalIgnoreCase);
}
[HttpGet]
[Route("api/tblProducts/AllProductbySearch/{SearchText}")]
[ResponseType(typeof(IEnumerable<tblProduct>))]
public IHttpActionResult AllProductbySearch(string SearchText)
{
IEnumerable<tblProduct> tblProduct = db.tblProducts.ToList()
.Where(x => CheckWord(x.PrdKeyword, SearchText)).AsEnumerable();
if (tblProduct == null)
{
return NotFound();
}
return Ok(tblProduct);
}
Sorry, I'm from phone now, there can be mistakes here. Will try it in 3-4 hour
You are making a simple mistake. You just need to use .Equals instead of .Contains.
When you use Contains .Net will check if the input string is part of the main string. Whereas Equals will check for exact match.
var mainStr = “long string with Hello World”;
var inputStr = “Hello”;
var status = mainStr.Contains(inputStr);
// Value of status is `true`
status = mainStr.Equals(inputStr);
// Value of status is `false`
So your code should look like this:
IEnumerable<tblProduct> tblProduct = db.tblProducts.Where(x=>x.PrdKeyword.Equals(SearchText)).AsEnumerable();
.Equals can also help you find exact match with or without having case-sensitive check in force. The single-parameterised method does a Case-Sensitive check whereas the other overridden methods of .Equals gives you an opportunity to ignore it.
Hope this helps!

Issues with Contentful SDK code after migration

See the code below I am having issues with. I have added most of the function even tho I am only getting the error in line 3. Just to give a better understanding of what I am trying to do.
func getTopArticles(_ vc: ArticleListViewController, subCatId: String) {
var articleDict = [String: Article]()
Constants.CLIENT.fetchEntries(["content_type":Constants.CONTENT_TYPE_ARTICLE,
"fields.top10Listing.sys.id":subCatId, "order":Constants.SORT_CREATED_AT_DESCENDING]) { //Getting error here
switch $0 {
case let .success(articleResult):
if articleResult.items.isEmpty {
vc.noTopArticlePresent()
}
else{
for articleEntry in articleResult.items {
let article = Article (entry:articleEntry)
vc.art.append(article)
// store into search cache
Constants.ARTICLE_CACHE.fetch(key: "articles").onSuccess({ (result) in
if let dictValue = result as? [String:Article]
{
articleDict = dictValue
articleDict[article.articleId] = article
}
Constants.ARTICLE_CACHE.set(value: articleDict, key: "articles")
}).onFailure({ (error) in
Constants.ARTICLE_CACHE.set(value: articleDict, key: "articles")
})
}
Constants.CACHE.set(value: NSKeyedArchiver.archivedData(withRootObject: vc.art), key: subCatId)
DispatchQueue.main.async {
vc.dothis()
}
}
}
}
Getting error in line 3. See error below
Argument labels '(__:,_:)' do not match any available overloads
you are missing the argument label matching for the method call.
The function signature is fetchEntries(matching:completion)
Taking your example above, and adding the our call would look like the following:
Constants.CLIENT.fetchEntries(matching:
["content_type": Constants.CONTENT_TYPE_ARTICLE,
"fields.top10Listing.sys.id":subCatId, "order":Constants.SORT_CREATED_AT_DESCENDING]) { (result: Result<ArrayResponse<Entry>>) in // Or anonymous argument $0 as you were using in your example.
Generally, if you see an error telling you argument labels don't match, you can find the declaration in the source and compare to see if you have a mismatch with the naming of your arguments being passed in. See more about argument labels and parameter names in Swift here.

How to Access Mono<T> While Handling Exception with onErrorMap()?

In data class I defined the 'name' must be unique across whole mongo collection:
#Document
data class Inn(#Indexed(unique = true) val name: String,
val description: String) {
#Id
var id: String = UUID.randomUUID().toString()
var intro: String = ""
}
So in service I have to capture the unexpected exception if someone pass the same name again.
#Service
class InnService(val repository: InnRepository) {
fun create(inn: Mono<Inn>): Mono<Inn> =
repository
.create(inn)
.onErrorMap(
DuplicateKeyException::class.java,
{ err -> InnAlreadyExistedException("The inn already existed", err) }
)
}
This is OK, but what if I want to add more info to the exceptional message like "The inn named '$it.name' already existed", what should I do for transforming exception with enriched message.
Clearly, assign Mono<Inn> to a local variable at the beginning is not a good idea...
Similar situation in handler, I'd like to give client more info which derived from the customized exception, but no proper way can be found.
#Component
class InnHandler(val innService: InnService) {
fun create(req: ServerRequest): Mono<ServerResponse> {
return innService
.create(req.bodyToMono<Inn>())
.flatMap {
created(URI.create("/api/inns/${it.id}"))
.contentType(MediaType.APPLICATION_JSON_UTF8).body(it.toMono())
}
.onErrorReturn(
InnAlreadyExistedException::class.java,
badRequest().body(mapOf("code" to "SF400", "message" to t.message).toMono()).block()
)
}
}
In reactor, you aren't going to have the value you want handed to you in onErrorMap as an argument, you just get the Throwable. However, in Kotlin you can reach outside the scope of the error handler and just refer to inn directly. You don't need to change much:
fun create(inn: Mono<Inn>): Mono<Inn> =
repository
.create(inn)
.onErrorMap(
DuplicateKeyException::class.java,
{ InnAlreadyExistedException("The inn ${inn.name} already existed", it) }
)
}

Resources