Is there a way to read an input value as in JavaScript using java - elemental2?
My entire code looks like this:
public void onModuleLoad() {
document.body.style.margin = MarginUnionType.of("0");
document.body.appendChild(navigation());
document.body.appendChild(mainSection());
}
// *********************** //
// Elemental methods
public static HTMLElement mainSection() {
// create list
HTMLElement ul = (HTMLElement) document.createElement("ul");
ul.style.listStyle = "none";
HTMLElement li = (HTMLElement) document.createElement("li");
li.textContent = "Tasks";
ul.appendChild(li);
return ul;
}
public static HTMLElement navigation() {
// create button
HTMLButtonElement button = (HTMLButtonElement) document.createElement("button");
button.textContent = "Add Task";
button.addEventListener("click", evt -> onAddTask());
// create main nav
HTMLElement mainNav = (HTMLElement) document.createElement("nav");
mainNav.className = "main-nav";
mainNav.appendChild(addInput());
mainNav.appendChild(button);
return mainNav;
}
public static HTMLInputElement addInput() {
// create input
HTMLInputElement input = (HTMLInputElement) document.createElement("input");
input.placeholder = "Enter your name here";
input.id = "tasks-input";
return input;
};
public static void onAddTask() {
alert(document.getElementById("tasks-input").getAttribute("value"));
}
}
Basically when I click on the button I want to print whatever I typed into the input.
Thanks!
Generally with elemental2 you can use a DOM API object's property directly. So according to:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
you can do the following in java with elemental2:
HTMLInputElement input;
input.value = "foo";
String value = input.value;
Related
My problem is simple but I have no clue how to solve it. I have a feedbackPanel and I want to show an error message if the BootstrapDownloadLink fails. With a submit I could easily do:
protected void onSubmit(AjaxRequestTarget target) {
...
error("File_not_found"); //Wicket will print this on the feedback panel
target.add(getModalPanel().getFeedbackPanel()); //But i need to refresh it first
}
But the button is inside a panel which I fill with a populateItem and is the only way I know to insert Bootstrap Styles to it. The code of the button:
BootstrapDownloadLink downloadDocument = new BootstrapDownloadLink(IDITEMREPEATER, file) {
#Override
public void onClick() {
File file = (File)getModelObject();
if(file.exists()) {
IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));
getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream, file.getName()));
} else {
error(getString("error_fichero_no_existe"));
/// ???? need to refresh-> getModalPanel().getFeedbackPanel()
}
}
};
downloadDocument.setIconType(GlyphIconType.clouddownload);
downloadDocument.add(new AttributeModifier("title", getString("documentos.descargar")));
downloadDocument.add(new AttributeModifier("class", " btn btn-info negrita btn-xs center-block"));
downloadDocument.setVisible(Boolean.TRUE);
list.add(downloadDocument);
You could create or extend from an AjaxDownloadLink, for example like here.
The main idea is to have an AjaxBehavior that does the download, and you get a public void onClick(AjaxRequestTarget target) in which you can add the FeedbackPanel
downloadBehavior = new AbstractAjaxBehavior()
{
private static final long serialVersionUID = 3472918725573624819L;
#Override
public void onRequest()
{
[...]
ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(
AjaxDownloadLink.this.getModelObject(), name);
handler.setContentDisposition(ContentDisposition.ATTACHMENT);
getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
}
};
And use that behavior in the onclick:
#Override
public void onClick(AjaxRequestTarget aTarget)
{
String url = downloadBehavior.getCallbackUrl().toString();
if (addAntiCache) {
url = url + (url.contains("?") ? "&" : "?");
url = url + "antiCache=" + System.currentTimeMillis();
}
// the timeout is needed to let Wicket release the channel
aTarget.appendJavaScript("setTimeout(\"window.location.href='" + url + "'\", 100);");
}
You can use target.addChildren(getPage(), IFeedback.class). This will add all instances of IFeedback interface in the page to the AjaxRequestTarget.
You can also use FeedbackPanel.class instead of the interface.
Or use getPage().visit(new IVisitor() {...}) to find a specific feedback panel if you don't want to add others which are not related.
I use oracle-adf via xml menu model. Now I want to start download file on one of itemNode and without redirect. I'm tried to define action attribute with method which invokes hidden button's method(this button has inner fileDownloadActionListener) through javascript. But it doesn't work. Is it correct? or there is other way to decide this problem? Or may be it is impossible at all?
Hidden button code:
<af:commandButton text="NONE"
id="downloadInstructionsBtn"
action=" "
visible="false"
clientComponent="true"
partialSubmit="false">
<af:fileDownloadActionListener filename="Инструкции пользователя"
contentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
method="#{pageFlowScope.vocsReportsRegionController.instructionsDownload}"/>
</af:commandButton>
Item node code:
<itemNode id="userInstructionsDownloadFlow" label="Инструкции пользователя"
focusViewId="#"
action="#{pageFlowScope.vocsReportsRegionController.invokeInstructionDownload}"
partialSubmit="true"
clientComponent="true"/>
Javascript cut:
function handleInstructionsDownload(event) {
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
Methods' description:
public void invokeInstructionDownload(){
FacesContext context = FacesContext.getCurrentInstance();
ExtendedRenderKitService erks =
Service.getService(context.getRenderKit(),
ExtendedRenderKitService.class);
erks.addScript(context, "handleInstructionsDownload();");
}
public void instructionsDownload(FacesContext context,
OutputStream out) throws IOException{
File f = new File("C:\\Users\\apozdnyakov\\Downloads\\Типы_контроля_время.xlsx");
FileInputStream fis;
byte[] b;
try {
fis = new FileInputStream(f);
int n;
while ((n = fis.available()) > 0) {
b = new byte[n];
int result = fis.read(b);
out.write(b, 0, b.length);
if (result == -1)
break;
}
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
}
I think there are a few possible reasons of your problem.
1- handleInstructionsDownload javascript function couldn't find the component, because of hierarchy of the jsf codes. You can add log in javascript function, for understanding that.
function handleInstructionsDownload(event) {
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
if (downloadBtn == null) {
console.log('The component is null!');
}
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
If you see this log in javascript console you should control your hierarchy of jsf codes. And you should access to button by true component id.
2- invokeInstructionDownload java method couldn't find or call the javascript handleInstructionsDownload function. You can add log in the first line of the javascript function like that:
function handleInstructionsDownload(event) {
console.log('The js function fired!');
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
If there is this log in console, you should change your javascript method calling. But I think your Java method is true :)
3- If these are not solutions of your problem, you can change your calling the hidden button like that.
Hidden button code:
<af:commandButton text="NONE"
id="downloadInstructionsBtn" action=" "
visible="false"
clientComponent="true"
partialSubmit="false"
binding="#{pageFlowScope.vocsReportsRegionController.downloadInstructionsBtn}">
<af:fileDownloadActionListener filename="Инструкции пользователя"
contentType="application/vnd.openxmlformats officedocument.spreadsheetml.sheet"
method="#{pageFlowScope.vocsReportsRegionController.instructionsDownload}"/>
</af:commandButton>
ManagedBean code:
private RichButton downloadInstructionsBtn;
public RichButton getDownloadInstructionsBtn() {
return downloadInstructionsBtn;
}
public void setDownloadInstructionsBtn(RichButton downloadInstructionsBtn) {
this.downloadInstructionsBtn = downloadInstructionsBtn;
}
public void invokeInstructionDownload(){
ActionEvent actionEvent = new ActionEvent((UIComponent) downloadInstructionsBtn);
actionEvent.queue();
}
NewForm.java
public class NewForm extends WebPage {
private Bean bean;
private DropDownClass dropdown;
private String selected = "choice";
void init()
{
bean = new Bean();
dropdown=new DropDownClass("test");
}
public NewForm(final PageParameters page) {
init();
final TextField<String> textname = new TextField<String>("name",Model.of(""));
textname.setRequired(true);
final DropDownChoice<String> dropname = new DropDownChoice<String>("type", new PropertyModel<String>(this, "selected"),
dropdown.getlist());
Form<?> form = new Form<Void>("Form") {
#Override
public void onSubmit() {
final String name = (String) textname.getModelObject();
final String dropdown = (String)dropname.getModelObject();
bean.add(name,dropdown);
final String schema = bean.getJsonSchema().toString();
page.add("schema", schema);
setResponsePage(new NewForm(page));
}
};
Label schemalabel = new Label("schema", page.get("schema"));
add(form);
form.add(textname);
form.add(dropname);
form.add(schemalabel);
}
}
Bean.java
public class Bean
{
private JSONObject jsonSchema;
public JSONObject getJsonSchema() {
return jsonSchema;
}
public void setJsonSchema(JSONObject jsonSchema) {
this.jsonSchema = jsonSchema;
}
public Bean() {
jsonSchema = new JSONObject();
}
public void add(String key,String value)
{
jsonSchema.put(key, value); // I am able to append values each time using "put" or "append" in JSF but not in WICKET.How can I append values in Wicket?
//or jsonSchema.append(key, value); //adding values only once and not appending each time,I enter the values in TextField and DropDown
}
}
In CreateForm.java - I have a Textfield and DropDown. When I enter the values in TextField and DropDown..I am able to convert the values entered in TextField and DropDown as JSON schema from method add(String key,String value) in AttributeInfo.java and display the schema as - {"name":"abc"} //where name is value entered in TextField and abc is from DropDown.
I am able to display the schema only once onSubmit But I need to append the values to schema each time,I enter in TextField and DropDown onSubmit and display in the samepage.
How can I achieve this in Wicket?
I am just a beginner.Any Help would be appreciated.Thankyou in advance.
I am testing Selenium-Webdriver on Google Translate page. What I'm trying to do is:
See if the input language is already presented
If presented, is it selected? If not select it.
If not present, open the more language table. Select (click on) the language on the table.
See if the output language is already presented
If presented, is it selected? If not select it.
If not present, open the more language table. Select (click on) the language on the table.
Finally translate and check result
I don't have any problem with Case 1: Input and Output language already presented and the result is as expected. But with Case 2: Output language is not presented yet and has to be selected on the table, the problem occurs. The language selected is incorrect (for example, I choose Norwegian but finally Samoan will be selected). The select input uses the same way to select but doesn't return any issue at all.
My code below
package TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.*;
public class GoogleTranslate {
WebDriver driver;
#BeforeMethod
public void setUp() {
System.setProperty("webdriver.gecko.driver","F:\\path\\geckodriver.exe");
driver=new FirefoxDriver();
}
#Test(priority=0)
public void VietnameseToEnglish() throws InterruptedException {
// Go to google translate
driver.manage().window().maximize();
driver.get("https://translate.google.com/");
Thread.sleep(5000);
// Check if the page is correct
String currentTitle = driver.getTitle();
Assert.assertEquals(currentTitle, "Google Translate");
Thread.sleep(3000);
// Select Vietnamese as input
if (driver.findElements(By.xpath("//div[#id='gt-lang-left']/div[#id='gt-lang-src']/div[#id='gt-sl-sugg']/div[contains(#class,'goog-inline-block jfk-button jfk-button-standard') and #value='vi']")).size() > 0)
{
WebElement Vi = driver.findElement(By.xpath("//div[#id='gt-lang-left']/div[#id='gt-lang-src']/div[#id='gt-sl-sugg']/div[contains(#class,'goog-inline-block jfk-button jfk-button-standard') and #value='vi']"));
String isViSelected = Vi.getAttribute("aria-pressed");
if (isViSelected.equals("false"))
{
Vi.click();
}
}
else
{
WebElement allLangSrc = driver.findElement(By.id("gt-sl-gms"));
allLangSrc.click();
WebElement ViSrc = driver.findElement(By.xpath("//div[#id='goog-menuitem-group-7']/div[#id=':2r']/div"));
ViSrc.click();
}
// Select English as output
if (driver.findElements(By.xpath("//div[#id='gt-lang-right']/div[#id='gt-lang-tgt']/div[#id='gt-tl-sugg']/div[contains(#class,'goog-inline-block jfk-button jfk-button-standard') and #value='en']")).size() > 0)
{
WebElement En = driver.findElement(By.xpath("//div[#id='gt-lang-right']/div[#id='gt-lang-tgt']/div[#id='gt-tl-sugg']/div[contains(#class,'goog-inline-block jfk-button jfk-button-standard') and #value='en']"));
String isEnSelected = En.getAttribute("aria-pressed");
if (isEnSelected.equals("false"))
{
En.click();
}
}
else
{
WebElement allLangTrg = driver.findElement(By.id("gt-tl-gms"));
allLangTrg.click();
WebElement EnTrg = driver.findElement(By.xpath("//div[#id='goog-menuitem-group-2']/div[#id=':3j']/div"));
EnTrg.click();
}
WebElement Input = driver.findElement(By.id("source-is"));
//Input.clear();
Input.sendKeys("Ga");
WebElement TranslateButton = driver.findElement(By.id("gt-submit"));
TranslateButton.click();
Thread.sleep(3000);
WebElement Output = driver.findElement(By.xpath("//span[#id='result_box']/span"));
String Outtext = Output.getText();
Assert.assertEquals(Outtext, "Chicken");
}
#Test(priority=1)
public void VietnameseToNorg() throws InterruptedException {
// Go to google translate
driver.manage().window().maximize();
driver.get("https://translate.google.com/");
Thread.sleep(5000);
// Check if the page is correct
String currentTitle = driver.getTitle();
Assert.assertEquals(currentTitle, "Google Translate");
Thread.sleep(3000);
// Select Vietnamese as input
if (driver.findElements(By.xpath("//div[#id='gt-lang-left']/div[#id='gt-lang-src']/div[#id='gt-sl-sugg']/div[contains(#class,'goog-inline-block jfk-button jfk-button-standard') and #value='vi']")).size() > 0)
{
WebElement Vi = driver.findElement(By.xpath("//div[#id='gt-lang-left']/div[#id='gt-lang-src']/div[#id='gt-sl-sugg']/div[contains(#class,'goog-inline-block jfk-button jfk-button-standard') and #value='vi']"));
String isViSelected = Vi.getAttribute("aria-pressed");
if (isViSelected.equals("false"))
{
Vi.click();
}
}
else
{
WebElement allLangSrc = driver.findElement(By.id("gt-sl-gms"));
allLangSrc.click();
WebElement ViSrc = driver.findElement(By.xpath("//div[#id='goog-menuitem-group-7']/div[#id=':2r']/div"));
ViSrc.click();
}
// Select Norg as output
if (driver.findElements(By.xpath("//div[#id='gt-lang-right']/div[#id='gt-lang-tgt']/div[#id='gt-tl-sugg']/div[contains(#class,'goog-inline-block jfk-button jfk-button-standard') and #value='no']")).size() > 0)
{
WebElement No = driver.findElement(By.xpath("//div[#id='gt-lang-right']/div[#id='gt-lang-tgt']/div[#id='gt-tl-sugg']/div[contains(#class,'goog-inline-block jfk-button jfk-button-standard') and #value='no']"));
String isNoSelected = No.getAttribute("aria-pressed");
if (isNoSelected.equals("false"))
{
No.click();
}
}
else
{
WebElement allLangTrg = driver.findElement(By.id("gt-tl-gms"));
allLangTrg.click();
WebElement NoTrg = driver.findElement(By.xpath("//div[#id='goog-menuitem-group-5']/div[#id=':52']/div"));
NoTrg.click();
}
WebElement Input = driver.findElement(By.id("source-is"));
//Input.clear();
Input.sendKeys("Sua");
WebElement TranslateButton = driver.findElement(By.id("gt-submit"));
TranslateButton.click();
Thread.sleep(3000);
WebElement Output = driver.findElement(By.xpath("//span[#id='result_box']/span"));
String Outtext = Output.getText();
Assert.assertEquals(Outtext, "Melk");
}
#AfterMethod
public void tearDown(){
driver.close();
driver.quit();
}
}
I would do something like this. You should focus on creating functions that do a single thing so that you have reusable code that can be used in various tests easily.
Here are my functions
static public String getTranslatedText()
{
new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>()
{
public Boolean apply(WebDriver d)
{
return d.findElement(By.id("result_box")).getText().length() != 0;
}
});
return driver.findElement(By.id("result_box")).getText();
}
static public void setSourceLanguage(String lang)
{
// see if the desired language is already selected
if (!driver.findElement(By.cssSelector("#gt-lang-src div.jfk-button-checked")).getText().equals(lang))
{
// open the Source language dropdown
driver.findElement(By.id("gt-sl-gms")).click();
// select the desired language
driver.findElement(By.xpath("//div[#id='gt-sl-gms-menu']//div[text()='" + lang + "']")).click();
}
}
static public void setTargetLanguage(String lang)
{
// see if the desired language is already selected
if (!driver.findElement(By.cssSelector("#gt-lang-tgt div.jfk-button-checked")).getText().equals(lang))
{
// open the Source language dropdown
driver.findElement(By.id("gt-tl-gms")).click();
// select the desired language
driver.findElement(By.xpath("//div[#id='gt-tl-gms-menu']//div[text()='" + lang + "']")).click();
}
}
static public void translateText(String text)
{
driver.findElement(By.id("source")).sendKeys(text);
}
A simple test would look like
driver.get("https://translate.google.com/");
setSourceLanguage("English");
setTargetLanguage("Lao");
translateText("This is some text");
System.out.println(getTranslatedText());
After going through this exercise, I noticed the URL after the text was translated was https://translate.google.com/#en/lo/This%20is%20some%20text. I'm assuming that you aren't testing google translate but instead just want the translations? If that's true, you could just navigate to the URL based on the language tokens and pass in the desired text.
The URL is of the form
https://translate.google.com/#<source language token>/<target language token>/<text to be translated>
So Vietnamese to English would be
https://translate.google.com/#vi/en/This%20is%20some%20text
and Vietnamese to Norwegian would be
https://translate.google.com/#vi/no/This%20is%20some%20text
Then all you would have to do is to grab the translated text.
I have entity for reporting. I wonna know who filled up report. I would like to put id of user from session to form class.
I've tried already methods like: bind, fill; but no working solution found.
Ofcorse I mean form class: play.data.Form.form
How can I achive this?
Please help.
Here is my approach (when I wrote this Post):
static Form<Registry> modelForm = form(Registry.class);
Registry registry = new Registry();
registry.creationUser = User.getCurrentUser();
registry.test="tt";
modelForm.fill(registry);
modelForm.bind(data, allowedFields)
My submit method
#Transactional
public static Result submit() {
modelForm = modelForm.bindFromRequest();
if (modelForm.hasErrors()) {
return badRequest(views.html.Registry.form.render(modelForm));
} else {
modelForm.get();
}
registry.creationUser = User.getCurrentUser();
modelForm.fill(registry);
if (modelForm.hasErrors()) {
Logger.debug(modelForm.toString());
return badRequest(views.html.Registry.form.render(modelForm));
} else {
modelForm.get().toDataBase();
toLog("success", "Succefully added new Report");
flash("success", "Pomyślnie dodano.");
return redirect(routes.Index.index());
}
}
Let's say you have a Report model like:
public Date date;
public User user;
public String message;
You need to create and fill an object first (without saving to DB!) and then fill the form with it, like:
Report report = new Report(); // constructors params are welcome here
report.user = loggedUser;
report.date = new Date();
Form<Report> reportForm = Form.form(Report.class).fill(report);
// OR
Form<Report> reportForm = Form.form(Report.class);
reportForm = reportForm().fill(report);
// NOT
Form<Report> reportForm = Form.form(Report.class);
reportForm().fill(report); // Wrong!
return ok(reportCreatingView.render(reportForm));
Edit: You don't need to fill User data at first step, as actually you can add it after binding, you have too much lines in your submit() action, keep it simple :)
public static Result submit() {
User user = User.getCurrentUser();
if (user == null) return unauthorized("You must log in");
modelForm = modelForm.bindFromRequest();
if (modelForm.hasErrors()) {
return badRequest(views.html.Registry.form.render(modelForm));
}
// At this point you have a logged User obj which is not null,
// you have modelForm without errors (checked previously)
// so you need to only add the user to form and save it.
Registry registry = modelForm.get();
registry.creationUser = user;
registry.save();
flash("success", "Twój log został zapisany w bazie.");
return redirect(routes.Index.index());
}