Spring cloud contract: using URL as response body parameter - java

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?

Related

Drawing piechart in HTML email using Apache Commons Email

I would want to send statistical information to my clients showing the number of transactions processed on every terminal or branch. I am using Apache Commons Email to send HTML emails.
I would like to send a pie-chart data like this one on the site.
My java code is basic extracted from.
It goes like:
public void testHtmlEmailPiechart()
throws UnsupportedEncodingException, EmailException, MalformedURLException {
HtmlEmail email = new HtmlEmail();
email.setHostName(emailServer);
email.setSmtpPort(587);
email.setSSLOnConnect(true);
email.setAuthentication(userName, password);
email.setCharset(emailEncoding);
email.addTo(receiver, "Mwesigye John Bosco");
email.setFrom(userName, "Enovate system emailing alert");
email.setSubject("Conkev aml Engine Statistics");
URL url = new URL("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcROXe8tn1ljtctM53TkLJhLs6gEX56CvL0shvyq1V6wg7tXUDH8KRyVP30");
// URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid2 = email.embed(url, "logo.gif");
email.setHtmlMsg("<html>\n" +
" <head>\n" +
" <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n" +
" <script type=\"text/javascript\">\n" +
" google.charts.load(\"current\", {packages:[\"corechart\"]});\n" +
" google.charts.setOnLoadCallback(drawChart);\n" +
" function drawChart() {\n" +
" var data = google.visualization.arrayToDataTable([\n" +
" ['Task', 'Hours per Day'],\n" +
" ['Work', 11],\n" +
" ['Eat', 2],\n" +
" ['Commute', 2],\n" +
" ['Watch TV', 2],\n" +
" ['Sleep', 7]\n" +
" ]);\n" +
"\n" +
" var options = {\n" +
" title: 'My Daily Activities',\n" +
" is3D: true,\n" +
" };\n" +
"\n" +
" var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));\n" +
" chart.draw(data, options);\n" +
" }\n" +
" </script>\n" +
" </head>\n" +
" <body>\n" +
" <div id=\"piechart_3d\" style=\"width: 900px; height: 500px;\">Piechart Data</div>\n" +
" </body>\n" +
"</html>");
email.setTextMsg("Your email client does not support HTML messages");
email.send();
}
My guess is that the JavaScript is not recognized because the code works like sending images,styling fonts and I have sent to my email address some sample mail. I would like your help or recommendation of any material I can read to achieve this as long as am using Java.The processes is automated running in the background so no user interface is involved.
Thanks.

`rtserver-id` turns to `rtserver - id` in java string

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, " +

Loading local CSS file in WebView.replaceContent

I'm trying to implement a code editor in JavaFx using
https://gist.github.com/jewelsea/1463485
but the issue is that it downloads the CSS/Javascript from the internet to load CodeMirror. Is there a way to download those files and put them so that it can load them locally on Netbeans? I'm experienced with Java but not so much JavaFX or HTML.
I
Please put the CSS/Javascript in the classpath and use the following code:
private final String editingTemplate =
"<!doctype html>" +
"<html>" +
"<head>" +
" <link rel=\"stylesheet\" href=\"codemirror.css\">" +
" <script src=\"codemirror.js\"></script>" +
" <script src=\"clike.js\"></script>" +
"</head>" +
"<body>" +
"<form><textarea id=\"code\" name=\"code\">\n" +
"${code}" +
"</textarea></form>" +
"<script>" +
" var editor = CodeMirror.fromTextArea(document.getElementById(\"code\"), {" +
" lineNumbers: true," +
" matchBrackets: true," +
" mode: \"text/x-java\"" +
" });" +
"</script>" +
"</body>" +
"</html>";
I am just trying to pick the CSS/Javascript from the classpath instead of the internet

Why is this query not returning the data( in XQuery, Java)?

This is for XQuery used in Java. My code is working with other XML files, but this time it is not returning the required data. The faulty code is below. What is wrong with it? Thanks.
String queryString =
"declare variable $docName as xs:string external;" + sep +
" for $TRACK in doc($docName)/playlist/tracklist/track " +
" return " +
" <track><title>{$TRACK/title/text()}</title>" +
" <location>{$TRACK/location/text()}</location></track>";
This is the target XML:
<?xml version="1.0"?>
-<playlist xmlns="http://xspf.org/ns/0/" version="1">
-<trackList>-<track><location>http://radiotool.com/242.mp3</location><title>New York</title></track>
-<track><location>http://radiotool.com/243.mp3</location> <title>Chicago Repeater</title></track>
</trackList></playlist>
It's probably because the source XML uses a namespace and your XPath doesn't. How about this:
String queryString =
"declare namespace xsp='http://xspf.org/ns/0/'; " +
"declare variable $docName as xs:string external;" + sep +
" for $TRACK in doc($docName)/xsp:playlist/xsp:trackList/xsp:track " +
" return " +
" <track><title>{$TRACK/xsp:title/text()}</title>" +
" <location>{$TRACK/xsp:location/text()}</location></track>";

Java vs. Net HTTP Client Performance

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!

Categories

Resources