JEditorPane.setPage() method works only once during runtime - java

I am currently working on a project that allows the user to input a url, such as http://www.google.com and the user is able to edit the html code of the page. So far I save the edited file as an html document when the JTextArea has a key released. Here is the source code that I use:
String s = jTextArea1.getText();
PrintStream ps = new PrintStream(new FileOutputStream(new File("HTML.htm")));
ps.print(s);
ps.close();
this.resetPage();
The last line of code calls this bit of source code (this is actually where I attempt to update the page with the user's input:
File f = new File("HTML.htm");
URL u =f.toURI().toURL();
jEditorPane1.setPage(u);
All the proper exceptions are caught. It updates the text on the page once. All the images are blank (which I expected because the paths were all local) but that should have no real effect on the other html in the document.
When I open the HTML.htm file in notepad++ the file IS being updated but the jEditorPane is not getting updated with the new html script.
Also, the JEditorPane has its Editable vale set to false.
When I open the file in Chrome, it gets the fully updated script.

From the JEditorPane setPage(URL) API description:
To force a document reload it is necessary to clear the stream description property of the document. The following code shows how this can be done:
Document doc = jEditorPane.getDocument();
doc.putProperty(Document.StreamDescriptionProperty, null);

try this
File f = new File("HTML.htm");
URL u =f.toURI().toURL();
jEditorPane1.setPage(u);
jEditorPane1.updateUI();

Related

PDFBox: Loading an Image Into PDF From a JAR Resource

Good afternoon. I have a JAR file to which I have attached some images as resources in a folder called logos. I am being told to do this due to security restrictions (we don't want the image files to be exposed in the same folder as the JAR). I first tried to load these images in as if they were a File object, but that obviously doesn't work. I am now trying to use an InputStream to load the image into the required PDImageXObject, but the images are not rendering into the PDF. Here is a snippet of the code which I am using:
String logoName = "aLogoName.png";
PDDocument document = new PDDocument();
// the variable "generator" is an object used for operations in generating the PDF
InputStream logoFileAsStream = generator.getClass().getResourceAsStream("/" + logoName);
PDStream logoStream = new PDStream(document, logoFileAsStream);
PDImageXObject logoImage = new PDImageXObject(logoStream, new PDResources());
PDPage page = new PDPage(new PDRectangle(PDRectangle.A4.getHeight(), PDRectangle.A4.getWidth()));
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(logoImage, 500, 100);
Note that I have verified that the resource is getting loaded in correctly, as using logoFileAsStream.available() returns a different value for various logos. After running this code, the image does not actually get drawn on the PDF, and upon opening it, the error message "An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem." appears. Could someone please help me figure what's wrong with that code snippet/a different solution to load my images in as a resource from the JAR? Thanks so much. Let me know if more details are needed/clarification.
This PDImageXObject constructor is for internal PDFBox use only. You can use
PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(logoFileAsStream), logoName /* optional, can be null */)
for maximum flexibility, or if you know it is always a PNG file
LosslessFactory.createFromImage(document, ImageIO.read(logoFileAsStream))
don't forget to close logoFileAsStream and contentStream.

using java not javascript, open URL in same tab of default browser

I have written a java script whose work is to open URL's mentioned in the text file and it should repeat this process continuously but the problem is as soon as it reads the new URL mention in next line of text file it opens that URL in new tab but I want to open all the URL's in same tab of chrome browser.
Code what I have written:
while(true){
BufferedReader buf = new BufferedReader(new FileReader("C:\\link.txt"));
String currentLine = null;
while((currentLine = buf.readLine())!=null){
System.out.print(currentLine+"\n");
Desktop.getDesktop().browse(new URL(currentLine).toURI());
Thread.sleep(10000);
}
}
}
Is there any other option then Desktop.getDesktop() that will also work
My text file has two links like this:
https://www.google.co.in/?gfe_rd=cr&ei=y8a_WPTUFLOl8weF8bK4DQ
https://in.yahoo.com/
How to open them in same tab?
Desktop.getDesktop().browse()
Does NOT support this, as seen in Can Java's Desktop.browse provide an HTML Target in order to reuse a browser window?
Though, alternatives for this are the use of Process as seen in
Process oProc = Runtime.getRuntime().exec( currentLine );
And then make use of this process to send more commands to.
Or make use of a library / API such as Browserlaunch
The issue with Chrome, however is that Chrome likes to open new tabs in a new screen. If you hit ctrl + N (new tab on a lot of browsers) on Chrome, it'll open up a new screen instead

how to load the local files relative to the current java file in jwebbrowser

how would I load local files relative to the current java file in JWebbrowser?
I know that I could load my page with navigate("path"); the problem is how to set relative path!
for example my java code is in :
D:\Eclipse_Project\MyProject\src\javaCode\browser.java
and the html file is in :
D:\Eclipse_Project\MyProject\src\pages\html.html
but I don't want to use as follow:
webBrowser.navigate("file:///D:/Eclipse_Project/MyProject/src/pages/html.html");
Edit:
my html file also contains CSS an javaScript.
If it's still actual, I had the same problem, this is the solution:
you need to use webserver like that:
webBrowser = new JWebBrowser();
webBrowser.navigate(WebServer.getDefaultWebServer().getClassPathResourceURL(getClass().getName(), "your_html_content.html"));
Please try the following code:
1. Read html content with scanner.
2. Set html string to webBrowser.
String webContent = new Scanner(new File("src\\pages\\html.html")).useDelimiter("\\Z").next();
webBrowser.setHTMLContent(webContent);

