Is it OK to include Java Swing with JSP? - java

I tried using Swing code in a JSP page. To my surprise it does work well and fine.
But I cannot judge if it is OK to use Swing with JSP?
Basically I want to display some pop up reports from Database. I was thinking to display a JFrame pop up/ applet to do the trick.
But do a web browser require any additional plugin for this?
Or is it fine to do such a thingy? Any guidance will be helpful.

Always remember that every java fragment you insert into your JSP is executed server-side, so it can be deceitful (it may seem to work in your development local machine, but it is only because the server and the client side are running on the same box).
The proper way to do this would be to write an Applet and include it into your page - this way, the browser will download it to client side and run it there. You should subclass JApplet (http://docs.oracle.com/javase/8/docs/api/javax/swing/JApplet.html) and then you will be able to use Swing components at will

The library works but your controls will never be shown at the client side (browser) but at the server (if it is that you have a working window service: Ms Windows, X11, Xorg,...).
I don't think that is a good practice and I would only use Swing library classes not to show GUI components but to use some classes to store special objects such as ImageIcon to store icons. But never to try to paint them.
I have a project where I use JLaTeXMath to generate a PNG within a JSP representing some math equations, in this context, I use javax.swing.JLabel to generate the image:
TeXFormula formula = new TeXFormula(texCode);
TeXIcon texImg = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 25);
BufferedImage img = new BufferedImage(texImg.getIconWidth(), texImg.getIconHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
texImg.paintIcon(new JLabel(),img.getGraphics(), 0, 0);
try {
OutputStream os = res.getOutputStream();
res.setContentType("image/png");
ImageIO.write(img, "png", os);
os.close();
res.flushBuffer();
} catch (Exception ex) {
log.warn("LaTeX renderer: " + ex.toString() + "\t" + "Msg: " + ex.getMessage());
return;
}

the JSP would run on the server,and probably display the GUI there,
but why would you want that? In the meantime, the person at the client
who submitted the request would be sitting there waiting for somebody
at the server end to close the Swing window so the JSP could get on
with its work.
So i would say that it is not feasible.

Related

Java Code to save Web page as image

I have an application developed using struts2. One of my web page has a div in which it displays a world map created using Google map API. On click of a button I want to save this map as an image on the server location. I tried this using the ROBOT class but this is not working. My application supports IE8. Below is the code I wrote:
Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rect = new Rectangle(screenDim);
Robot rob = new Robot();
BufferedImage img = rob.createScreenCapture(rect);
String FileName="D:\\SP_Maps\\Map.png";
ImageIO.write(img, "png", new File(FileName));
Basically I tried to take a screen shot of the page on click of a button and save it as an image. This works fine on my local host but, when I deploy this on my server and try to get the screen shot I just get a black page saved as png image.
While you are developing a web application you may use javascript if you are interested..
To get a screen shot and save it with any format you may use PhantomJS
PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast
and native support for various web standards: DOM handling, CSS selector,
JSON, Canvas, and SVG.
Check those examples written with PhantomJS:
https://github.com/ariya/phantomjs/wiki/Examples
Also check this tutorial Taking website screenshots using PhantomJS
The tutorial is about taking a web shot and saving it as JPEG, PNG, PDF ... etc
Hope this helps you...
Can you explain your use case clearly ? If I understand correctly you have a web application which has a functionality to take a screen capture upon user action? Ideally, Java Robot utility should use to do automated testing of java applications. As per the doc
The primary purpose of Robot is to facilitate automated testing of
Java platform implementations.
Maybe you can try using phantomjs.
example
var page = require('webpage').create();
page.open('http://google.com', function () {
page.render('google.png');
phantom.exit();
});
https://github.com/ariya/phantomjs/wiki/Quick-Start
To perform user actions like button clicks, you can use casper.js
http://casperjs.org/quickstart.html

Render and Export FusionCharts on the Server

I am trying to render and export FusionCharts completely on the server. I am aware of solutions such as FCimg and FusionCharts .NET Solution. I have also implemented a Java solution that uses the Process class to run wkhtmltoimage.
However, I am trying to find a pure Java solution of doing this. I have an html file that includes FusionCharts JS Libraries and code to generate the fusion chart. I found JxBrowser that properly renders the chart but it requires X-Server for it to work on Linux. I also have tried Cobra/Lobo Browser but it does not fully support JavaScript. Are there any other ways to render and export fusion charts on the server or atleast render an html file that includes JavaScript completely in Java (and that does not require xserver)?
Thanks in advance for all the help!
Update: Solution that does not require xserver: WebRenderer. The Swing Edition is the only edition that supports HTML5 as of July 9th, 2012. You can use the swing edition to capture the image without a GUI.
I found a way that uses Eclipse's SWT Browser. However this cannot be run in an headless mode. You will have to use xserver to implement this. See this question.
Since this requires xserver and cannot be run in an headless mode, I would suggest using JxBrowser. It is a lot simpler and all you need is to generate an html file with all the fusion charts scripts. See #1, #2, #3
You have to create a template.html file that contains the header
(<html><head>), jquery.min.js, FusionCharts.js,
FusionCharts.HC.js, FusionCharts.HC.Charts.js. Make sure each of
these scripts are in their own script tags (<script type="text/javascript"> [js code] </script>)
Now add another JavaScript function with its own script tags containing the steps to render the chart. For example:
function load() { FusionCharts.setCurrentRenderer('javascript'); var chart = new FusionCharts("swf", 'chart0', "width", "height", "0", "1"); chart.setXMLData("XML DATA HERE"); chart.render("divNAMEHere"); }
Now you need to call the load() function onload, create a div to render the chart in, and end the html file. For example:
`
test
`
Create a new class that imports the eclipse swt browser libraries. Instantiate Display, Shell, and Browser (use this as a guideline to help understand what is happening: http://www.roseindia.net/tutorials/swt/swt-browser.shtml).
Set the text of the browser (browser.setText("htmlcode")) to the html code from template.html. The best way to do this would be to read the file using BufferedReader.
Lastly, the image takes some time to render. Now there is probably a better way to do this but if you want to just get it working, I set up a count and it captures the image after a certain number. This is what you need to add to the end:
int i = 0;
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
i++;
// System.out.println(i);
if(i==100)
{
GC source = new GC (shell);
Image image = new Image(display, browser.getClientArea());
source.copyArea(image, 0, 0);
ImageLoader io = new ImageLoader ();
io.data = new ImageData[] { image.getImageData() };
File f = new File (currentDir+"/workpng.png");
io.save (f.getAbsolutePath(), SWT.IMAGE_PNG);
}
}
}

