Wiremock match request POST by params - post

I have a simple POST request sending params using application/x-www-form-urlencoded encoding.
Looking in the wiremock docs I can't find a way to match the request by the params values, something like the querystring match I mean.
Furthermore it seems also impossible to contains for the body, nor to match the entire body in clear (just as base64).
Is there a way to match this kind of requests?

Another option that I found was to use contains for Stubbing Content-Type: application/x-www-form-urlencoded
{
"request": {
"method": "POST",
"url": "/oauth/token",
"basicAuthCredentials": {
...
},
"bodyPatterns": [
{
"contains": "username=someuser"
}
]
},
"response": {
....
}
}

With classic wiremock you can use bodyPatterns' matchers and regular expressions:
for example:
...
"request": {
"method": "POST",
"url": "/api/v1/auth/login",
"bodyPatterns": [
{
"matches": "(.*&|^)username=test($|&.*)"
},
{
"matches": "(.*&|^)password=123($|&.*)"
}
]
},

I had a similar problem - I wanted to check the exact parameters , but without patterm magic (so easier to maintain). As a workaround, I created a helper class :
import java.util.Iterator;
import java.util.LinkedHashMap;
public class WireMockUtil {
public static String toFormUrlEncoded(LinkedHashMap<String, String> map) {
if (map == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = map.get(key);
appendFormUrlEncoded(key,value,sb);
if (it.hasNext()) {
sb.append('&');
}
}
return sb.toString();
}
public static String toFormUrlEncoded(String key, String value) {
StringBuilder sb = new StringBuilder();
appendFormUrlEncoded(key, value,sb);
return sb.toString();
}
public static void appendFormUrlEncoded(String key, String value, StringBuilder sb) {
sb.append(key).append('=');
if (value != null) {
sb.append(value);
}
}
}
Inside the Wiremock test you can use it via:
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
...
withRequestBody(equalTo(WireMockUtil.toFormUrlEncoded(map))).
Or check only dedicated parts by containing:
withRequestBody(containing(WireMockUtil.toFormUrlEncoded("key","value1"))).

You could try https://github.com/WireMock-Net/WireMock.Net
Matching query parameters and body can be done with this example json:
{
"Guid": "dae02a0d-8a33-46ed-aab0-afbecc8643e3",
"Request": {
"Url": "/testabc",
"Methods": [
"put"
],
"Params": [
{
"Name": "start",
"Values": [ "1000", "1001" ]
},
{
"Name": "end",
"Values": [ "42" ]
}
],
"Body": {
"Matcher": {
"Name": "WildcardMatcher",
"Pattern": "test*test"
}
}
}
}

Related

index percolate queries using spring data jpa

