I'm using wiremock to test a client. One particular test is to verify that the client send one header with a comma separated list of values.
However those values are from an unordered collection. So it can be first,second or second,first and both are valids.
Sadly, I cannot find any ValueMatchingStrategy that can be used for that. containing expect only one value.
I tried to build a custom ValueMatcherStratgey but the isMatchFor method is never called.
new ValueMatchingStrategy(){
#Override
public ValuePattern asValuePattern() {
return new ValuePattern(){
#Override
public boolean isMatchFor(String value) {
return value.contains("first") &&
value.contains("second") &&
value.contains(",");
}
};
}
}
Is there an easier way to verify that a header contains more than one value ? Or how can I create a custom matcher ?
Have you looked at the doc for creating custom matchers?
http://wiremock.org/docs/extending-wiremock/#custom-request-matchers
Related
I need to write a custom LemmaTokenFilter, which replaces and indexes the words with their lemmatized(base) form. The problem is, that I get the base forms from an external API, meaning I need to call the API, send my text, parse the response and send it as a Map<String, String> to my LemmaTokenFilter. The map contains pairs of <originalWord, baseFormOfWord>. However, I cannot figure out how can I access the full value of the text field, which is being proccessed by the TokenFilters.
One idea is to go through the tokenStream one by one when the LemmaTokenFilter is being created by the LemmaTokenFilterFactory, however I would need to watch out to not edit anything in the tokenStream, somehow reset the current token(since I would need to call the .increment() method on it to get all the tokens), but most importantly this seems unnecessary, since the field value is already there somewhere and I don't want to spend time trying to put it together again from the tokens. This implementation would probably be too slow.
Another idea would be to just process every token separately, however calling an external API with only one word and then parsing the response is definitely too inefficient.
I have found something on using the ResourceLoaderAware interface, however I don't really understand how could I use this to my advantage. I could probably save the map in a text file before every indexing, but writing to a file, opening it and reading from it before every document indexing seems too slow as well.
So the best way would be to just pass the value of the field as a String to the constructor of LemmaTokenFilter, however I don't know how to access it from the create() method of the LemmaTokenFilterFactory.
I could not find any help googling it, so any ideas are welcome.
Here's what I have so far:
public final class LemmaTokenFilter extends TokenFilter {
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
private Map<String, String> lemmaMap;
protected LemmaTokenFilter(TokenStream input, Map<String, String> lemmaMap) {
super(input);
this.lemmaMap = lemmaMap;
}
#Override
public boolean incrementToken() throws IOException {
if (input.incrementToken()) {
String term = termAtt.toString();
String lemma;
if ((lemma = lemmaMap.get(term)) != null) {
termAtt.setEmpty();
termAtt.copyBuffer(lemma.toCharArray(), 0, lemma.length());
}
return true;
} else {
return false;
}
}
}
public class LemmaTokenFilterFactory extends TokenFilterFactory implements ResourceLoaderAware {
public LemmaTokenFilterFactory(Map<String, String> args) {
super(args);
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
#Override
public TokenStream create(TokenStream input) {
return new LemmaTokenFilter(input, getLemmaMap(getFieldValue(input)));
}
private String getFieldValue(TokenStream input) {
//TODO: how?
return "Šach je desková hra pro dva hráče, v dnešní soutěžní podobě zároveň považovaná i za odvětví sportu.";
}
private Map<String, String> getLemmaMap(String data) {
return UdPipeService.getLemma(data);
}
#Override
public void inform(ResourceLoader loader) throws IOException {
}
}
1. API based approach:
You can create an Analysis Chain with the Custom lemmatizer on top. To design this lemmatizer, I guess you can look at the implementation of the Keyword Tokenizer;
Such that you can read everything whatever is there inside the input and then call your API;
Replace all your tokens from the API response in the input text;
After that in Analysis Chain, use standard or white space tokenizer to tokenized your data.
2. File-Based Approach
It will follow all the same steps, except calling the API it can use the hashmap, from the files mentioned while defining the TokenStream
Now coming to the ResourceLoaderAware:
It is required when you need to indicate your Tokenstream that resource has changed it has inform method which takes care of that. For reference, you can look into StemmerOverrideFilter
Keyword Tokenizer: Emits the entire input as a single token.
So I think I found the answer, or actually two answers.
One would be to write my client application in a way, that incoming requests are first processed - the field value is sent to the external API and the response is stored into some global variable, which can then be accessed from the custom TokenFilters.
Another one would be to use custom UpdateRequestProcessors, which allow us to modify the content of the incoming document, calling the external API and again saving the response so it's somehow globally accessible from custom TokenFilters. Here Erik Hatcher talks about the use of the ScriptUpdateProcessor, which I believe can be used in my case too.
Hope this helps to anyone stumbling upon a similar problem, because I had a hard time looking for a solution to this(could not find any similar threads on SO)
I have some problems with using Optional.ifPresent statement. I would like to reduce number of NullPointerExceptions, so I decided to use Optional values.
Also I am trying to avoid a ladder of if statements anti-pattern.
So I implemented Optional.isPresent statement. But it's not really that what I expected.
Please look at these listings:
This is a part of my service:
if (getAllComputerProducers().isPresent()) {
if (isComputerProducerAlreadyExist(computerProducer))
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
computerProducerRepository.save(computerProducer);
return new ResponseEntity<>(HttpStatus.CREATED);
getAllComputerProducers function looks like that:
private Optional<List<ComputerProducer>> getAllComputerProducers() {
return Optional.ofNullable(computerProducerRepository.findAll());
}
As you can see, this function returns Optional of List.
The isComputerProducerAlreadyExist function is implemented like that:
private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer) {
return getAllComputerProducers()
.get()
.stream()
.anyMatch(producer -> producer.getProducerName()
.equalsIgnoreCase(computerProducer.getProducerName()));
}
It's so much code and I believe that it could be made simpler.
My target is to reduce code to one line command like:
getAllCimputerProducers().ifPresent(***and-here-some-anyMatch-boolean-function***)
but I can't insert there a function which returns something. How can I do it?
Regards to everyone :)
You could try something like
private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer){
return this.getAllComputerProducers()
.map((List<ComputerProducer> computerProducers) -> computerProducers.stream()
.anyMatch(producer -> producer.getProducerName().equalsIgnoreCase(computerProducer.getProducerName())))
.orElse(Boolean.FALSE);
}
Or instead of loading all computer producers load only the ones using its name.
private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer){
return computerProducerRepository.findByName(computerProducer.getProducerName()).isEmpty();
}
And as far as I know Spring supports also "exist" methods for repositories without even the need to load the Entity.
The following should work
Predicate<ComputerProducer> cpPredicate = producer -> producer.getProducerName()
.equalsIgnoreCase(computerProducer.getProducerName());
boolean compProdExists = getAllCimputerProducers()
.map(list -> list.stream()
.filter(cpPredicate)
.findFirst()))
.isPresent();
You can pass the computerProducer.getProducerName() to repository to get the existing record. Method name will be 'findByProducerName(String producerName)', if producerName has unique constraint, return type will be Optional<ComputerProducer>, else Optional<List<ComputerProducer>>. However, JPA returns empty list instead of null, so optional on list is not required.
Is it possible to define optional parameter when rendering an scala template in Play Framework 2?
My controller looks like this:
public static Result recoverPassword() {
Form<RecoveryForm> resetForm = form(RecoveryForm.class);
return ok(recover.render(resetForm));
// On success I'd like to pass an optional parameter:
// return ok(recover.render(resetForm, true));
}
My Scala template looks like this:
#(resetForm: Form[controllers.Account.RecoveryForm], success:Boolean = false)
Also tried:
#(resetForm: Form[controllers.Account.RecoveryForm]) (success:Boolean = false)
In both cases i got "error: method render in class recover cannot be applied to given types;"
From Java controller you can't omit assignation of the value (in Scala controller or other template it will work), the fastest and cleanest solution in this situation is assignation every time with default value, ie:
public static Result recoverPassword() {
Form<RecoveryForm> resetForm = form(RecoveryForm.class);
if (!successfullPaswordChange){
return badRequest(recover.render(resetForm, false));
}
return ok(recover.render(resetForm, true));
}
Scala template can stay unchanged, as Scala controllers and other templates which can call the template will respect the default value if not given there.
BTW: as you can see, you should use proper methods for returning results from Play's actions, see ok() vs badRequest() also: forrbiden(), notFound(), etc, etc
You can also use flash scope for populating messages and use redirect() to main page after successful password change, then you can just check if flash message exists and display it:
public static Result recoverPassword() {
...
if (!successfullPaswordChange){
return badRequest(recover.render(resetForm, false));
}
flash("passchange.succces", "Your password was reseted, check your mail");
return redirect(routes.Application.index());
}
in ANY template:
#if(flash.containsKey("passchange.succces")) {
<div class="alert-message warning">
<strong>Done!</strong> #flash.get("passchange.succces")
</div>
}
(this snippet is copied from Computer Database sample for Java, so you can check it on your own disk)
I am trying to make a custom filter in Lucene which simply recognizes whether two consequent words in a text start with a capital letter and have the rest as lower case, in which case the two words are to be joined as one token.
The overriden incrementToken method has the following code
#Override
public boolean incrementToken() throws IOException {
if(!input.incrementToken()){
return false;}
//Case were the previous token WAS NOT starting with capital letter and the rest small
if(previousTokenCanditateMainName==false)
{
if(CheckIfMainName(termAtt.term()))
{
previousTokenCanditateMainName=true;
tempString=this.termAtt.term() ; /*This is the*/
// myToken.offsetAtt=this.offsetAtt; /*Token i need to "delete"*/
tempStartOffset=this.offsetAtt.startOffset();
tempEndOffset=this.offsetAtt.endOffset();
return true;
}
else
{
return true;
}
}
//Case were the previous token WAS a Proper name (starting with Capital and continuiing with small letters)
else
{
if(CheckIfMainName(termAtt.term()))
{
previousTokenCanditateMainName=false;
posIncrAtt.setPositionIncrement(0);
termAtt.setTermBuffer(tempString+TOKEN_SEPARATOR+this.termAtt.term());
offsetAtt.setOffset(tempStartOffset, this.offsetAtt.endOffset());
return true;
}
else
{
previousTokenCanditateMainName=false;
return true;
}
}
}
My question is how once i find the first Token that meets my requirements can i "ignore" it.
Currently the code works perfectly with joining the two tokens but i also get an extra token with the first one of the two that I identified.
I tried using the same method setEnableIncrementsPosition(true) as does the built-in stopFilter but in that case my filter needs to be a TokenFilter type which does not allow me to override the incrementToken method.
I hope i phrased my problem properly
You might have a custom method:
private void tokenize()
where you do the splitting and the custom joins. The resulting List<String> tokens need to be held as an attribute of the tokenizer.
In the incrementToken method you simply check if this attribute is null and initialize it if necessary.
You also need to add the tokens in the incrementToken() method to the termAttribute
termAttribute.append(tokens.get(tokenIndex));
this includes that your Tokenizer needs to have an attribute like this:
private CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);
Probably you need also some fine tuning. But thats only a draft on how this can be achieved in a pretty simple way.
I set up ext direct for my Spring MVC app using extdirectspring. I am able to retrieve primitives and Strings and use them in ext.js. When I try to retrieve a list of objects, I am getting "undefined" on the javascript side. Is there anything special that I need to do to the Person class to get it to work?
I annotated the following code:
#ExtDirectMethod(ExtDirectMethodType.STORE_READ)
#Override
public Collection<Person> getPeople(String groupId) {
Group group = GroupManager.getGroup(groupId);
return group.getPeopleList();
}
This is what I am using on the client side:
directory.getPeople(id, function(result) {
console.log(result);
});
Here is what app.js looks like:
Ext.ns('Ext.app');
Ext.app.REMOTING_API = {
"actions":{
"directory":[{
"name":"getID","len":0
},{
"name":"getPeople","len":1
}
]},
"type":"remoting",
"url":"/test/action/router"
};
Have you tried using the ExtDirectStoreResponse class? It does use a collection but also manages some useful values for use in the store.
#ExtDirectMethod(ExtDirectMethodType.STORE_READ)
public ExtDirectStoreResponse<Person> load()
{
Group group = GroupManager.getGroup(groupId);
Collection<Person> people = group.getPeopleList();
return new ExtDirectStoreResponse<Person>(people.size(), people);
}
This is the approach to use when using the STORE_READ. That method annotation is expecting the request to come in matching values in the ExtDirectStoreReadRequest class. This is the reference to use when doing a store read. https://github.com/ralscha/extdirectspring/wiki/Store-Read-Method
Also, instead of calling the method directly, you would set up an ExtJs store and call
store.load();