HTML UNIT FOUND: INTERNAL ERROR: Oops! Exiting - htmlunit

I'm new to the HTMLUNIT, When I run the below code.
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
public class WeBrowser {
public void homePage() throws Exception {
final WebClient webClient = new WebClient();
// Get the first page
final HtmlPage page1 = webClient.getPage("http://some_url");
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
final HtmlForm form = page1.getFormByName("myform");
final HtmlSubmitInput button = form.getInputByName("submitbutton");
final HtmlTextInput textField = form.getInputByName("userid");
// Change the value of the text field
textField.setValueAttribute("root");
// Submit the form by clicking the button and get back the second page.
final HtmlPage page2 = button.click();
webClient.closeAllWindows();
}
}
It shows the following Error :
Exception in thread "main" org.apache.bcel.verifier.exc.AssertionViolatedException:
FOUND:
INTERNAL ERROR: Oops!
Exiting!!
at org.apache.bcel.verifier.exc.AssertionViolatedException.main(AssertionViolatedException.java:102)

Yesterday I have almost same problem, Alhtough it looks odd but try by debugging rather than running, or add some delay before clicking submit button
Thread.sleep(10000);
and also take a look at this answer AssertionViolatedException

I was getting the same error using eclipse to run java code that had previously worked ok. After using 'project>>clean>>all projects' the problem disappeared. Don't know what triggered it but all projects in the workspace were affected.

Related

Wicket page is refreshed if use ajax after form is submitted with target=_blank