Open and maximise a browser window in OATS Java (not javascript)

I am a tester and just installed oracle application test suite to use testing eBus apps
Anyway the only language it supports for coding test scripts (I don't want to use the recorder for a number of reasons). The problem I am having is that everything I search or google is javascript not java (even googling with -script I still ended up looking at javascript. This just gets rejected by the oats editor
The only other examples I have seen, appear to be defining a variable then setting the value of that variable as the window they want to maximize. Aside from the fact that my java skills are not up to doing that - I do not need to do this for a newly opened browser window do I? (The assumption is that this will be the only browser window open (ie test is executed with browser closed)
Is there any easy way to do this?
Below is the very simple initiate of the browser which is generated from a recording plus part of the first step which loads the url the test starts at: (I realize the first step is not complete below -I didn't paste it all, just enough to hopefully allow someone to show me what I need to edit to force the browser to load maximized, or maximize it immediately after loading?
public void initialize() throws Exception {
browser.launch();
}
/**
* Add code to be executed each iteration for this virtual user.
*/
public void run() throws Exception {
beginStep("[1] Login (/RF.jsp)", 0);
{
web
.window(2,
"/web:window[#index='0' or #title='about:blank']")
.navigate(
"http://somepageiwantolaunch");
web.window(4, "/web:window[#index='0' or #title='Login']")
.waitForPage(null);
I am not sure whether you already got the answer for this.. if not this code should help you
browser.launch();
DOMBrowser currentExecutionBrowser = web.window("/web:window[#index='0' or #index='1']");
currentExecutionBrowser.maximize();
Let me know if this helps!
There is a function in the Oracle Functional Tester API Reference which has a build in function called object.WindowState It says you can get or set using this function and it has values
0 - Normal, 1- minimized and 2-maximised.
Only issue is that these examples look more like VB than Javascript but presumably there is a similar function built into to the Oracle libraries for Java.
I did a quick search for Oracle Openscript API and came up with this link which asks for the same thing. They suggest using Help->Search from within the openscript application and then searching for "openscript API" which should provide a list of the functions available.
Hope that helps.
To Maximize browser in OATS, follow the below code
Open script ha in built methods which helps coding easy
browser.launch();
web.window(12, "/web:window[#index='0' or #title='about:blank']").navigate("http://www.google.com/");
web.window(12, "/web:window[#index='0' or #title='about:blank']").maximize();
for more OATS Tips/Tricks follow here
http://www.testinghive.com/category/oracle-application-testing-suite-tips
If it is the only browser window open, you can use the below code. It must be used with caution since the code maximizes any window that is open above the browser window.
try {
Robot a = new Robot();
a.keyPress(KeyEvent.VK_ALT);
a.keyPress(KeyEvent.VK_SPACE);
a.keyRelease(KeyEvent.VK_SPACE);
a.keyRelease(KeyEvent.VK_ALT);
a.keyPress(KeyEvent.VK_X);
a.keyRelease(KeyEvent.VK_X);
} catch (AWTException e) {
}

JEditorPane can't take Google search queries, why?

I am creating a very basic web browser using JEditorPane just to teach myself Swing and GUIs in Java but am having trouble implementing a Firefox-like Google Search bar.
I'm not if it's due to a limitation of JEditorPane or my lack of understanding but if I try and take the string typed into the "Google Search" bar and use the setPage() method of JEditorPane, it doesn't work.
Here is my code for the ActionListener of the "Google Search" button:
public void actionPerformed(ActionEvent arg0)
{
try
{
content.setPage("http://www.google.com/search?q=" + searchBar.getText());
}
catch (IOException e)
{
JOptionPane.showMessageDialog(frame, "Error searching for: " + searchBar.getText());
}
}
Even when I try and just do content.setPage("http://www.google.com/search?p=test"); it doesnt work, so is it something to do with setPage()'s way of taking the URL string? As in it doesn't like the "?" or "=" characters or is there another way of doing it all together?
Thanks for your time,
InfinitiFizz
Add something to print the exception you are catching and you'll see that you're receiving a 403 Forbidden from Google.
There are a lot of Java bots out there and sites have started blocking requests with "java" in the User-agent field. Google will let you get their home page, but won't let you search unless you override the User-agent field.
Start your jvm with -Dhttp.agent=myappname/1.0 where myappname is the name of your application.
JEditorPane is a poor choice to implement even the simplest browser. It works to display simple HTML pages but it stops there.
Try The Flying Saucer Project, it works pretty well(it's not a full browser, but close enough).They have an example which simulates actually a web browser.
Like adrian.tarau said, JEditorPane is very poor at displaying modern web pages.
It doesn't even support HTML 4 or Javascript. I believe Google uses Javascript to make the Search button work.
Another suggestion would be to use the Lobo Browser/Cobra engine.
If you need a full browser in Java check out Lobo:
http://lobobrowser.org/java-browser.jsp

Applet issue with jre 1.6

I have an applet, and it consist of an CLOSE button which closes the applet and redirects user to the home page. Home page consists 3 frames (Top, Left and Right). Once user clicks on the CLOSE button, the home page is appearing in the right frames, due to this now user has inconsistent view (multiple frames) of the page.
Code written in CLOSE button of the applet.
protected void cancelActionPerformed()
{
try
{
String type = "3";
AppletContext context = getAppletContext();
context.showDocument(new URL("javascript:goBack(\"" + type + "\")"));
destroy();
}
catch(MalformedURLException ex)
{
// System.out.println(ex.getMessage());
}
}
This is working perfectly in the JRE version 1.6 UPDATES 07 installed in the browser but higher updates of JRE creating this problem.
Kindly suggest if any thing wrong or any suggestion to overcome this situation.
Thank you
Regards
By default the JRE does not support java.net.URLs with the javascript protocol. So unless a handler has been installed (even though you never use it - horrible API) you will get a java.net.MalformedURLException.
Probably the easiest solution is to use the LiveConnect API to call the JavaScript.

Categories