Using Controlled Embedded Browser in SWT - java

Does anyone know how to use the "Controlled Embedded Browser" in SWT, which allows page manipulation? I can only find info on how to use the normal SWT browser, but I need to be able to interact with the loaded page. Thank you. Like this -
http://publib.boulder.ibm.com/infocenter/btt/v7r0/index.jsp?topic=%2Fcom.ibm.btt.application_presentation.doc_7.0%2Fdoc%2Freference%2Frichclient%2Fcontrolembededbrowser.html - but there is no instruction on how to initiate such a class.

Here is an example from Eclipse SWT snippets website
Also this post might give you some insight on this.
Using Java Objects in JavaScript in Eclipse SWT Browser Control
To expose Java Object from Eclipse to JavaScript, you need to create a class that extends BrowserFunction. The constructor of this class takes two arguments; the first one is Browser instance and second one is name of the the function that will be available in JavaScript code running the SWT browser control... ...
Code snippet
BrowserFunction:
import java.io.File;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;
public class ListFilesFunction extends BrowserFunction {
Browser browser = null;
String functionName = null;
public ListFilesFunction(Browser browser, String name) {
super(browser, name);
this.browser = browser;
this.functionName = name;
}
public Object function (Object[] args)
{
if (args.length == 0)
browser.execute("alert('Function " +
functionName + " requires one argument - parent folder path');");
File file = new File(args[0].toString());
if (!file.exists())
browser.execute("alert('Folder " + args[0] +
" does not exist');");
if (!file.isDirectory())
browser.execute("alert('Path " + args[0] + " must be a folder');");
return file.list();
}
}
associate this function with the browser control
public class View extends ViewPart
{
Browser browserCtl = null;
...
public void createPartControl(Composite parent) {
...
browserCtl = new Browser(parent, SWT.None);
new ListFilesFunction(browserCtl, "getFiles");
...
}
...
}
invoke this function from JavaScript:
<html>
<head>
<script type='text/javascript'>
files = getFiles("c:/");
for (i = 0; i < files.length; i++)
{
document.writeln(files[i] + "<br>");
}
</script>
</head>
<body>
</body>
</html>

Related

Command Line Output of .jar is Different than its Output When Run by C# Code

I have a .jar file named "DynamicContentLoader.jar" that executes a Java process that connects to a web page, using HtmlUnit, and prints its Html document via System.out.println();. This Process takes one argument from the command line: the URI of the webpage needed to be retrieved.
Code of the Java process thats exported to the .jar file:
import java.io.IOException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class DynamicContentLoader {
public static void main(String[] args) {
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
String s = DynamicContentLoader.loadHtml("https://query.nytimes.com/search/sitesearch/?action=click&contentCollection&region=TopBar&WT.nav=searchWidget&module=SearchSubmit&pgtype=Homepage#/Donald%20Trump");
System.out.println(s);
}
public static String loadHtml(String url) {
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setCssEnabled(false); //if you don't need css
webClient.getOptions().setThrowExceptionOnScriptError(false); // stop process breaking exception throws
HtmlPage page;
try {
page = webClient.getPage(url);
webClient.waitForBackgroundJavaScript(20 * 1000); /* will wait JavaScript to execute up to 5s */
String pageAsXml = page.asXml();
webClient.close();
return pageAsXml;
} catch (FailingHttpStatusCodeException | IOException e) {
return null;
}
}
}
Next, I execute this .jar within a Mono project with a class that uses a Process Object to execute the .jar, read its StandardOutput stream into a StringBuilder, then create and return an HtmlAgilityPack.HtmlDocument object from StringBuilder.ToString();:
using System;
using System.Diagnostics;
using System.Text;
using HtmlAgilityPack;
namespace Search {
public static class DynamicContentLoader {
// path of .jar file in ProjectDirectory/Resources/.jar
readonly static string jarPath =
AppDomain.CurrentDomain.BaseDirectory +
"Resources/DynamicContentLoader.jar";
public static HtmlDocument LoadDynamicWebPage(string url) {
var startInfo = new ProcessStartInfo("java", #" -jar "
+ jarPath + " \'" + url + "\'");
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
var javaProcess = new Process();
javaProcess.StartInfo = startInfo;
javaProcess.Start();
var output = new StringBuilder();
while (!javaProcess.HasExited) {
output.Append(javaProcess.StandardOutput.ReadToEnd());
}
if (output.Length > 0) {
var doc = new HtmlDocument();
doc.LoadHtml(output.ToString());
// looking see if correct Html doc
Console.WriteLine(doc.DocumentNode.InnerHtml);
return doc;
}
return null;
}
}
}
My issue is that when I run the .jar from the command line,
"java -jar path/to/file/DynamicContentLoader.jar 'some uri'"
I get the correctly loaded Html doc/string. However, my C# code above returns a different, incomplete Html doc/string, or even crashes with exceptions like:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
atorg.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: com.gargoylesoftware.htmlunit.ScriptException: TypeError:
Cannot find function all in object function Promise() { [native code] }
Does anyone know what may cause the difference in behavior between these two different execution methods or what will fix this issue?