I have a preview button. When user press preview, form is submitted on new tab to show a pdf file have data in form.
I use a custom SubmitLink to do that
SubmitResourceLink
public abstract class SubmitResourceLink extends SubmitLink implements IResourceListener {
private final IResource resource;
#Override
public final void onResourceRequested() {
Attributes a = new Attributes(RequestCycle.get().getRequest(), RequestCycle.get().getResponse(), null);
resource.respond(a);
}
Implement on form
new SubmitResourceLink("previewBtn", form, new JasperReportsResource() {
private static final long serialVersionUID = -2596569027102924489L;
#Override
public byte[] getData(Attributes attributes) {
return control.getExportPreviewByteStream(estimateModel.getObject());
}
}) {
private static final long serialVersionUID = 1L;
#Override
protected String getTriggerJavaScript() {
String js = super.getTriggerJavaScript();
js = "document.getElementById('" + form.getMarkupId() + "').target='_blank';" + js;
return js;
}
#Override
public void onSubmit() {
form.add(AttributeModifier.append("target", Model.of("_blank")));
processInputs(form);
onResourceRequested();
}
}.setDefaultFormProcessing(false);
When I press preview, a new tab is opend. But when I input in any ajax component (ex:AutoCompleteTextField), ajax reponse data xml: <ajax-response><redirect>....</redirect></ajax-response> and refresh page.
Now, I want after press preview, I still use current form normaly.
Thank.
This is caused by the "stale page protection" in Wicket.
The first click opens the same page instance in a new tab/window. This increments the page's renderCount counter, i.e. it says "this page has been rendered N times".
The links in Wicket look like ?2-1.ILinkListener-component~path. Here '2' is the page id and '1' is the page render count.
So the links in tab1 have renderCount 'N', and the links in tab2 - 'N+1'.
Clicking on a link in tab1 will fail with StalePageException that tells Wicket "the user is trying to use an obsolete version of the page. Please render the latest version of the page so the user can try again".
This protection is needed because the user may do many actions in tab3, e.g. replace a panel that replaces/hides the link the user wants to click in tab1. If there is no such protection Wicket will either fail with
ComponentNotFoundException while trying to click the Link or even worse can do the wrong action if the Link/Button is in a repeater and the repeater has changed its items in tab2.
To overcome your problem you should open a new page instance in tab2, i.e. it submits the form but in onSubmit() does something like setResponsePage(getPage().getClass()). This way it won't re-render the current page instance N+1 time.

how to prevent confirm alert In Spring MVC on F5

In Spring I usually did a redirect-after-submit(get method mapping) to prevent the user of submitting a form ,
but when i pressing F5 it will go to get method mapping again and display me this kind of confirm message. how could i prevent this message every time on F5.
Here is the code for controller -
ScheduleDetail objScheduleDetail = new ScheduleDetail();
HttpSession session = request.getSession(true);
String condition = "";
try{
int careProfessionalIDF = (Integer) session.getAttribute("careProfessionalIDF");
condition = "CareProfessionalIDF = "+careProfessionalIDF;
objScheduleDetail.setCareProfessionalIDF(careProfessionalIDF);
}catch (Exception e) {
int careProviderIDF = (Integer) session.getAttribute("careProviderIDF");
condition = "CareProviderIDF = "+careProviderIDF;
objScheduleDetail.setCareProviderIDF(careProviderIDF);
}
List<ScheduleDetail> ScheduleDetailList = objScheduleDetailManager.getAllScheduleDetail(condition+" ORDER BY ScheduleDetailIDP DESC");
model.addObject("List_of_ScheduleDetail",ScheduleDetailList);
model.addAttribute("ScheduleDetail", objScheduleDetail);
return "hospital/scheduleDetail";//jsp page
edited code
#RequestMapping("/editAddressType.html")
public String editAddressType(ModelMap model,HttpServletRequest request)
{
int addressTypeIDP = Integer.parseInt(request.getParameter("AddressTypeIDP"));
AddressType objAddressType = new AddressType();
objAddressType = objAddressTypeManager.getByID(addressTypeIDP);
model.addAttribute("AddressType", objAddressType);
return "jsp/addressType";
it open addressType.jsp with data tht we bind with `model.addAttribute`. now if i press F5 it show alert message as above image.
**get method**
#RequestMapping(value="/getAddressType.html", method=RequestMethod.GET)
public String getAddressType(ModelMap model, HttpServletRequest request) throws RemoteException
{
AddressType objAddressType = new AddressType();
model.addAttribute("AddressType", objAddressType);
return "hospital/addressType";
}
If you implement the POST - REDIRECT - GET pattern correctly, you will not see the warning from the browser that you mentioned. The warning is shown when the Page being viewed is in response to a POST request. The traditional pattern, FORM - POST - SUCCESS page.
The code you provided in the question is not enough to reach the root cause of the problem. I'm listing key points of the implementation here, please compare with your code and you'll understand what the mistake is.
To show the user the form, where they are supposed to enter data for submission. (Just the starting point, could be any page in your application.)
#RequestMapping(value = "/checkout/{cartId}.htm", method = RequestMethod.GET)
public ModelAndView showCheckoutForm(...) {
......
return new ModelAndView("/WEB-INF/jsp/form.jsp")
}
The form POSTs to a handler method, which issues a redirect to the user, pointing to a URL that will show the details of the resource created as a result of the POST.
#RequestMapping(value = "/checkout/{cartId}.htm", method = RequestMethod.POST)
public View submitCheckoutForm(....) {
return new RedirectView("/checkout/confirmation/" + cartId + ".htm");
}
The details of the created resource will be shown by a handler method like the following. Note that at this point, if your implementation worked properly, the URL in the user's browser will change to the path redirected by the POST handler. And a fresh GET request will be issued to the server.
#RequestMapping(value = "/checkout/confirmation/{cartId}.htm", method = RequestMethod.GET)
public ModelAndView showCheckoutConfirmation(....) {
return new ModelAndView("viewThatShowsCheckoutConfirmation");
}
If your implementation is similar, the confirmation page is a result of a GET request, so browsers won't issue a warning for re-POSTing data if you refresh the page.
My suspicion is that your POST handler is not issuing a redirect to the user, it is instead rendering the confirmation page itself.
Hope this helps. Please let me know if this does not solve your problem.

HTML Unit - login to secure website using form - can't connect to page after form

I'm a newbie to java htmlunit so any help would be greatly appreciated - Thanks in advance.
I'm trying to login to a webpage that is protected with username and password authentication by submitting a username and password to the form on the webpage using htmlunit to mirror the actions of a web browser. The website itself has form based authorisation.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.Set;
//Import htmlunit classes
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.gargoylesoftware.htmlunit.util.Cookie;
//This Class attempts to submit user and password credentials
//and mirrors how a login button would be clicked on a webpage:
public class submitForm {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
// Get the first page
HtmlPage page1 = (HtmlPage) webClient.getPage("http://cmdbjr/frameset.php?ci_name=&ci_id=&ci_type=");
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
HtmlForm form = page1.getFormByName("loginform");
// Enter login and passwd
form.getInputByName("user_id").setValueAttribute("#####");
form.getInputByName("password").setValueAttribute("#####");
// Click "Sign In" button/link
page1 = (HtmlPage) form.getInputByValue("Log In").click();
// I added the cookie section but this returns a null pointer exception
Set<Cookie> cookie = webClient.getCookieManager().getCookies();
if(cookie != null){
Iterator<Cookie> i = cookie.iterator();
while (i.hasNext()) {
webClient.getCookieManager().addCookie(i.next());
}
}
// Get page as Html
String htmlBody = page1.getWebResponse().getContentAsString();
// Save the response in a file
String filePath = "c:/temp/test_out.html";
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath)));
bw.write(htmlBody);
bw.close();
// Change the value of the text field
// userField.setValueAttribute("alwalsh");
// passwordField.setValueAttribute("1REland6");
// Now submit the form by clicking the button and get back the second page.
// final HtmlPage page2 = button.click();
webClient.closeAllWindows();
}
}
If I run the code without the cookie section of code the page I am trying to reach which
is after the login page doesn't appear an error page appears saying I'm not connected to the internet.
If the code is run with the cookie section the error:
Exception in thread "main" >java.lang.NullPointerException at contentWeb.main(contentWeb.java:26)
is returned.
I'm new to java htmlunit so any help at all would be greatly appreciated.
Thanks in advance.
I replicated your example with my yahoo mail login credentials and it worked. However, I added : webClient.setThrowExceptionOnScriptError(false); to ignore exceptions on script errors.

