In spring cloud contract (groovy) file I have issues with extracting a segment of request URL to use it as a parameter of in response body, e.g.
package contracts
import org.springframework.cloud.contract.spec.Contract
Contract.make {
description "Should return OK "
request {
url "/discovery.svc/something(\'${value(consumer(regex(".*")),producer('defaultSomething'))}\')"
method GET()
}
response {
status 200
body :
value(
consumer(file("response/defaultSomething.xml").file.write(
String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<entry xmlns:metadata=\"http://docs.oasis-open.org/odata/ns/metadata\" xmlns:data=\"http://docs.oasis-open.org/odata/ns/data\" xmlns=\"http://www.w3.org/2005/Atom\" metadata:context=\"http://localhost:8082/discovery.svc/\$metadata#Environment/ContentServiceCapability\" xml:base=\"http://localhost:8082/discovery.svc\">\n" +
" <id>http://localhost:8082/discovery.svc/something('%1\$s')</id>\n" +
" <title></title>\n" +
" <summary></summary>\n" +
" <updated>2020-03-23T15:19:53.272668900Z</updated>\n" +
" <author>\n" +
" <name>SDL OData v4 framework</name>\n" +
" </author>\n" +
" <link rel=\"edit\" title=\"ContentServiceCapability\" href=\"something('%1\$s')\"></link>\n" +
" <link rel=\"http://docs.oasis-open.org/odata/ns/related/Environment\" type=\"application/atom+xml;type=entry\" title=\"Environment\" href=\"something('%1\$s')/Environment\"></link>\n" +
" <link rel=\"http://docs.oasis-open.org/odata/ns/relatedlinks/Environment\" type=\"application/xml\" title=\"Environment\" href=\"something('%1\$s')/Environment/\$ref\"></link>\n" +
" <category scheme=\"http://docs.oasis-open.org/odata/ns/scheme\" term=\"#Tridion.WebDelivery.Platform.ContentServiceCapability\"></category>\n" +
" <content type=\"application/xml\">\n" +
" <metadata:properties>\n" +
" <data:id>%1\$s</data:id>\n" +
" <data:LastUpdateTime metadata:type=\"Int64\">1580489088713</data:LastUpdateTime>\n" +
" <data:URI>http://localhost:8081/content.svc</data:URI>\n" +
" <data:ExtensionProperties metadata:type=\"#Collection(Tridion.WebDelivery.Platform.ContentKeyValuePair)\"></data:ExtensionProperties>\n" +
" </metadata:properties>\n" +
" </content>\n" +
"</entry>", fromRequest().url().split('/')[-1].split('\'')[-2]))),
producer(file("response/defaultSomething.xml")))
)
}
}
the problen is that fromRequest().url() doesn't seem to be working and when I try to insert
print fromRequest().url()
in response section (in order to debug) I get as a result:
DslProperty{
clientValue={{{request.url}}},
serverValue={{{request.url}}}}
instead of plain string URL. .toString() doesn't help neither. Do you have any ideas how can I get request.url as a plain string?
is that any idea on putting variable into json text body and POST it out? Here is my text body
final String POST_PARAMS = "{\n" + "\"company\": 101,\r\n" +
" \"product\": 101,\r\n" +
" \"condition\": \"Test Title\",\r\n" +
" \"delivery_time\": \"Test Body\``"" + "\n}";
You have to use org.json.JSONObject
Example:
myString = new JSONObject()
.put("JSON", "Hello, World!").toString();
produces the string {"JSON": "Hello, World"}
I am trying to implement a function to be able to remove or modify a json object base on a specified json path. For example, if i have a below json string/object:
{
"PersonalDetailsDTO": {
"FirstName": "Mark",
"LastName": "Sully",
"TotalDependent": "2",
"DOB": "19811212",
"SecQuestion": "Some Que",
"SecAnswer": "Some-Ans",
"Mobile": "0123456789",
"Email": "some#validemail.com",
"Title": "Mr",
"EmploymentListDTO": [
{
"Type": "Full-time",
"Probation": true
}
],
"AddressListDTO": [
{
"AddressType": "BUS",
"PostCode": "1234",
"State": "NSW",
"StreetName": "miller",
"StreetNumber": "111",
"StreetType": "Invalid",
"Suburb": "Sydney",
"UnitNumber": "Maximum"
}
]
}
}
And i want to remove element $.PersonalDetailsDTO.AddressListDTO.PostCode.
I've done quite some search, and the one lib i found is JsonPath: http://static.javadoc.io/com.jayway.jsonpath/json-path/2.2.0/com/jayway/jsonpath/JsonPath.html
So i wrote the below code:
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
String jsonString = "{\n" +
" \"PersonalDetailsDTO\": {\n" +
" \"FirstName\":\"Mark\",\n" +
" \"LastName\":\"Sully\",\n" +
" \"Title\":\"Mr\",\n" +
" \"DOB\":\"19811201\",\n" +
" \"SecQuestion\":\"Some Ques\",\n" +
" \"SecAnswer\":\"Some-Ans\",\n" +
" \"Email\":\"some#validemail.com\",\n" +
" \"EmploymentListDTO\": [\n" +
" {\n" +
" \"Type\": \"Full-time\",\n" +
" \"Probation\": true\n" +
" }\n" +
" ],\n" +
" \"AddressListDTO\": [\n" +
" {\n" +
" \"AddressType\": \"Residential\",\n" +
" \"PostCode\": \"2345\",\n" +
" \"State\": \"NSW\",\n" +
" \"StreetName\": \"MEL\",\n" +
" \"StreetNumber\": \"2\",\n" +
" \"StreetType\": \"Boulevard\",\n" +
" \"Suburb\": \"Melbourne\",\n" +
" \"UnitNumber\": \"345\"\n" +
" }\n" +
" ]\n" +
" } \n" +
"}";
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println("Before: " + jsonObject.toString());
JsonPath jp = JsonPath.compile("$.PersonalDetailsDTO.AddressListDTO[0].PostCode");
Configuration conf = Configuration.defaultConfiguration();
Object json = conf.jsonProvider().parse(jsonString);
System.out.println("After: " + jp.delete(json, conf).toString());
}
And the console log displays:
Before: {"PersonalDetailsDTO":{"EmploymentListDTO":[{"Type":"Full-time","Probation":true}],"SecAnswer":"Some-Ans","Email":"some#validemail.com","SecQuestion":"Some Ques","FirstName":"Mark","DOB":"19811201","AddressListDTO":[{"StreetName":"MEL","Suburb":"Melbourne","State":"NSW","StreetNumber":"2","UnitNumber":"345","AddressType":"Residential","PostCode":"2345","StreetType":"Boulevard"}],"Title":"Mr","LastName":"Sully"}}
After: {PersonalDetailsDTO={FirstName=Mark, LastName=Sully, Title=Mr, DOB=19811201, SecQuestion=Some Ques, SecAnswer=Some-Ans, Email=some#validemail.com, EmploymentListDTO=[{"Type":"Full-time","Probation":true}], AddressListDTO=[{"AddressType":"Residential","State":"NSW","StreetName":"MEL","StreetNumber":"2","StreetType":"Boulevard","Suburb":"Melbourne","UnitNumber":"345"}]}}
Looks like JsonPath is doing it's job and removing $.PersonalDetailsDTO.AddressListDTO.PostCode. However, there's something very obvious that bothers me:
Looking at the json string produced by .toString() in before and after case, JSONObject API printed a nice string in true json standard format with every double quotes "" present, while the JsonPath .toString produce a customer string format that has some elements in double quote "" while others are not and i can not use it further like JSONObject.
And what i noticed is that although JsonPath claim to accept "java.lang.Object" as parameter in many of its function, what it truely accept is something called "jsonProvider". Not sure if it's causing the weird .toString() behavior.
Anyway, does anyone know how get a nice formatted json string out of JsonPath APIs like remove(), put(), read() and many other? Or to convert the return value to something like JSONObject?
If you know any other Java lib that can do remove/modify element by json path, please feel free to recommand. Thank you!
I don't know JsonPath.
I think you should use jackson which is defacto standard lib when work with JSON in java
aproximate what you are going to do is:
String jsonString = "{"k1": {"k2":"v2"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
actualObj.at("/k1/k2").getValueAsInt()
and replace getValueAsInt with any other function
I have this code:
public void foo (){
String script =
"var aLocation = {};" +
"var aOffer = {};" +
"var aAdData = " +
"{ " +
"location: aLocation, " +
"offer: aOffer " +
" };" +
"var aClientEnv = " +
" { " +
" sessionid: \"\", " +
" cookie: \"\", " +
" rtserver-id: 1, " +
" lon: 34.847, " +
" lat: 32.123, " +
" venue: \"\", " +
" venue_context: \"\", " +
" source: \"\"," + // One of the following (string) values: ADS_PIN_INFO,
// ADS_0SPEED_INFO, ADS_LINE_SEARCH_INFO,
// ADS_ARROW_NEARBY_INFO, ADS_CATEGORY_AUTOCOMPLETE_INFO,
// ADS_HISTORY_LIST_INFO
// (this field is also called "channel")
" locale: \"\"" + // ISO639-1 language code (2-5 characters), supported formats:
" };" +
"W.setOffer(aAdData, aClientEnv);";
javascriptExecutor.executeScript(script);
}
I have two q:
when I debug and copy script value I see a member rtserver - id instead of rtserver-id
how can it be? the code throws an exception because of this.
Even if i remove this rtserver-id member (and there is not exception thrown)
I evaluate aLocation in this browser console and get "variable not defined". How can this be?
rtserver-id isn't a valid identifier - so if you want it as a field/property name, you need to quote it. You can see this in a Chrome Javascript console, with no need for any Java involved:
> var aClientEnv = { sessionId: "", rtserver-id: 1 };
Uncaught SyntaxError: Unexpected token -
> var aClientEnv = { sessionId: "", "rtserver-id": 1 };
undefined
> aClientEnv
Object {sessionId: "", rtserver-id: 1}
Basically I don't think anything's adding spaces - you've just got an invalid script. You can easily add the quotes in your Java code:
" \"rtserver-id\": 1, " +
We call a webservice from our C# app which takes about 300ms using WCF (BasicHttpBinding). We noticed that the same SOAP call does only take about 30ms when sending it from SOAP UI.
Now we also implemented a test accessing the webservice via a basic WebClient in order to make sure that the DeSer-part of the WCf is not the reason for this additional delay. When using the WebClient class the call takes about 300ms as well.
Any ideas on why Java compared to C# is about 10x faster in this regard? Is there some kind of tweaking possible on the .NET side of things?
private void Button_Click(object sender, RoutedEventArgs e)
{
executeTest(() =>
{
var resultObj = client.getNextSeqNr(new WcfClient()
{
domain = "?",
hostname = "?",
ipaddress = "?",
loginVersion = "?",
processId = "?",
program = "?",
userId = "?",
userIdPw = "?",
userName = "?"
}, "?", "?");
});
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
executeTest(()=>
{
webClient.Proxy = null;
webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
webClient.Headers.Add("Content-Type", "application/xml");
webClient.Encoding = Encoding.UTF8;
var data = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"SomeNamespace\">" +
" <soapenv:Header/>" +
" <soapenv:Body>" +
" <ser:getNextSeqNr>" +
" <!--Optional:-->" +
" <clientInfo>" +
" <!--Optional:-->" +
" <domain>?</domain>" +
" <!--Optional:-->" +
" <hostname>?</hostname>" +
" <!--Optional:-->" +
" <ipaddress>?</ipaddress>" +
" <!--Optional:-->" +
" <loginVersion>?</loginVersion>" +
" <!--Optional:-->" +
" <processId>?</processId>" +
" <!--Optional:-->" +
" <program>?</program>" +
" <!--Optional:-->" +
" <userId>*</userId>" +
" <!--Optional:-->" +
" <userIdPw>?</userIdPw>" +
" <!--Optional:-->" +
" <userName>?</userName>" +
" </clientInfo>" +
" <!--Optional:-->" +
" <name>?</name>" +
" <!--Optional:-->" +
" <schema>?</schema>" +
" </ser:getNextSeqNr>" +
" </soapenv:Body>" +
"</soapenv:Envelope>";
string result = webClient.UploadString("http://server:8080/service", "POST", data);
});
}
Am I missing something here? Any idea would be helpful... ;-)
Kind regards,
Sebastian
I just found the reason for this.
It's the 100-Expect Continue HTTP Header and the corresponding implementation in .NET. The .NET client wait 350ms as default on the server. This causes the delays. Java seems to have other default values here...
Just add the following line of code very early in your code:
System.Net.ServicePointManager.Expect100Continue = false;
Cheers!