Using Browserfield.displayContent with <frame> that has an external url - java

I am trying to create a screen for a blackberry 5.0+ app that has a banner at the top and then a Browserfield underneath that views an external site. The banner is hosted on one site and the content for the BrowserField is hosted on another.
Originally I tried using 2 BrowserFields but had issues when several devices did not display the banner and only showed the content underneath. Furthermore when another screen with the same setup was displayed the app would crash with an IllegalStateException. I did a bit of research and it seems that BrowserField seems to have some trouble when several instances of it exist at once.
So in order to get around this issue I have combined both BrowserFields into one, using the frame tag in html, with the hopes of displaying the Banner ad in the first frame and the content underneath in the second frame.
The html I made works in a normal browser:
<!DOCTYPE html>
<html>
<frameset rows="10%,90%">
<frame scrolling="no" src="http://4.bp.blogspot.com/_CZ1HhhanNgc/TI0xscVLW8I/AAAAAAAABps/sfeO4E3234k/s1600/head-mp-700x88.jpg" noresize="noresize" frameborder="0">
<frame src="http://www.penny-arcade.com" frameborder="0">
</frameset>
</html>
What I am doing is reading the html in as text, removing the \n and \rs and then putting it in the following method: browserField.displayContent(html,"http://localhost");
This method is supposed to display the html in the browser, but instead on the simulator I get this:
On the device I get a blank screen. I don't know whats going on with the displayContent() method, so I would assume that it doesn't allow external sites? I don't really know what my options are from this point on. Is there some kind of fix for this, some library that I can use or some other way to implement this?
Edit:
So #Nate suggested a change to the DOCTYPE tag, and posted a screenshot of the html working. However I did this and I still get the same results, so I am going to post the code I'm using to make the screen. Here it is:
public final class MyScreen extends MainScreen
{
/**
* Creates a new MyScreen object
*/
private BrowserField browserField;
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
BrowserFieldConfig config = new BrowserFieldConfig();
config.setProperty(BrowserFieldConfig.VIEWPORT_WIDTH, new Integer(Display.getWidth()));
config.setProperty(BrowserFieldConfig.NAVIGATION_MODE,
BrowserFieldConfig.NAVIGATION_MODE_POINTER);
config.setProperty(BrowserFieldConfig.INITIAL_SCALE, new Float(1.0));
config.setProperty(BrowserFieldConfig.USER_SCALABLE, Boolean.FALSE);
//supposed to prevent InvalidStateException from refreshing sometimes
ProtocolController eventsProtocolController = new ProtocolController(browserField)
{
public void handleNavigationRequest(BrowserFieldRequest request) throws Exception
{
browserField.setFocus();
super.handleNavigationRequest(request);
}
};
config.setProperty(BrowserFieldConfig.CONTROLLER, eventsProtocolController);
browserField = new BrowserField(config);
try
{
String embeddedLinkFrame = readTextFile("frame.html");
browserField.displayContent(embeddedLinkFrame, "http://localhost");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
add(browserField);
}
public String readTextFile(String fName)
{
String result = null;
DataInputStream is = null;
try
{
is = new DataInputStream(getClass().getResourceAsStream("/" + fName));
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (null != is)
is.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
return result;
}
}

Ok, my apologies for the first answer. I think DOCTYPE was a red herring (but I didn't have your Java code at the time).
I see a few potential problems:
Network Connectivity
First, as is always the case, make sure you have network connectivity for your device, or simulator. That may include the MDS simulator running. You can always test connectivity with the normal Browser app, checking a website you know to be running. I believe that if you have a total lack of connectivity (i.e. network disabled), then you will get your frames showing just the text / URLs. However, I believe it will also have something like this:
Could not select proper Transport Descriptor for: http://www.penny-arcade.com
instead of showing null, as you show.
Adding BrowserField
Next, I think there is a problem with you asking the browser field to display content before you've added the field. Simply switch the order of those two lines of code to this:
add(browserField);
try
{
String embeddedLinkFrame = readTextFile("frame.html");
browserField.displayContent(embeddedLinkFrame, "http://localhost");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
I believe the behaviour if you have these lines out of order, however, is just to get a blank browser field.
Viewport Properties
Lastly, I would not recommend setting page properties programmatically, as you've done. Although this is not going to keep your page from displaying, I'd recommend putting those properties in HTML meta elements:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
Source: BlackBerry.com
Update: Protocol Controller
Unfortunately, my simulator is acting up, and declining to support hot-swap right now. So, it's hard for me to run many times, and collect decisive results. But, it looks to me like removing your ProtocolController object prevents this problem from happening for me. (maybe you can clarify why you're using the protocol controller in this situation?). If this answer was a motivation, you might look carefully at the poster's full comments about it's usefulness.

Related

Opening an URL from default browser crashes the application

I have a GUI application written in JavaFX 14 (not the XML one). I currently have three lists that are connected each to a different custom class, in whom exists an ObservableList which updates the ListViews. I have three. Upon doubleclicking on an element of the first ListView, which also contains URLs, I want to open said URL inside the default browser, no matter the OS (I'm programming on Ubuntu 20.04, and this app will be used on W10 too).
listSquads.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(event.getClickCount()==2) {
try {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI(bot.getSquadHandler().extractURL(listSquads.getSelectionModel().getSelectedItem())));
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
});
This is the code. The bot is a custom TwitchBot object, based on pIRCbot libraries. The squadHandler mentioned in the getter method is said custom class. Extract URL is a method that, as the name would suggest, extracts the exact URL given a string as input - this part works, as it's called upon in other parts of the code and works correctly, and I've also tested it.
However, upon double clicking on any given element of the ViewList, the app freezes to then crash a few seconds later. Why could that be? Is there a way to open the browser no matter the OS?
Thanks in advance! :)

Information on Server Is Not Updated

I've been testing HtmlUnit with a few sites; in all these sites,they have
elements such as a radio button or checkbox that when you click, then your
profile on that site is updated; you don't need to submit a form or
anything. But when I take the exact same actions with HtmlUnit, my profile
on the server is not really updated. Do I have to do something special
such as synchronizing the local copy of the page that HtmlUnit has with the
server so that the server sees the change? As an example, I have added my
code for switching my resume on a website from private/public and vice
versa. When I visit the page on a browser, all I have to do is click one
of the two radio buttons to make the resume public/private; but when I do
the same on HtmlUnit, and then go and visit the page on a browser to check, I can see that the information on the server hasn't been changed. I've
included my code below. Note that I have another method which logs in to
the site, and I know that I login correctly. Given this is happening
with my sites for me, I thought maybe there is something like synchronizing with the server that I'm not doing.
=====================================
public void update(String urlOfThePage)
{
// First, declare any element name or xapth that you are going to
use. String xpathOfIsPublicRadioButton = "//input[#id='privacy_show']";
String xpathOfIsPrivateRadioButton = "//input[#id='privacy_hide']";
// Get the first page
try
{
final HtmlPage resumePage = (HtmlPage) webclient.getPage(urlOfThePage);
CrawlerUtility.savePage(resumePage, "resumePage");
final HtmlRadioButtonInput makePublicRadioButton =
(HtmlRadioButtonInput)
resumePage.getFirstByXPath(xpathOfIsPublicRadioButton);
final HtmlRadioButtonInput makePrivateRadioButton =
(HtmlRadioButtonInput)
resumePage.getFirstByXPath(xpathOfIsPrivateRadioButton);
Page result = null;
if (isProfilePublic())
{
result = makePrivateRadioButton.click();
System.out.println("The Profile is changed to private
now.");
Thread.sleep(60000);
}
else
{
result = makePublicRadioButton.click();
System.out.println("The Profile is changed to public now.");
Thread.sleep(60000);
}
}
catch (Throwable e)
{
e.printStackTrace();
}//End of try/catch block.
}//End of update().
If you don't submit a form, then you may be using AJAX behind the scenes to send data to the server. HTML unit won't send the same to the server since it will not process the AJAX requests. What you need is something more sophisticated such as Sikuli http://www.sikuli.org which actually clicks on elements on your webpage in the exact same way a user does. You can also try Selenium (http://www.seleniumhq.org/) which is specific to web browsers.

Get page's html source using a Java applet

I know in scripting languages like Python that this is possible but I know that Java applets can't access other servers other than their own.
I don't know/think I can get this applet signed. Is there a way to use PHP to do what I want to accomplish?
I also know that this code will go to google.com
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
public class tesURL extends Applet implements ActionListener{
public void init(){
String link_Text = "google";
Button b = new Button(link_Text);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){
//get the button label
Button source = (Button)ae.getSource();
String link = "http://www."+source.getLabel()+".com";
try
{
AppletContext a = getAppletContext();
URL u = new URL(link);
// a.showDocument(u,"_blank");
// _blank to open page in new window
a.showDocument(u,"_self");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
That is assuming that source.getLabel() is "google"
But how would I get the source html of that page?
The source html is dynamic and is updated every few seconds or miliseconds. But, the html is also updated, so I can still read the dynamic content directly from the html. I already did this in vb.net, but now I need to port it to Java, but I can't figure out how to access a page's html source; that's why I'm asking.
AppletContext.showDocument opens a page in the browser, much like a hyperlink in HTML or a similar call in JavaScript would do. Under the Same Origin Policy you will not have access to this page if it is from a different site, even if the page is in an iframe.
Some sites may have a crossdomain.xml policy file that allows access if you were to read the contents of the java.net.URL directly. However, www.google.com appears to be using a restricted form that I don't believe is currently supported by the Java PlugIn.
Someone will probably suggest signing your applet, which turns off the "sandbox" security feature of Java. You would then need to persuade your users to trust your ability to publish safe signed code.

Load a page and then execute javascript on page load

I want to make a button in NetBeans, that when clicked, will open a webpage, wait until the webpage loads, and logs in to that site. I have some code here, but I am not sure what to do after this:
javascript:(function (){
window.open("http://www.stackoverflow.com");
object.onload="LoginToThisSite"
})();
I also have a bookmarklet that logs you in to the site automatically, I am just not sure how to tie that in to the button.
Here is the code I have in NetBeans for the button:
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if (cmd == "POST") {
try {
String url = "http://www.stackoverflow.com";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
}
catch (java.io.IOException e) {
System.out.println("Couldn't open browser...");
}
}
}
I would appreciate all the help I can get, as I am horrible at coding in Java.
Use $(document).ready()
This function would excute after document is loaded
(Jquery)
since you don't have access to the website you are trying to authenticate with the best you can do is to wait an arbitrary length of time (in this case 30000 milliseconds):
<body onload="setTimeout(authenticationAttempt,30000);">
<script>
function authenticationAttempt() {
// add your code to login here
alert('after 30 seconds i assume the page is loaded');
}
</script>
</body>
here is a jsfiddle example which allows 5 seconds for bing.com to load before running additional code.
http://jsfiddle.net/DaveAlger/CFLh2/
if the website you are trying to authenticate with is public you should post a link to it because i still think what you are attempting will not be allowed unless you have access to change the code on the school website.

How to both start a file download and close a (jQuery) dialog in Wicket?

In a Wicket app, I have a modal dialog that contains a simple form and a button. User enters values (report parameters), and then clicks the button which starts the download of a report file (typically a PDF). (All form values are required, and Wicket's validation mechanism is used to make sure user entered them before the download can start.)
Maybe this is better explained with a picture:
I'm using here a jQuery UI Dialog (instead of Wicket's ModalWindow which felt a lot clumsier and uglier from user's perspective).
Everything is pretty much working, except closing the dialog when/after clicking the download button.
Current version (irrelevant bits omitted):
public class ReportDownloadLink extends Link {
public ReportDownloadLink(String id, ReportDto report) {
super(id);
this.report = report;
}
#Override
public void onClick() {
IResourceStream resourceStream = new AbstractResourceStreamWriter() {
#Override
public void write(OutputStream output) {
try {
reportService.generateReport(output, report);
} catch (ReportGenerationException e) {
// ...
}
}
#Override
public String getContentType() {
// ...
}
};
ResourceStreamRequestTarget target =
new ResourceStreamRequestTarget(resourceStream, report.getFileName());
getRequestCycle().setRequestTarget(target);
}
The dialog is a Wicket Panel (which makes use of ReportDownloadLink above), which we put in a certain div, and then when a report is selected in a list, the dialog is opened from an AjaxLink's onClick() quite simply like this:
target.appendJavascript(String.format("showReportExportDialog('%s')", ... ));
Which calls this JS function:
function showReportExportDialog(dialogTitle) {
$("#reportExportPanelContainer").dialog(
{modal:true, draggable:true, width: 320, height: 330, title: dialogTitle}
);
}
Some options:
Make ReportDownloadLink extend something else than Link, perhaps, and/or find an appropriate method to override which would allow me to execute the tiny bit of JavaScript needed to close the jQuery Dialog.
Investigate jQuery + Wicket libraries (such as jqwicket or wiquery) that supposedly make these two work better together.
Latest thing I tried was overriding method getOnClickScript() in ReportDownloadLink which seemed promising (according to the Javadocs, it returns "Any onClick JavaScript that should be used"):
#Override
protected CharSequence getOnClickScript(CharSequence url) {
return "closeDownloadDialog()";
}
Thing is, this causes onClick() not to be called at all, i.e., the download doesn't start.
Could I perhaps override some more "ajaxy" class from Wicket (than Link) to combine these things: first init the download, then call the JS for closing the dialog?
Any recommendations or experiences from similar cases? Note that I want to keep using the jQuery dialog here, even though it makes things like these more complicated. Using a DownloadLink (see related question) is fine too in case that makes things easier.
NB: if you recommend JQWicket or wiQuery, please provide an example of how to do this.
Maybe you can try to bind the close modal code to the button "click" event using only JQuery, in your modal panel page, add something similar to ${"#mySubmit").click(myCloseModalFunction). It should keep Wicket default's behavior and add modal closing in the mix.
The other way is to override the getOnClickScript(...) method but the javascript has to return true in order for the browser to call the continue link evaluation and load the corresponding href. If you return false, the evaluation stops. I would suggest something like
#Override
protected CharSequence getOnClickScript(CharSequence url) {
return "closeDownloadDialog();return true;";
}
Hope it helps...
See https://cwiki.apache.org/WICKET/ajax-update-and-file-download-in-one-blow.html for inspiration.

Categories