Use HtmlUnit to search google

The following code is an attempt to search google, and return the results as text or html.
The code was almost entirely copied directly from code snippets online, and i see no reason for it to not return results from the search. How do you return google search results, using htmlunit to submit the search query, without a browser?
import com.gargoylesoftware.htmlunit.WebClient;
import java.io.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import java.net.*;
public class GoogleSearch {
public static void main(String[] args)throws IOException, MalformedURLException
{
final WebClient webClient = new WebClient();
HtmlPage page1 = webClient.getPage("http://www.google.com");
HtmlInput input1 = page1.getElementByName("q");
input1.setValueAttribute("yarn");
HtmlSubmitInput submit1 = page1.getElementByName("btnK");
page1=submit1.click();
System.out.println(page1.asXml());
webClient.closeAllWindows();
}
}
There must be some browser detection that changes the generated HTML, because when inspecting the HTML with page1.getWebResponse().getContentAsString(), the submit button is named btnG and not btnK (which is not what I observe in Firefox). Make this change, and the result will be the expected one.
I've just checked this. It's actually 2 ids for 2 google pages:
btnK: on the google home page (where there's 1 long textbox in the middle of the screen). This time the button's id = 'gbqfa'
btnG: on the google result page (where the main textbox is on top of the screen). This time the button's id = 'gbqfb'

Navigation using RelayCommand<T> in MVVM Light

I have been following Jesse Liberty's tutorial on MVVM Light for Windows Phone 7, but I'm stuck on this problem. I need to navigate from a main page to a detail page. Following the tutorial, I'm using a RelayCommand in the MainViewModel:
public RelayCommand<Customer> DetailsPageCommand { get; private set;}
I then initialize it in the constructor:
DetailsPageCommand = new RelayCommand<Customer>((msg) => GoToDetailsPage(msg));
Finally you implement the GoToDetailsPage method:
private object GoToDetailsPage(Customer msg)
{
System.Windows.MessageBox.Show("Go to details page with: " +
msg.First +
" " +
msg.Last );
return null;
}
Showing the message box works, but I'm not sure how to navigate to the detail page instead. In previous sections of the tutorial page navigation was handled with something like this:
var msg = new GoToPageMessage {PageName = "DetailPage"};
Messenger.Default.Send(msg);
You'll need to register to receive messages of that type and then navigate appropriately.
The following assumes a page name and that you're navigating to details of the specific customer by passing their Id in the query string.
Messenger.Default.Register<Customer>(
this,
c => NavigationService.Navigate("/Pages/CustomerDetails.xaml?cid=" + c.Id));
You'd then adjust your code accordingly:
private void GoToDetailsPage(Customer msg)
{
Messenger.Default.Send(msg);
}
I hope this helps.

Resources