Jsoup transform my javascript string into a single line - java

I am having trouble with the .append function in Jsoup. I am appending my simple Javascript file response string to a Jsoup Element. But after appending my response transforms into a single line which is hurting me a lot.
My string is like this
(function () {
var count = 0;
var root = this;
var require = root.require;
//var require = cordova.require;
require.config({
config: {
text: { //this hacks the text api to allow cross domain loading of the templates. it is needed only for the packaged applications
useXhr: function (url, protocol, hostname, port) {
//console.log("text.useXhr request came from : " + url + ", " + protocol + " and " + hostname);
return true;
//return true if you want to allow this url, given that the
//text plugin thinks the request is coming from protocol, hostname, port.
}
},
'is': {
isBundled: true
}
},
waitSeconds: 45,
baseUrl: 'scripts/app',
deps: ["app"],
BUt after appending to a Element it will become
(function () { var count = 0; var root = this; var require = root.require; //var require = cordova.require; require.config({ config: { text: { //this hacks the text api to allow cross domain loading of the templates. it is needed only for the packaged applications useXhr: function (url, protocol, hostname, port) { //console.log("text.useXhr request came from : " +
My Code is for this
String temp=script.attr("src");
temp=temp.replace("/"+Heirarchy, DomainName+"/"+Heirarchy.toLowerCase());
script.attr("src", temp);
script.removeAttr("data-main");
script.removeAttr("async");
String innerHtml="</script>\n<script>\n"+old_configString;
script.append(innerHtml);
old_configString is my Javascript response String....

You should use a DataNode for adding scripts or styles.
script.after(new DataNode("<script>" + old_configString + "</script>", "http://domain.tld/path"));

Related

How to collect HTTP requests

I need to populate a database with the fields of the HTTP requests based on if the sender IP is valid or not.
For example if someone make a GET request on my IP with that:
/test/demo.php?name1=value1&name2=value2
How can I receive it so I can handle it and perform actions like:
Get the ip of the sender (And validate it - just confronting it with a list -)
Recognize the type of the Request
Extrapolate the fields (value1 and value2) and save them in variables
I'm using java.net.http package
You can't perform that using package java.net.http because you need to create an http server not an http client. To achieve that, you need HttpServer which is found in package com.sun.net.httpserver.
The first thing is to create a new instance of HttpServer :
final int port = 3000;//You can change with your port number you need
final HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 0);
System.out.println("Listening port : " + port);
Then, configure an http context. The first parameter accepts the route you defines and the second parameter accepts the http handler in which you can extract all your data that you need to store in your database.
httpServer.createContext("/test/demo.php", buildHttpHandler());//buildHttpHandler is to create
What contains the function buildHttpHandler()? :
Each time where route /test/demo.php is called, the content of arrow function is called. Here, we attempt only to create a simple page html and serves it to the http client. But before responding http client, we need to extract all data you need (ip, request type and parameters).
return httpExchange -> {
final String html = "<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <title>Page</title>\n" +
" <meta charset='utf-8'/>\n" +
" </head>\n" +
" <body>Ok</body>\n" +
"</html>";
//Function to create
extractData(httpExchange);
httpExchange.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8");
httpExchange.sendResponseHeaders(200, html.length());
final OutputStream outputStream = httpExchange.getResponseBody();
outputStream.write(html.getBytes(StandardCharsets.UTF_8));
outputStream.close();
};
What contains extractData() function?
In this function we will extract the data you need.
final String ip = getClientIp(httpExchange);
System.out.println("IP : " + ip);
final String requestType = httpExchange.getRequestMethod();
System.out.println("Request type : " + requestType);
final Map<String, String> parameters = extractParameters(httpExchange);
displayParameters(parameters);
Extracting ip client is more complicated because sometime client uses proxy that's why we create a dedicated function getClientIp() to extract the ip.
In this function, we attempt to extract firstly proxy ip. If not found, we extract standard ip from remote :
final String ip = getProxyIp(httpExchange);
return ip == null ? httpExchange.getRemoteAddress().getAddress().getHostAddress() : ip;
To extract proxy ip, we create another function getProxyIp(). It attempts to extract the ip provided from x-forwarded-for request header.
final List<String> ips = httpExchange.getRequestHeaders().get("x-forwarded-for");
return ips == null ? null : ips.get(ips.size() - 1);
I don't know what do you mean with extrapolating fields but you can store all data in a Map variable. The key will be the name of parameter and the value will be the value of parameter. But this is complicated also because we need to parse the string value from name1=value1&name2=value2. So, we create a new function extractParameters(). It contains :
final String query = httpExchange.getRequestURI().getQuery();
final Map<String, String> parameters = new HashMap<>();
if (query != null) {
final String[] firstParts = query.split("&");
for (final String firstPart : firstParts) {
final String[] secondParts = firstPart.split("=");
final String name = secondParts[0];
final String value = secondParts.length > 1 ? secondParts[1] : null;
parameters.put(name, value);
}
}
return parameters;
You notice maybe what is displayParameters() content. It just attempts to display, parameters retrieved from extractParameters().
for (final Map.Entry<String, String> parameter : parameters.entrySet()) {
System.out.println("Parameter key : " + parameter.getKey());
System.out.println("Parameter value : " + parameter.getValue());
}
And finally don't forget to start the http server :
httpServer.start();
You can check for a full code here https://gist.github.com/razafinarivohanania/24fe0986ea5868097404f2a758131823
When you test it, you can get something like :
IP : 127.0.0.1
Request type : GET
Parameter key : name2
Parameter value : value2
Parameter key : name1
Parameter value : value1

Base64 JAVA encode with dynamic values in SCALA - GATLING

I'm USING GATLING AND trying to use in java's library "Base64" in scala for sending encode uder:password in header ("authorization") request, with dynamic values:
I'm trying to do as follow :
val register = {
exec(request.asJSON
.check(status.is(200))
.check(jsonPath("$..user").saveAs("user"))
.check(jsonPath("$..password").saveAs("password"))
).pause(1)
}
val myvalue: HttpRequestBuilder = Utils.createPostFormParamsRequest(
"myvalue",
login,
Map("value"-> ("Basic " + Base64.getEncoder.encodeToString((("${user}").getBytes() + ":" + ("${password}").getBytes()).getBytes("utf-8")))),
Map())
I'd tried also Base64.getEncoder.encodeToString(("${uesr}" + ":" + "${password}").getBytes("utf-8"))))
But it seems like the Base64 take the String "${user}" and not the actual value, so the encryption does not work properly.
I'd tried to :
val helper = {
exec { session =>
val user : String= (session("user").as[String])
val password : String= (session("password").as[String])
val temp = "Basic " + Base64.getEncoder.encodeToString((user + ":" + password).getBytes("utf-8"))
val temp2: HttpRequestBuilder = Utils.createPostFormParamsRequest(
"bla",
login,
Map("value"-> temp),
Map())
val assert = {
exec(helper.asJSON
.check(status.is(200))
.check(header("answer").saveAs("answer"))
).pause(1)
}
session
}
And here the encryption works properly, but the "exec" do not.
There is a way to save the values in run time without part of the exec?
I don't know Gatling that well, but I think this should work. It's not the prettiest but without seeing the full code and how it's used it's a bit difficult to come up with something that looks good:
var token: String = null
val registerAssert = exec(...)
def finalToken = {
Utils.createPostFormParamsRequest(
"Final token",
Constants.LOGIN,
Map("Authorization"-> token),
Map())
}
def saveToken(s: Session) = {
token = "Basic " + Base64.getEncoder.encodeToString((s("uuid").as[String].getBytes() + ":" + s("secret").as[String].getBytes()).getBytes("utf-8")
s
}
// now you're actually executing the above
scenario(...)
.exec(registerAssert)
.exec(saveToken(_))
.exec(finalToken) // I'm assuming finalToken is executable
The intention of this is to first save the token value in a class variable, and then only construct the finalToken request (which uses that token) afterwards. Hence the def, and when it's called the token value will have been set.

Create Release Notes using JIRA Rest API in HTML format in groovy

I am working on a script where I need to create the release notes using JIRA REST API in HTML format for any project.The below four field should come in that release notes.
Issue Key Module Summary Release Note
I am trying the below code but it is giving me only the issue Key field but need all other fields as well and in html file.Could you please suggest me on this?
Issue:1
Initially it was giving me the output in below format:
NTTB-2141
NTTB-2144
NTTB-2140
But now it is giving me the output json fromat way.
Code which I am trying from the groovy console:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
import groovyx.net.http.RESTClient
final String USAGE =
"Usage: -Djira.username=xxx -Djira.password=xxx -Djira.fixVersion=1.0"
String jiraUsername = 'ABCDEF'
String jiraPassword = '********'
String jiraFixVersion = '3.8.101'
println "Getting issues..."
if (!jiraUsername?.trim()) {
fail("Empty property: jira.username " + USAGE)
}
if (!jiraPassword?.trim()) {
fail("Empty property: jira.password " + USAGE)
}
if (!jiraFixVersion?.trim()) {
fail("Empty property: jira.fixVersion " + USAGE)
}
final String JIRA_SEARCH_URL = "https://jira.test.com/rest/api/latest/"
// see JIRA docs about search:
// https://docs.atlassian.com/jira/REST/latest/#idp1389824
String JQL = "project = NCCB"
JQL += " AND issuetype in standardIssueTypes()"
JQL += " AND status in (Resolved, Closed)"
JQL += " AND fixVersion = \"${jiraFixVersion}\""
def jira = new RESTClient(JIRA_SEARCH_URL)
def query = [:]
query['os_username'] = jiraUsername
query['os_password'] = jiraPassword
query['jql'] = JQL
query['startAt'] = 0
query['maxResults'] = 1000
try {
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
assert (resp.data instanceof net.sf.json.JSON)
resp.data.issues.each { issue ->
println issue.key
}
println "Total issues: " + resp.data.total
} catch (groovyx.net.http.HttpResponseException e) {
if (e.response.status == 400) {
// HTTP 400: Bad Request, JIRA JQL error
fail("JIRA query failed: ${e.response.data}", e)
} else {
fail("Failure HTTP status ${e.response.status}", e)
}
}
I suspect the code is right, except for that assertion:
assert (resp.data instanceof net.sf.json.JSON)
I get a groovy.json.internal.LazyMap (maybe you have changed versions of Groovy or Jira or something).
As a result, the assertion fails and Groovy tries to be helpful by giving you a comparison... but it shows you the toString() of the result, which is a huge mess of maps.
If you remove that assertion, it works for me, and I suspect it will work for you too.
Edit: huh... you cannot literally take "all" data and print to html. You will have to select the properties you need, and those depend on your Jira configuration. Here is an example with only 2 properties that should be universal:
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
def output = new File('issues.html')
output << "<html><body><ul>"
resp.data.issues.each { issue ->
def url = "https://yourjirainstance/browse/${issue.key}"
output << "<li>${issue.key}: ${issue.fields.summary}</li>"
}
output << "</ul></body></html>"
println "Exported ${resp.data.total} issues to ${output.name}"
See here details about what the service will give you.
If you just want an HTML dump, maybe the REST API is not what you want: you can also ask Jira to export results of JQL as a printable output (that will actually be html).

How to send string[] to the spring controller?

I have the following JQuery code which sends some request parameters to my Spring MVC controller. For some parameters I should get multiple values.
$('#tb-email').click(function(event) {
var base, data, formats, recipients, reportSource, reportSourceType;
if ($(this).parent('li').hasClass('disabled')) {
return false;
}
base = "<base href=\"" + window.location.protocol + "//" + window.location.host + window.DashboardGlobals.baseUrl + "\">";
data = $('html').clone().find('script').remove().end().find('nav').remove().end().find('#dashboardCanvas').removeClass('dashboardCanvas').end().find('head').prepend(base).end().html();
data = encodeURIComponent(Base64.encode('<html>' + data + '</html>'));
$.post(window.DashboardGlobals.sendMail, {
formats: ['png', 'pdf'],
recipients: ['abc#xyz.com', 'xyz#abc.com'],
reportSource: data, //Base64 data
reportSourceType: 'adhoc',
reportName: 'DataQualityApp'
});
event.preventDefault();
});
When the tb-email is clicked, request is submitted to some controller which is saved in the DashboardGlobals variable.
At the server side I have written the following Java code to get the multiple values for the parameters formats and recipients.
public #ResponseBody String process(#RequestParam("formats") String[] formats, #RequestParam("recipients") String[] recipients, #RequestParam("reportSource") String reportSource, #RequestParam("reportSourceType") String reportSourceType, HttpServletRequest request) {
...Some Processing....
return null;
}
I checked the formats and recipients length which is 1.
I even tried to get the values using
String[] formats = request.getParameterValues("formats");
String[] recipients = request.getParameterValues("recipients");
Still I am getting single values in the array. The length is still one?
What is going wrong?
You may try this, spring controller can take csv as array or list:
$.post(window.DashboardGlobals.sendMail, {
formats: ['png', 'pdf'].join(","),//<-- create csv string
recipients: ['abc#xyz.com', 'xyz#abc.com'].join(","),//<-- create csv string
...
});
OR
$.post(window.DashboardGlobals.sendMail, {
formats: 'png,pdf',
recipients: 'abc#xyz.com,xyz#abc.com',
...
});

Automatically opening pages on different monitors

I am designing an emergency response page, which needs to display information across 3 different monitors. The first monitor will gather information about the caller, and then contain 2 links. The first link needs to display a different web page on the 2nd monitor, and the 2nd link needs to display a different web page on the 3rd monitor.
Is this possible?
Thanks for any help
The first link needs to display a different web page on the 2nd monitor, and the 2nd link needs to display a different web page on the 3rd monitor.
While, depending on your operating system, it is possible to control where a window appears, there are much fewer options for doing this using javascript / serverside code over HTTP / browsers.
The only sensible way to achieve this is by configuring the displays to be tiles of a larger display rather than independent screens (for *nix/BSD/Linux, check out xinerama).
The code below saves the size of a window - and would only need some simple changes to support x/y offset and multiple windows - I leave it to you as to how you differentiate between the windows.
A simpler approach would be to just have one huge window with frames whose borders align with the monitors.
if (document.getElementById && !document.all) { // NOT for MSIE
stickySizeOverloadOnload(stickySizeSetWindowSize);
stickySizeOverloadOnresize(stickySizeSaveWindowSize);
}
function stickySizeSaveWindowSize(event)
{
var expiry = new Date();
var path = document.location.pathname;
expiry.setDate(expiry.getDate()+500);
stickySizeSetCookie('windowSize', window.outerWidth + ',' + window.outerHeight, expiry, path);
}
function stickySizeSetWindowSize()
{
var saved=stickySizeGetCookie('windowSize');
var parts=new Array();
if (saved.length) {
parts = saved.split(',');
if ((parts[0]>100) && (parts[1]>100)) {
window.outerWidth=parts[0];
window.outerHeight=parts[1];
} else {
alert("invalid size - '" + saved + "'");
stickySizeDeleteCookie('windowSize');
}
}
}
function stickySizeOverloadOnload(func)
{
var oldhandler=window.onload;
if (typeof window.onload != "function") {
window.onload=func;
} else {
window.onload=function(event) {
oldhandler(event);
func(event);
}
}
}
function stickySizeOverloadOnresize(func)
{
var oldhandler=window.onresize;
if (typeof window.onresize != "function") {
window.onresize=func;
} else {
window.onresize=function(event) {
oldhandler(event);
func(event);
}
}
}
function stickySizeSetCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
document.cookie = curCookie;
}
function stickySizeGetCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1)
end = dc.length;
return unescape(dc.substring(begin + prefix.length, end));
}
function stickySizeDeleteCookie(name, path, domain) {
if (stickySizeGetCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
You can open the links in a different window with the attribute target="windowName".
You have to set up the three windows manually, so assign them manually to the three screens. When you open a link again in a window it is still on the same screen.
Have a look at Java: Getting resolutions of one/all available monitors (instead of the whole desktop)?
(The answer discuss the GraphicsEnvironment.getLocalGraphicsEnvironment() call)
If you really want the windows to be locked to a specific monitor, you will need to implement this client side. Here is a link describing how to detect which monitor a window is on in Java, so you can move it to the proper monitor and maximize the window if you desire. Obviously you can implement the rest of the system server side and just display pages inside the windows you have created.

Categories

Resources