how to create custom reports in testng

I have the following Java code:
public class Login {
String Login_Status = null;
String Login_Message = null;
#Test
#Parameters({"USERNAME","PASSWORD"})
public void Execute(String UserName, String Password) throws IOException {
try {
Config.driver.findElement(By.linkText("Log in")).click();
Config.driver.findElement(By.id("user_login")).sendKeys(UserName);
Config.driver.findElement(By.id("user_pass")).sendKeys(Password);
Config.driver.findElement(By.id("wp-submit")).click();
// perform validation here
boolean expvalue = Config.driver.findElement(By.xpath("//a[#rel='home']")).isDisplayed();
if (expvalue) {
Login_Status = "PASS";
Login_Message="Login Successfull for user:" + UserName + ",password:" + Password + ",\n EXPECTED: rtMedia Demo Site LINK SHOULD BE PRESENT ON THE HOME PAGE OF rtMedia ACTUAL: rtMedia LINK is PRESENT ON THE HOME PAGE OF rtMedia. DETAILS:NA";
}
} catch(Exception generalException) {
Login_Status = "FAIL";
Login_Message = "Login UnSuccessfull for user:" + UserName + ",password:" + Password + ",\n EXPECTED: rtMedia Demo Site LINK SHOULD BE PRESENT ON THE HOME PAGE OF rtMedia ACTUAL: rtMedia LINK is NOT PRESENT ON THE HOME PAGE OF rtMedia. DETAILS:Exception Occurred:"+generalException.getLocalizedMessage();
// File scrFile = ((TakesScreenshot) Config.driver).getScreenshotAs(OutputType.FILE);
// FileUtils.copyFile(scrFile, new File("C:\\Users\\Public\\Pictures\\failure.png"));
} finally {
Assert.assertTrue(Login_Status.equalsIgnoreCase("PASS"), Login_Message);
}
}
}
I wrote the above Java code for login functionality and now I want to create reports for whatever the result will be (pass or fail) and it should be stored in folder? I have no idea about the generating the reports and also I found the reports are automatically generated by TestNG itself but when we run another test it gets overwritten, that will not help for me. Any help?
There are quite a few ways you can achieve this
If you're using XML report then you can implement IReporter and create a listener. You have to override a method called generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) and you can have your own logic to save the output in a different folder everytime you run the test case.
There is an attribute in testNG called fileFragmentationLevel if you set it to 3 I think your report will not be overwritten. It's in XML reporter class
You can create a listener that will extend TestListenerAdapter and override onStart(ITestContext testContext) method to back up your testoutput folder everytime. But I don't prefer this method.
I prefer #1.

How to get images from a folder in the server using Jersey WS?

