Drag & drop hierarchical list using selenium webdriver in java
Github link: https://github.com/dbushell/Nestable
Demo link:- http://dbushell.github.io/Nestable/
I want to drag and drop hierarchical list using selenium webdriver in java . See demo link for more details.
i tried the following things:-
Get the source element
Create a div with class=dd-placeholder
Drag the source element and drop on the newly created div element
Error:- Not able drop the source element on newly created div element.
How can i do it. Is it possible using selenium webdriver.
Note: See demo link
I found drag and drop functionality to be a little different depending on which browser you use, and I had to add an offset to the drop location to get it to work in Chrome Firefox and IE consistently.
This is a C# snippet, but java should be similar. The target in this instance is a placeholder div that I inserted with JS, just like your approach
Actions act = new Actions(WebDriver);
act.ClickAndHold(source);
act.MoveToElement(target);
act.MoveByOffset(0, 5); //Minimum 1 pixel offset for Chrome, 5 for IE
act.Release(source);
act.Build().Perform();
This method drags and drops a webelement from a location to another using Javascript. Don't get bogged down with its javascript :). Just use the method by providing from and to parameters. Good luck!
public void dragAndDrop(WebElement from, WebElement to) {
js.executeScript("function createEvent(typeOfEvent) {\n" + "var event =document.createEvent(\"CustomEvent\");\n"
+ "event.initCustomEvent(typeOfEvent,true, true, null);\n" + "event.dataTransfer = {\n" + "data: {},\n"
+ "setData: function (key, value) {\n" + "this.data[key] = value;\n" + "},\n"
+ "getData: function (key) {\n" + "return this.data[key];\n" + "}\n" + "};\n" + "return event;\n"
+ "}\n" + "\n" + "function dispatchEvent(element, event,transferData) {\n"
+ "if (transferData !== undefined) {\n" + "event.dataTransfer = transferData;\n" + "}\n"
+ "if (element.dispatchEvent) {\n" + "element.dispatchEvent(event);\n"
+ "} else if (element.fireEvent) {\n" + "element.fireEvent(\"on\" + event.type, event);\n" + "}\n"
+ "}\n" + "\n" + "function simulateHTML5DragAndDrop(element, destination) {\n"
+ "var dragStartEvent =createEvent('dragstart');\n" + "dispatchEvent(element, dragStartEvent);\n"
+ "var dropEvent = createEvent('drop');\n"
+ "dispatchEvent(destination, dropEvent,dragStartEvent.dataTransfer);\n"
+ "var dragEndEvent = createEvent('dragend');\n"
+ "dispatchEvent(element, dragEndEvent,dropEvent.dataTransfer);\n" + "}\n" + "\n"
+ "var source = arguments[0];\n" + "var destination = arguments[1];\n"
+ "simulateHTML5DragAndDrop(source,destination);", from, to);
}
Related
I'm using Java High level rest client in my project and i want to limit my indices based on document count. I'm using rollover api but its not creating indices automatically.
The code will be given below.
I'm creating index pattern so that my custom analyzer will be applied to all other indices that follow the respective pattern.
PutIndexTemplateRequest request = new PutIndexTemplateRequest("testingtemplate");
request.source("{\n" +
" \"index_patterns\":[\n" +
" \"test_log-*\"\n" +
" ],\n" +
" \"settings\": {\n" +
" \"analysis\": {\n" +
" \"analyzer\": { \n" +
" \"my_analyzer\": {\n" +
" \"type\": \"custom\",\n" +
" \"tokenizer\": \"whitespace\",\n" +
" \"filter\": []\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"mappings\": {\n" +
" \"properties\": {\n" +
" \"fullLog\": {\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"my_analyzer\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }",XContentType.JSON);
return client.indices().putTemplate(request,RequestOptions.DEFAULT).isAcknowledged();
My Rollover code. Here i want to rollover one when index gets one or document.
final RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
boolean isIndexTemplateCreated = createIndexTemplate(client);
System.out.println(isIndexTemplateCreated);
CreateIndexRequest request = new CreateIndexRequest("test_log-1");
request.alias(new Alias("temp_alias_new"));
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
RolloverRequest roll_req = new RolloverRequest("temp_alias_new",null);
roll_req.addMaxIndexAgeCondition(new TimeValue(7, TimeUnit.DAYS));
roll_req.addMaxIndexDocsCondition(1);
roll_req.addMaxIndexSizeCondition(new ByteSizeValue(5, ByteSizeUnit.GB));
RolloverResponse rolloverResponse = client.indices().rollover(roll_req, RequestOptions.DEFAULT);
Map<String,Object> map = new HashMap<>();
map.put("fullLog","Hi");
client.index(new IndexRequest("temp_alias_new").source(map), RequestOptions.DEFAULT);
map.put("fullLog","hello");
client.index(new IndexRequest("temp_alias_new").source(map), RequestOptions.DEFAULT);
But the code is not working and the rollover api is not creating indices automatically. All the 2 documents are stored only in test_log-1 index.
Is there any mistake in my code?
Thanks
Note: Rollover will not happen automatically.
Elasticsearch tries to rollover the index on getting a rollover request.
For example consider the following sequences:
You have a new index test_log-1 which is empty and is being pointed by the alias temp_alias_new.
If you try to rollover now, none of the conditions mentioned along with rollover request holds good as the index is new and empty. So this time rollover fails.
Add some documents to the index.
Now try the rollover with the condition maxIndexDocsCondition(1), it will rollover. Because the condition holds good.
Update
With the latest release of elastic search, you can use ILM (Index Life cycle Management) to automate the rollover.
Here is doc link for more info: https://www.elastic.co/guide/en/elasticsearch/reference/7.x/getting-started-index-lifecycle-management.html
So in Java, I have this as my json String:
public static void main(String[] args) {
String stringJson = "{\n" +
"nodes: {\n" +
"Random-key-Here: {\n" +
"name: \"PRO-cnt-elastic2-4-i-0a414518a5b67\",\n" +
"transport_address: \"172.18.7.104:9300\",\n" +
"host: \"189.88.7.884\",\n" +
"ip: \"188.88.8.884:8880\",\n" +
"roles: [\n" +
"\"ingest\"\n" +
"],\n" +
"attributes: {\n" +
"zone: \"us-east-1a\"\n" +
"},\n" +
"tasks: {\n" +
"Random-key-Here: {\n" +
"node: \"-2688888mRPYHywWA\",\n" +
"id: 37202060,\n" +
"type: \"transport\",\n" +
"action: \"indices:data/write/reindex\",\n" +
"status: {\n" +
"total: 4869544,\n" +
"updated: 13920,\n" +
"created: 3654080,\n" +
"deleted: 0\n" +
"},\n" +
"description: \"blaaa\",\n" +
"start_time_in_millis: 1596456902705,\n" +
"running_time_in_nanos: 647855785005,\n" +
"cancellable: true,\n" +
"headers: { }\n" +
"}\n" +
"}\n" +
"}\n" +
"}\n" +
"}";
JsonObject jo = new JsonParser().parse(stringJson).getAsJsonObject();
Set s = jo.get("nodes").getAsJsonObject().entrySet().stream().map(e ->
e.getValue().getAsJsonObject().get("tasks").collect(toSet());
}
Important: notice inside the Json some of the Keys are actually a random string that I couldn't know what it is in advance... - so I Wrote them as "Random-key-Here"
In short: My goal is to retrieve the number of this field, "total: 4869544".
Above that's what I've tried. I've managed to have a list that contains one object member of a set, and it's the "Random-key-Here" as the key, and the value is the rest of my nested json.
I thought if I would repeat the same logic as I did to overcome the first "Random-key-Here" thing, like I did with
.entrySet().stream().map(e ->
e.getValue().getAsJsonObject().get("tasks")
then I would get to another level below, so instead of "tasks" I wrote "status"
and I tought then I would be able to get the rest of the nested json which is easier from then on... but instead, nothing is returned when doing that:
jo.get("nodes").getAsJsonObject().entrySet()
.stream()
.map(e -> e.getValue().getAsJsonObject().get("tasks").getAsJsonObject().entrySet()
.stream()
.map(ent-> ent.getValue().getAsJsonObject().get("status").getAsJsonObject().get("total").getAsJsonObject()))
would appreciate any help to get to the nested part I need which is: "total: 4869544".
and keep in mind, I can't simply just use this:
jo.get("nodes").getAsJsonObject().get("Random-key-Here").getAsJsonObject().get("tasks")
.getAsJsonObject().get("Random-key-Here").getAsJsonObject()
.get("status").getAsJsonObject().get("total").getAsInt()
because of "Random-key-Here".
Tnx for the helpers!
Answer to myself: So, on every unknown key that you have, you can use entrySet()
and then loop over it until you get to your desired field member.
so this usage solves the problem and can get you the nested Json even when your key is unknown in advance:
jo.get("nodes").getAsJsonObject().entrySet()
.forEach(node -> node.getValue().getAsJsonObject().get("tasks").getAsJsonObject().entrySet()
.forEach(task -> { int i = task.getValue().getAsJsonObject().get("status").getAsJsonObject().get("total").getAsInt();
System.out.println(i); }))
pls share if someone has a more efficient way to do so
Can anyone provide me a failsafe(ish) method for selecting text from dropdowns on this page I am practicing on?
https://www.club18-30.com/club18-30
Specifically, the 'from' and 'to' airport dropdowns. I am using the following code:
public void selectWhereFrom(String query, String whereFromSelect) throws InterruptedException {
WebElement dropDownContainer = driver.findElement(By.xpath(departureAirportLocator));
dropDownContainer.click();
selectOption(query,whereFromSelect);
}
public void selectOption(String query, String option) {
String script =
"function selectOption(s) {\r\n" +
" var sel = document.querySelector(' " + query + "');\r\n" +
" for (var i = 0; i < sel.options.length; i++)\r\n" +
" {\r\n" +
" if (sel.options[i].text.indexOf(s) > -1)\r\n" +
" {\r\n" +
" sel.options[i].selected = true;\r\n" +
" break;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"return selectOption('" + option + "');";
javaScriptExecutor(script);
}
This seems to successfully populate the box with text but when I hit 'Search' I then receive a message saying I need to select an option, suggesting it has not registered the selection?
I would rather avoid JavaScriptExecutor but haven't been able to make these Selects work with a regular Selenium Select mechanism
I would set up a function for each dropdown, one for setting the departure airport and another for setting the destination airport. I've tested the code below and it works.
The functions
public static void setDepartureAirport(String airport)
{
driver.findElement(By.cssSelector("div.departureAirport div.departurePoint")).click();
String xpath = "//div[contains(#class, 'departurePoint')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
public static void setDestinationAirport(String airport)
{
driver.findElement(By.cssSelector("div.destinationAirport div.airportSelect")).click();
String xpath = "//div[contains(#class, 'destinationAirport')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
and you call them like
driver.get("https://www.club18-30.com/club18-30");
setDepartureAirport("(MAN)");
setDestinationAirport("(IBZ)");
I would suggest that you use the 3-letter airport codes for your search, e.g. "(MAN)" for Manchester. That will be unique to each airport but you can use any unique part of the text.
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.
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