How to save .pdf file that pops up in a browser window with no url?

I am working with .pdf files that are available on my companies' website only. I am not aware of any way to download them and store in one folder.
The link that I click to get the .pdf file has the following source code:
<a href="javascript:propertiesView('documentName')">
As I click on the link, a .pdf file pops up in a new browser window with no url and no source code. I presume that there is no way to manipulate that .pdf directly, then how can I save it then in order to manipulate the .pdfs from a folder?
Thank You
You may have luck by simply telling your browser to always save PDF files to disk (credits to Dirk):
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
If that doesn't work, you are probably able to iterate through all open windows/tabs by using the switchTo() methods. Try something like this to get some insight about your opened windows (credits to Prashant Shukla):
public void getWindows() {
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
driver.switchTo().window(window);
System.out.println(driver.getTitle());
}
}
A non-selenium solution to download the file would be to use the apache-commons library (creadits to Shengyuan Lu):
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
But this would require that you know the URL of the window, which you probably are able to fetch with the second approach i mentioned (driver.switchTo()) and driver.getCurrentUrl().
I presume that there is no way to manipulate that .pdf directly
That's correct. With Selenium, you cannot.
how can I save it then in order to manipulate the .pdfs from a folder?
I've actually implemented this exact thing in our regression system where I work.
My first step, was to construct a Url based on what the propertiesView(). method did.
in your case, propertiesView() does some sort of window.open is my guess. So your goal is, to extract that Url that it opens, and use concatenation to construct the url.
Once you've found your Url, the rest is a cakewalk. Just download the url to a folder named /pdfs. See this question for how to do that.
It may even require calling that method to figure it out.. Due to my ignorance of your System Under Test, it's difficult for me to give you a code answer, unless you posted it.
A hint that i'll tell you, is if you are using Selenium 1, use
String url =selenium.getEval("var url = something; url;");
to fetch the url and get it into a java object.
(If using selenium 2, use the JavaScriptExecutor#executeScript)
If you want to save a PDF to your hard drive in IE with selenium, you need to use pywinauto with selenium. I just used this code for PDF files that open up in the browser.
//selenium imports
from pywinauto import application //pywinauto import
//write selenium code to open up pdf in the browser
driver = webdriver.Ie("IEDriverServer.exe", capabilities = caps)
//this could be a get or driver.execute_script() to click a link
driver.get("link to pdf")
//save pdf
app = application.Application()
//get the ie window by the title of the application (assuming only one window is open here)
ie = app.window_(title_re = ".*Internet Explorer.*")
//this line focuses on the pdf that is open in the browser
static = ie.Static
//focus on the pdf so we can access the internal controls
static.SetFocus()
//control + h shows the pdf bar, but you don't really need this step
//for it to work. i just used it as a debug
static.TypeKeys("^H")
//open save file dialog
static.TypeKeys("+^S")
//tricky here because the save file dialog opens up as another app instance
//which is how pywinauto sees it
app2 = application.Application()
//bind to the window by title - name of the dialog
save = app2.window_(title_re = ".*Save As.*")
//this is the name of the property where you type in the filename
//way to be undescriptive microsoft
file_name = save[u'FloatNotifySink']
//type in the file name
save.TypeKeys("hello")
//pause for a second - you don't have to do this
time.sleep(4)
//find and bind the save button
button = save[u'&SaveButton']
//click the save button
button.Click()

Read / write program in Java using JFileChooser

How would I link the file choosen from a JFileChooser to a file and how would I convert it to string being able to display and edit it in a TextArea?
I have the GUI set up using swing, but the link between actionListener and the JFileChooser is not complete.
Any help would be much appreciated.
Code: http://pastebin.com/p3fb17Wi
EDIT: I found this program, that does pretty much what i wanted to, but it does not allow me to save the actual file : http://www.java-forums.org/new-java/8856-how-get-content-text-file-write-jtextarea.html
To be able to save the changes you have made, you will have to use a Save Dialog. In the example you have quoted, a File Open Dialog is used. They work in a similar way, all that you need to do is then get the file to which the user would like to store the changes made, open a stream to it and write the data back. This tutorial shows you how to use the various File Choosers.
All text components support a read(...) and write(...) method. So all you have to do is get the name of the File and create your FileReader or FileWriter and then invoke the method.
All the file chooser is used for is the get the File name to be used by the reader or writer. So the basic code would be:
File saveFile = chooser.getSelectedFile();
FileWriterr writerr = new FileWriter( saveFile );
textArea.write(writer)
Of course you will probably want to use a Buffered reader/writer.

Categories

Resources