play framework 2.1 accees log - java

I'm writing a play framework 2.1.5 access log, code like this
class AccessLog extends Filter {
def apply(next: (RequestHeader) => Result)(rh: RequestHeader) = {
val start = System.currentTimeMillis
def logTime(result: PlainResult): Result = {
val time = System.currentTimeMillis - start
val contentLength: String = result.header.headers getOrElse("Content-Length", "-")
play.Logger.info("" + rh.method +" " + rh.uri + " took " + " " + time + " ms and returned " + result.header.status + " " + contentLength)
result
}
next(rh) match {
case plain: PlainResult => logTime(plain)
case async: AsyncResult => async.transform(logTime)
}
}
}
I found that many people found an access log for the play framework and this works any way with an issue that
it can always get the response size, when you press CTRL + F5, if you just press F5, you cannot get the "Content-Length" even the "Content-Length" does not exist in the map.
any one konw this?

Related

How to fill in empty double value in test DTO, Java, Spring

So I am testing the controller of my application and I stumbled upon a problem.
This is the Json I use in my testcode:
String bike = "{" +
" \"bikeNumber\" : \"E2\"," +
" \"brand\" : \"Gazelle\"," +
" \"frameNumber\" : \"HA1234568\"," +
" \"retailPrice\" : 1200," +
" \"basePrice\" : 20.0," +
" \"electric\" : true" +
"}";
I want to test when the user doesn't fill in one of the values, it throws an exception. In other words I want to test the #NotNull, #NotBlank annotations.
I have done this for bikeNumber and frameNumber, these are string types and I can leave them open. The problem I get if I leave the basePrice open and run my test, I get an error saying:
java.lang.AssertionError: No value at JSON path "$.basePrice"
I know that it's a null value because I haven't filled it in, but that is part of the plan. So my question is, how do I leave a long, double or int value empty without getting a test error.
My full code block is here:
#Test
void whenPostRequestNoBasePrice_thenBadRequestResponse() throws Exception {
String bike = "{" +
" \"bikeNumber\" : \"E1\"," +
" \"brand\" : \"Gazelle\"," +
" \"frameNumber\" : \"HA1234568\"," +
" \"retailPrice\" : 1200," +
" \"basePrice\" : \"\" " +
" \"electric\" : true" +
"}";
mockMvc.perform(MockMvcRequestBuilders.post("/createbike")
.content(bike)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.basePrice", Is.is( "Base price is mandatory.")))
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andReturn().getResponse().getContentAsString();
}
I tried multiple things, also with and without the comma: "basePrice" : "" ," +
Also I can't seem to find this anywhere on stackoverflow.

I want to make a report command and send only the report part of the message and ignore arg[0] arg[1] and send arg[3 ] and up

So i want it to do send [sender] has reported [person] for [args[3] and up]
if (args[0].equalsIgnoreCase("!report")) {
event.getGuild().getTextChannelById("818967272731050024").sendMessage(event.getAuthor().getAsMention() + " has reported " + args[1].toString() + " for ' + event.getMessage().getContentDisplay()" + "'").queue();
event.getMessage().addReaction("👍").queue();
}

wait until angular 2+ has finished loading issue

I recently posted a question about an issue I have white testing an angular based application (ref: wait until Angular has finished loading issue )
Turns out that the check done was valid for angular 1.x apps, while our application runs on angular 6.x.
I've then found out that post: Detecting that Angular 2 is done running
which explains how to do a similar check but for angular 2+ apps. I've set up the check in a similar fashion to "Michal Filip" explained.
I've also tried to use the ngWebdriver solution proposed further down in the post.
Both suffers of the same problem: the check will always return true as in its done loading which isn't true.
tried to inverse the check, it didn't help (state never changed)
// Will check if Angular still has pending http_requests ongoing and wait if required
public void untilAngular2HasFinishedProcessing()
{
until(() ->
{
log.info("Waiting on angular 2+ to finish processing");
final boolean isReady = ((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"if (document.readyState !== 'complete') {" +
" callback('document not ready');" +
"} else {" +
" try {" +
" var testabilities = window.getAllAngularTestabilities();" +
" var count = testabilities.length;" +
" var decrement = function() {" +
" count--;" +
" if (count === 0) {" +
" callback('complete');" +
" }" +
" };" +
" testabilities.forEach(function(testability) {" +
" testability.whenStable(decrement);" +
" });" +
" } catch (err) {" +
" callback(err.message);" +
" }" +
"}"
).toString().equals("complete");
log.info("Is angular 2+ ready? " + isReady);
return isReady;
}
);
}
// sample call would be
untilAngular2HasFinishedProcessing();
Excpected: the test would wait until Angular is done loading before returning true
Actual: Returns true from the start, which I know isn't the case.
Possible duplicate? No, because this is a problem question based on the implementation proposed in the linked question.
Here's the solution I ended up using:
public boolean untilAngular2HasFinishedProcessing()
{
until(() ->
{
log.info("Waiting on angular 2+ to finish processing");
final boolean isReady = (Boolean.valueOf(((JavascriptExecutor) driver)
.executeScript(
"try{" +
"return (window.getAllAngularTestabilities()[0]._ngZone.hasPendingMicrotasks == " +
"false && " +
"window.getAllAngularTestabilities()[0]._ngZone.hasPendingMacrotasks == false && " +
"window.getAllAngularTestabilities()[0]._ngZone._nesting == 0 &&" +
"window.getAllAngularTestabilities()[0]._ngZone.isStable == true)" +
"}" +
"catch(err) {" +
"if (err.message == ('window.getAllAngularTestabilities is not a function'))" +
"{" +
"return true" +
"}" +
"}")
.toString()));
log.info("Is Angular 2+ ready? " + isReady);
return isReady;
}
);
return true;
}
That worked on a consistent fashion so far.

Java Selenium with Angular 5

I am trying to work with Selenium in Java with Angular 5 based website.
Selenium does not support it directly, but JavascriptExecutor can help validating the page components finished loading.
The problem is, I do not know how to implement the JavaScript to validate this.
I am using:
return window.getAngularTestability === undefined
to validate Angular 5 exists in the current page, but the next part of the implementation is a mystery to me.
I know I have to use return window.getAngularTestability somehow.
You can create a generic java method for running any javascript within your Java code. Refer below block of code:-
public void executeJavascript(String script) {
((JavascriptExecutor) driver).executeScript(script);
}
You can pass your return javascript statements as parameters to this method.
I found an answer after a lot of research and searching the web.
The solution is not mine, so i do not deserve the credit.
ExpectedCondition<Boolean> expectation = driver -> ((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"if (document.readyState !== 'complete') {" +
" callback('document not ready');" +
"} else {" +
" try {" +
" var testabilities = window.getAllAngularTestabilities();" +
" var count = testabilities.length;" +
" var decrement = function() {" +
" count--;" +
" if (count === 0) {" +
" callback('complete');" +
" }" +
" };" +
" testabilities.forEach(function(testability) {" +
" testability.whenStable(decrement);" +
" });" +
" } catch (err) {" +
" callback(err.message);" +
" }" +
"}"
).toString().equals("complete");
try {
WebDriverWait wait = new WebDriverWait(webDriver(), 15);
wait.until(expectation);
} catch (Throwable error) {
new Exception("Timeout waiting for Page Load Request to complete.");
}

Convert Loadrunner File Parameter to Java string for payload

I have a java virtual user script that is sending a payload request. I am trying to use values from a file to send via a loadrunner file parameter.
here is the payload:
private static final String PAYLOAD =
"<ips_cad_mdt>\n" +
" <SignOnRequest>\n" +
" <DestApplication>hhhh</DestApplication>\n" +
" <OrigApplication>hhh</OrigApplication>\n" +
" <SessionRef>3</SessionRef>\n" +
" <Aliasing>1234</Aliasing>\n" +
" </SignOnRequest>\n" +
"</ips_cad_mdt>";
I would like to use something like the following:
private static final String PAYLOAD =
"<ips_cad_mdt>\n" +
" <SignOnRequest>\n" +
" <DestApplication>hhh</DestApplication>\n" +
" <OrigApplication>hhh</OrigApplication>\n" +
" <SessionRef>3</SessionRef>\n" +
" <Aliasing>”+lr.eval_string(“{AliasId}”)+”</Aliasing>\n" +
" </SignOnRequest>\n" +
"</ips_cad_mdt>";
for some reason i cant see any output for this value. do i need to declare a variable: e.g. lr.save_string("AliasId", "{AliasId}");
an example of this would help loads. Many Thanks
There seems to be an error in the code completion in VuGen. The parameters should be reversed and without the {} in save_string.
lr.save_string("1234","myId");
lr.message(lr.eval_string("{myId}"));
In the documentation it is correct - https://admhelp.microfocus.com/lr/en/12.55/help/function_reference/FuncRef.htm#FuncRef/c_vuser/lrFr_lr_save_string.htm?Highlight=lr_save_string
I asked the responsible team to fix the code completion in VuGen so you will be able to see this change in one of the future releases.

Categories