I am learning the Jersey web services, now I understood how GET and POST work :
#GET
#Produces("text/html")
public String getHandler() {
return "<h1>Get some REST!<h1>";
}
#POST
#Consumes("application/x-www-form-urlencoded")
#Produces("text/plain")
public String postHandler(String content) {
return content;
}
in Jersey Documentation for featching images it said :
#GET
#Path("/images/{image}")
#Produces("image/*")
public Response getImage(#PathParam("image") String image) {
if (!isSafeToOpenFile(image)) {
throw new IllegalArgumentException("Cannot open the image file.");
}
File f = new File(image);
if (!f.exists()) {
throw new WebApplicationException(404);
}
String mt = new MimetypesFileTypeMap().getContentType(f);
return Response.ok(f, mt).build();
}
I would appreciated if you can show me an example using the above code to fetch images from a folder in the server and post them in a html.
Thanks lot.
Here is a full example of a live gallery, based on REST services.
REST services (Jersey)
This service gives the content (filenames) of the image server directory (here C:\Temp\hotfolder).
// array of supported extensions
static final String[] EXTENSIONS = new String[] { "jpg", "jpeg", "gif", "png", "bmp" };
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
#GET
#Path("folderImages")
#Produces("text/json")
public Response getFolderImages(#QueryParam("lastknown") String lastknown)
{
//Gets the contents of the folder (reverse order : more recent first)
//see http://stackoverflow.com/questions/11300847/load-and-display-all-the-images-from-a-folder
File dir = new File("C:\\Temp\\hotfolder");
File [] files = dir.listFiles(IMAGE_FILTER);
Arrays.sort( files, new Comparator<File>() {
public int compare(File f1, File f2) {
if (f1.lastModified() > f2.lastModified()) {
return -1;
} else if (f1.lastModified() < f2.lastModified()) {
return +1;
} else {
return 0;
}
}
});
//Fills a list (from the more recent one, until the last known file)
ArrayList<String> newfiles = new ArrayList<String>();
for (File f : files)
{
if (lastknown!=null && f.getName().equals(lastknown))
break;
newfiles.add(f.getName());
}
//Answers the list as a JSON array (using google-gson, but could be done manually here)
return Response.status(Status.OK).entity(new Gson().toJson(newfiles)).type("text/json").build();
}
Also this is the image service, needed for rendering each image individually.
#GET
#Path("/images/{image}")
#Produces("image/*")
public Response getImage(#PathParam("image") String image) {
File f = new File("C:\\Temp\\hotfolder\\" + image);
if (!f.exists()) {
throw new WebApplicationException(404);
}
String mt = new MimetypesFileTypeMap().getContentType(f);
return Response.ok(f, mt).build();
}
gallery.html
Html, with a little help of JQuery. This HTML polls every 5 seconds, asking for service if there is new files (more recent) than the last file known. Et voilĂ !
You can notice we are using the jquery .prepend method to insert images dynamically at the beginning of the gallery div.
<html>
<head>
<title>Folder demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1>Live gallery</h1>
<div id="gallery1" style="border:1px solid black;padding:10px;"></div>
<div id="info1"></div>
<script>
var counter = 0;
var lastknown = "";
function doPoll(){
$.get('rest/folderImages?lastknown='+lastknown, function(data) {
counter++;
$("#info1").html("<pre>Counter: " + counter + "<br>New files: " + data + "</pre>");
for (var i=data.length-1; i>=0; i--) {
$("#gallery1").prepend("<img src=\"rest/images/" + data[i] + "\" style=\"width:200px;height:200px\" />");
lastknown = data[i];
}
setTimeout(doPoll,5000);
});
}
$(document).ready( doPoll );
</script>
</body>
</html>
The Jersey example from documentation is clear enough to me. However, here is a simplified example without parameters (do simple to begin...)
#GET
#Path("/images/pet")
#Produces("image/*")
public Response getImage() {
File f = new File("C:\\\\Temp\\dog.jpg");
if (!f.exists()) {
throw new WebApplicationException(404);
}
String mt = new MimetypesFileTypeMap().getContentType(f);
return Response.ok(f, mt).build();
}
As my Jersey is configured as /rest/* path in the web.xml of the yourapp application, the image is accessible at the following address:
http://serverip:port/yourapp/rest/images/pet
You can try it directly this URL in the browser navigation bar (it is a REST image service, served as if it was a static image), or if you want it in a html page, you can use classic HTML:
<html>
<body>
<h1>Woof!</h1>
<img src="http://localhost:8080/myapp/rest/images/pet" />
</body>
</html>
Hope it helps.
EDIT
Okay that was too obvious. So you need to implement a method or service that gives the content of a directory with image file names in the given order you need (as a java List).
Using this List, you can build a html like this within a loop:
<html>
<body>
<h1>Several images</h1>
<img src="/yourapp/rest/images/last.jpg" /><br/>
<img src="/yourapp/rest/images/third.jpg" /><br/>
<img src="/yourapp/rest/images/second.jpg" /><br/>
<img src="/yourapp/rest/images/first.jpg" /><br/>
</body>
</html>
This is the result HTML you must output (in JSP or whatever you use). The REST service getImage() will be called automatically by the browser, once for each image.
Am I clear ?

create new word document from java

I want to open New MS Word Document to open on button click in java
can you suggest me the code , I am doing this by following code but i think its to open the existing document not to create the new document
class OpenWordFile {
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /C start Employee.doc");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Exception occured" + ex);
}
}
}
You can not do this using Java alone, at least if you need to generate DOC Files you need a 3rd tool library Aspose for example. Take a look at this thread, otherwise you can open existing files using the runtime.
only the comment with out any words
Runtime run = Runtime.getRuntime();
String lcOSName = System.getProperty("os.name").toLowerCase();
boolean MAC_OS_X = lcOSName.startsWith("mac os x");
if (MAC_OS_X) {
run.exec("open " + file);
} else {
//run.exec("cmd.exe /c start " + file); //win NT, win2000
run.exec("rundll32 url.dll, FileProtocolHandler " + path);
}
In the recent release (Java 6.0), Java provides Desktop class. The purpose of the class is to open the application in your system that is associated with the given file. So, if you invoke open() method with a Word document (.doc) then it automatically invokes MS Word as that is the application associated with .doc files.
I have developed a small Swing program (though you can develop it as a console application) to take document number from user and invoke document into MSWord. The assumption is; documents are stored with filename consisting of <document number>>.doc.
Given below is the Java program that you can compile and run it as-it-is. Make sure you change DIR variable to the folder where .doc files are stored.
Here is the code to open Word Doc in Java... its an extract from net....
import java.io.File;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class WordDocument extends JFrame {
private JButton btnOpen;
private JLabel jLabel1;
private JTextField txtDocNumber;
private static String DIR ="c:\\worddocuments\\"; // folder where word documents are present.
public WordDocument() {
super("Open Word Document");
initComponents();
}
private void initComponents() {
jLabel1 = new JLabel();
txtDocNumber = new JTextField();
btnOpen = new JButton();
Container c = getContentPane();
c.setLayout(new java.awt.FlowLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Enter Document Number : ");
c.add(jLabel1);
txtDocNumber.setColumns(5);
c.add(txtDocNumber);
btnOpen.setText("Open Document");
btnOpen.addActionListener(new ActionListener() { // anonymous inner class
public void actionPerformed(ActionEvent evt) {
Desktop desktop = Desktop.getDesktop();
try {
File f = new File( DIR + txtDocNumber.getText() + ".doc");
desktop.open(f); // opens application (MSWord) associated with .doc file
}
catch(Exception ex) {
// WordDocument.this is to refer to outer class's instance from inner class
JOptionPane.showMessageDialog(WordDocument.this,ex.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
}
}
});
c.add(btnOpen);
} // initCompnents()
public static void main(String args[]) {
WordDocument wd = new WordDocument();
wd.setSize(300,100);
wd.setVisible(true);
}
}
Maybe using java.awt.Desktop can help?
File f = new File("<some temp path>\\file.docx");
f.createNewFile();
Desktop.getDesktop().open(f);
Creates a new empty document and opens it with the systsem specifik program for the extension. The strength of this solution is that it works for all OS... As long as the OS has a program to view the file that is.
Although I suspect that you are looking for semthing with abit more control over the creation of the file...

Vaadin is not allowing import of external scripts

im using Vaadin and trying to import jQuery and my own script. I have extended ApplicationServlet class and redefined this method
#Override
protected void writeAjaxPageHtmlHeader(BufferedWriter page, String title,
String themeUri, HttpServletRequest request) {
try {
super.writeAjaxPageHtmlHeader(page, title, themeUri, request);
page.write("\n<script type=\"text/javascript\" src=\"/VAADIN/themes/MyTheme/js/jquery-1.7.1.js\"></script>");
page.write("\n<script type=\"text/javascript\" src=\"/VAADIN/themes/MyTheme/js/script.js\"></script>");
System.out.println("Added jQuery and other scripts to page header.");
} catch (IOException e) {
e.printStackTrace();
}
}
and changed in web.xml servlet class to my own, but when i get it running my scripts don't work, so i open JavaScript Console and get this two messages:
Not allowed to load local resource: file:///VAADIN/themes/MyTheme/js/jquery-1.7.1.js
Not allowed to load local resource: file:///VAADIN/themes/MyTheme/js/script.js
Why is this happening, what can i do?
The themeUri parameter provides the URI of the theme in use, so try to use that in your src attributes:
page.write("\n<script type=\"text/javascript\" src=\"" + themeUri + "/js/jquery-1.7.1.js\"></script>");

Categories

Resources