Here is my Dto for percolator query class.
#Data
#Document(indexName = "#{#es.indexName}")
#Builder(builderClassName = "RuleBuilder")
public class Rule {
#Id
private String id = UUID.randomUUID().toString();
private QueryBuilder query;
private RuleDataDto data;
public static class RuleBuilder {
private String id = UUID.randomUUID().toString();
}
}
Index Mapping
{
"mappings": {
"properties": {
"query": {
"type": "percolator"
},
"data": {
"properties": {
"subType": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"type": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"content": {
"type": "text"
}
}
}
}
based on criteria I am generating queries and trying to index those to percolator. but getting below exception
query malformed, no start_object after query name
what should be the query field Type? can someone help me on this
You are trying to store an Elasticsearch object (QueryBuilder) in Elasticsearch without specifying the mapping type.
You will need to annotate your query property as percolator type and might change the type of your property to a String:
#Document(indexName = "#{#es.indexName}")
public class Rule {
#Id
private String _id;
#Field(type = FieldType.Percolator)
private String query;
// ...
}
Or, if you want to have some other class for the query property you'll need a custom converter that will convert your object into a valid JSON query - see the documentation for the percolator mapping.

guidance with iterating over nested json and extract values

new to coding and java so trying to figure out how I can iterate over this JSON and extract the nested values
{
"prop1": {
"description": "",
"type": "string"
},
"prop2": {
"description": "",
"type": "string"
},
"prop3": {
"description": "",
"type": "string"
},
"prop4": {
"description": "",
"type": "string"
}
}
So far I have this :
public class JSONReadExample
{
public static void main(String[] args) throws Exception {
Object procedure = new JSONParser().parse(new FileReader("myFile.json"));
ObjectMapper objectMapper = new ObjectMapper();
String procedureString = objectMapper.writeValueAsString(procedure);
Map<String, Object> map
= objectMapper.readValue(procedureString, new TypeReference<Map<String,Object>>(){});
map.forEach((key, value) -> System.out.println(key + ":" + value));
How can I retrieve the "type" such as "string" or "number" nested value for each key?
Try to specific type of Map like this:
Map<String, LinkedHashMap<String, String>> map = objectMapper.readValue(procedureString, new TypeReference<>() {});
And then you can retrieve "type" by using:
map.forEach((key, value) -> System.out.println(key + ":" + value.get("type")));

Get size or length of json array response (restAssured Response interface)

We have REST API automation scripts using RestAssured. In this declared response object as public static Response response; and retrieving the response data using response.jsonPath().get("id"), during this trying to even get the size or length of the id, even need to get details about tags array.
JSON Response:
[
{
"id": 1,
"name": "test1",
"tags": [
{
"tagType": "details1",
"tag": {
"description": null
}
}
]
},
{
"id": 2,
"name": "test2",
"tags": [
{
"tagType": "details2",
"tag": {
"description": null
}
}
]
}
]
Tried below ways:
public static Response response;
List<String> resIDs = response.jsonPath().get("id");
System.err.println("Retrieved IDs from Response: " + resIDs);
O/P: is [1,2,3,4,5,6,7]
Tried as resIDs.size(), that also no response printed.
List<Object> size = response.jsonPath().getList("$");
System.err.println("ArraySize for IDs from Response: " + size);
or
int size = response.jsonPath().getList("$").size();
O/P: Not printed/nothing shown
Please guide how to get the size/length.
I don't seem to find any issue in your code, I just changed a bit to run locally and its working fine. Here's my code
public class S_62591968 {
public static Response postCallWithJsonBodyParam(String URL) {
return RestAssured.given().relaxedHTTPSValidation().contentType(ContentType.JSON).request().when().get(URL);
}
public static void main(String[] args) {
String url_endPoint = "http://localhost:8089/def/abc";
Response response = postCallWithJsonBodyParam(url_endPoint);
List<String> resIDs = response.jsonPath().get("id");
System.out.println("Retrieved IDs from Response : " + resIDs);
System.out.println("ArraySize for IDs from Response : " + resIDs.size());
}
}
Console :
Retrieved IDs from Response : [1, 2]
ArraySize for IDs from Response : 2

Neo4j OGM Neo4jSession variable substitution queries fail

For me:
neo4jSession.query("MATCH (n:Widget) WHERE (n.partNumber STARTS WITH '001') RETURN n.partNumber AS id, n.name AS description, n.urn AS urn LIMIT 10", Collections.emptyMap());
works.
This query does not work:
String query = "MATCH (n:Widget) " +
"WHERE (n.partNumber STARTS WITH {queryString}) " +
"RETURN n.partNumber AS id, n.name AS description, n.urn AS urn " +
"LIMIT {limit}";
Map<String, Object> params = ImmutableMap
.<String, Object>builder()
.put("queryString", queryString)
.put("limit", limit)
.build();
return (List) neo4jOperations.queryForObjects(Object.class, query, params);
It returns an empty list. I've also tried with my actual domain object:
return (List) neo4jOperations.queryForObjects(Widget.class, query, params);
with the same result.
I'm using OGM 2.0.2, neo4j 2.3.2, and Spring Data Neo4j 4.1.1 BUT I've tried this without neo4jOperations using Neo4jSession by itself with the same results. Oh, also I'm using a remove instance of neo4j with the HTTP driver.
Is there a bug in OGM?
MORE INFO:
Over the wire, I BELIEVE the messages look like this:
{ "statements":[
{
"statement":"MATCH (n:Widget) WHERE (n.partNumber STARTS WITH {queryString}) RETURN n.partNumber AS id, n.name AS description, n.urn AS urn LIMIT {limit}",
"parameters":{
"queryString":"001",
"limit":10
},
"resultDataContents":[
"graph"
],
"includeStats":false
} ] }
{ "statements":[
{
"statement":"MATCH (n:Widget) WHERE (n.partNumber STARTS WITH '001') RETURN n.partNumber AS id, n.name AS description, n.urn AS urn LIMIT 10",
"parameters":{
},
"resultDataContents":[
"rest"
],
"includeStats":true
} ] }
EVEN MORE INFORMATION:
I've tried this with Widget as both #QueryResult AND as #NodeEntity (w/ getters and setters).
#QueryResult
public class TypeaheadData {
public Object id;
public String description;
public String uid;
}
AND
#NodeEntity
public class TypeaheadData {
public Object id;
public String description;
public String uid;
public TypeaheadData() {
}
public Object getId() {
return id;
}
public void setId(Object id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
I've ALSO inspected the response over the wire and in both cases it looks like this:
{
"results":[
{
"columns":[
"id",
"description",
"uid"
],
"data":[
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
},
{
"graph":{
"nodes":[
],
"relationships":[
]
}
}
]
}
],
"errors":[
]
}
IF i remove the Widget #NodeEntity, this is the request sent out:
{
"statements":[
{
"statement":"MATCH (n:Widget) WHERE (n.partNumber STARTS WITH {queryString}) RETURN n.partNumber AS id, n.name AS description, n.urn AS urn LIMIT {limit}",
"parameters":{
"queryString":"001",
"limit":10
},
"resultDataContents":[
"row"
],
"includeStats":false
}
]
}
AND having removed the Widget #NodeEntity, the response DOES have the correct data in it, but the mapper throws:
Scalar response queries must only return one column. Make sure your
cypher query only returns one item.
The OGM cannot map a collection of properties into a domain entity.
Your query returns:
RETURN n.partNumber AS id, n.name AS description, n.urn AS urn
but there is nothing to tell the OGM what kind of entity this is, if it is one at all.
Changing this to RETURN n should do the job with neo4jOperations.queryForObjects(Widget.class, query, params);
Neo4j OGM can't handle mapping queries that don't return entire node objects. If you request only a subset of a node's properties in a query, you have to use the query method that returns a Result. And then you have to do the mapping yourself.
If you're using spring-data-neo4j, then you can use their #QueryResult annotation mixed with a repository #Query to handle the mapping for you. If you take a look at the code, they've finagled a mapper from from the metadata provided by the Neo4jSession.
The one exception is if you are querying for single properties on nodes, then the queryForObjects function will work.
Seem's like an oversight to me, but who am I to say.

How to parse a json in MVC view

I am getting the values of some datatypes in umbraco to my MVC view in cshtml I am getting a result in JSON how will I parse the JSON to bind it to a drop down list. What are the possible methods to do this. I have installed NetonSoft JSON in project also
if (home.GetProperty("residentsLogin") != null && !string.IsNullOrEmpty(home.GetPropertyValue("residentsLogin")))
{
var residentslog = home.GetPropertyValue("residentsLogin");
}
My JSON is in the corresponding format
[
{
"name": "Property1",
"url": "http://www.google.com",
"target": "_blank",
"icon": "icon-link"
},
{
"name": "Property2",
"url": "http://www.google.com",
"target": "_blank",
"icon": "icon-link"
}
]
Working code should look like this:
public class MyJsonObject
{
public string name{get;set;}
public string url { get; set; }
public string target { get; set; }
public string icon { get; set; }
}
var residentslog = #"[
{
'name': 'Property1',
'url': 'http://www.google.com',
'target': '_blank',
'icon': 'icon-link'
},
{
'name': 'Property2',
'url': 'http://www.google.com',
'target': '_blank',
'icon': 'icon-link'
}
]";
List<MyJsonObject> myJsonObjectList = JsonConvert.DeserializeObject<List<MyJsonObject>>(residentslog);
ViewBag.MySelectList = new SelectList(myJsonObjectList, "name", "url");

Resources