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
Related
i want to open multiple websites in IE using java program.
here is the code
the websites are fetched from txt file
while((line = br.readLine()) != null)
{
StringTokenizer webLink = new StringTokenizer(line,";");
while(webLink.hasMoreTokens())
{
String webPathString = webLink.nextToken();
System.out.println(webPathString);
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(webPathString));
}
}
problem is only last site is getting opened in a browser insted of all.
desktop.browse will open all links in a current window only
For more details check the below discussion
Can Java's Desktop library launch a URL in a new Browser Tab or Window?
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();
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()
My problem is saving documents in Netbeans. I created a program using Java in Netbeans. At first you register (at the click on register button a new user Map is created with the name of the user), then you login with your user name and your password. When you are logged in, the program displays a new window where you can create documents. You can write text in TextArea. Then when you're finished with writing your text you click on Save button and the text you've written saves in a document named after the text you've given in a jTextField. So for every different login the absolute path changes.
This is my code in submit button:
//ccc is the name of user map
String ccc = LogIn.uporabnik1;
try{
FileWriter writer = new FileWriter("C:\\Users\\ALEKS\\Documents\\NetBeansProjects\\EasyEdit\\"+ccc+"\\"+FileName+".txt");
BufferedWriter bw = new BufferedWriter (writer);
jTextArea1.write(bw);
bw.close();
jTextArea1.setText("");
jTextArea1.requestFocus();
writer.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
It looks like there is a typo with an extra space in your path.
Note that as an alternative, if you use Java 7+, you can also use the Paths utility class to generate paths without having to deal with os specific separators (\\ or /):
Path path = Paths.get("C:/Users/ALEKS/Documents/NetBeansProjects/EasyEdit/"
+ ccc + "/" + FileName + ".txt");
And to write a string to a file:
String text = jTextArea1.getText();
Files.write(path, text.getBytes("UTF-8"));
That makes your code shorter and you don't have to manually create and close the streams.
Finally, for long-ish operations, you should not use the GUI thread but use a background thread instead or you application will become unresponsive as the save operation is in progress.
I developp a Java application using Windows Desktop Search from which I can retrieve some information about files on my computer such as urls (System.ItemUrl). An example of such url is
file://c:/users/ausername/documents/aninterestingfile.txt
for "normal" files. This field give also urls of mail items indexed from Outlook or Thunderbird. Thunderbird's items (only available using vista and seven) are also files (.wdseml). But outlook's items urls start with "mapi://" like :
mapi://{S-1-5-21-1626573300-1364474481-487586288-1001}/toto#mycompany.com($b423dcd5)/0/Inbox/가가가가곕갘객겒갨겑곓걌게겻겨곹곒갓곅갩갤가갠가
The problem I have is opening the real item from Java in Outlook using this url. If I copy/paste it in the run dialog of Windows, it works ; it also works if I use "start" followed by the copied/pasted url in command line.
The url seems to be encoded in UTF-16. I want to be able to write such code :
String url = "mapi://{S-1-5-21-1626573300-1364474481-487586288-1001}/toto#mycompany.com($b423dcd5)/0/Inbox/가가가가곕갘객겒갨겑곓걌게겻겨곹곒갓곅갩갤가갠가";
Runtime.getRuntime().exec("cmd.exe /C start " + url);
I doesn't work and I've tried other solutions like :
String start = "start";
String url = "mapi://{S-1-5-21-1626573300-1364474481-487586288-1001}/toto#mycompany.com($b423dcd5)/0/Inbox/가가가가곕갘객겒갨겑곓걌게겻겨곹곒갓곅갩갤가갠가";
FileOutputStream fos = new FileOutputStream(new File("test.bat");
fos.write(start.getBytes("UTF16");
fos.write(url.getBytes("UTF16"));
fos.close();
Runtime.getRuntime().exec("cmd.exe /C test.bat");
without any success. Using the solution above, the file "test.bat" contains the correct url and the "start" command, but the run of "test.bat" results in the well known error message :
'■' is not recognized as an internal or external command, operable program or batch file.
Has anybody an idea to be able to open "mapi://" items from Java ?
Well, my question was a little bit tricky. But I finally found an answer and will share it here.
What I suspected was true : Windows uses UTF-16 (little endian) urls. It makes no differences working in UTF-8 when we only use paths to files such as images, text, etc. But to be able to access Outlook items, we must use UTF-16LE. If I were coding in C#, there wouldn't have been any problem. But in Java, you have to be more inventive.
From Windows Desktop Search, I retrieve this:
mapi://{S-1-5-21-1626573300-1364474481-487586288-1001}/toto#mycompany.com($b423dcd5)/0/Inbox/가가가가곕갘객겒갨겑곓걌게겻겨곹곒갓곅갩갤가갠가
And what I did is creating a temporary VB script and run it like this:
/**
* Opens a set of items using the given set of paths.
*/
public static void openItems(List<String> urls) {
try {
// Create VB script
String script =
"Sub Run(ByVal sFile)\n" +
"Dim shell\n" +
"Set shell = CreateObject(\"WScript.Shell\")\n" +
"shell.Run Chr(34) & sFile & Chr(34), 1, False\n" +
"Set shell = Nothing\n" +
"End Sub\n";
File file = new File("openitems.vbs");
// Format all urls before writing and add a line for each given url
String urlsString = "";
for (String url : urls) {
if (url.startsWith("file:")) {
url = url.substring(5);
}
urlsString += "Run \"" + url + "\"\n";
}
// Write UTF-16LE bytes in openitems.vbs
FileOutputStream fos = new FileOutputStream(file);
fos.write(script.getBytes("UTF-16LE"));
fos.write(urlsString.getBytes("UTF-16LE"));
fos.close();
// Run vbs file
Runtime.getRuntime().exec("cmd.exe /C openitems.vbs");
} catch(Exception e){}
}