Eclipse PDE: Get full path of an external file open in Workbench - pde

I am writing an Eclipse Plugin which requires me to get full path of any kind of file open in the Workspace.
I am able to get full path of any file which is part of any Eclipse project. Code to get open/active editor file from workspace.
public static String getActiveFilename(IWorkbenchWindow window) {
IWorkbenchPage activePage = window.getActivePage();
IEditorInput input = activePage.getActiveEditor().getEditorInput();
String name = activePage.getActiveEditor().getEditorInput().getName();
PluginUtils.log(activePage.getActiveEditor().getClass() +" Editor.");
IPath path = input instanceof FileEditorInput ? ((FileEditorInput) input).getPath() : null;
if (path != null) {
return path.toPortableString();
}
return name;
}
However, if any file is drag-dropped in Workspace or opened using File -> Open File. For instance, I opened a file from /Users/mac/log.txt from File -> Open File. My plugin is not able to find location of this file.

After couple of days search, I found the answer by looking at the source code of Eclipse IDE.
In IDE.class, Eclipse tries to find a suitable editor input depending on the workspace file or an external file. Eclipse handles files in workspace using FileEditorInput and external files using FileStoreEditorInput. Code snippet below:
/**
* Create the Editor Input appropriate for the given <code>IFileStore</code>.
* The result is a normal file editor input if the file exists in the
* workspace and, if not, we create a wrapper capable of managing an
* 'external' file using its <code>IFileStore</code>.
*
* #param fileStore
* The file store to provide the editor input for
* #return The editor input associated with the given file store
* #since 3.3
*/
private static IEditorInput getEditorInput(IFileStore fileStore) {
IFile workspaceFile = getWorkspaceFile(fileStore);
if (workspaceFile != null)
return new FileEditorInput(workspaceFile);
return new FileStoreEditorInput(fileStore);
}
I have modified the code posted in the question to handle both files in Workspace and external file.
public static String getActiveEditorFilepath(IWorkbenchWindow window) {
IWorkbenchPage activePage = window.getActivePage();
IEditorInput input = activePage.getActiveEditor().getEditorInput();
String name = activePage.getActiveEditor().getEditorInput().getName();
//Path of files in the workspace.
IPath path = input instanceof FileEditorInput ? ((FileEditorInput) input).getPath() : null;
if (path != null) {
return path.toPortableString();
}
//Path of the externally opened files in Editor context.
try {
URI urlPath = input instanceof FileStoreEditorInput ? ((FileStoreEditorInput) input).getURI() : null;
if (urlPath != null) {
return new File(urlPath.toURL().getPath()).getAbsolutePath();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Fallback option to get at least name
return name;
}

Related

Xamrin Forms: How to read the details of a file stored in device's external storage?

I have implemented creating a folder and file in the device's external storage and writing data into that file using this thread.
Now I am trying to get the details of the file. For that, I have added a new function in the interface like below.
//Interface
public interface IAccessFile
{
void CreateFile(string text);
Java.IO.File GetFileDetails();
}
//Android implementation
public Java.IO.File GetFileDetails()
{
string rootPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePathDir = Path.Combine(rootPath, "StockPDT");
if (File.Exists(filePathDir))
{
string filePath = Path.Combine(filePathDir, "STOCK.TXT");
Java.IO.File file = new Java.IO.File(filePath);
return file;
}
else
{
return null;
}
}
But the problem is with the interface function part, getting below error":
The type or namespace name 'Java' could not be found (are you missing a using directive or an assembly reference?)
Screenshot:
If I return the file from the android part like above, it is easy to get the file details in the portable project. Instead of File, I try to return the file path, but it is empty. Is there any other way to get the file details other than this?
As per the notes in question, I tried to fetch the file details using its path.
Reference: https://learn.microsoft.com/en-us/answers/questions/319908/xamrin-forms-how-to-read-the-details-of-a-file-sto.html
//Interface
public interface IAccessFile
{
string GetFileDetails();
}
//Android implementation
public string GetFileDetails()
{
string rootPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePathDir = Path.Combine(rootPath, "StockPDT");
if (!File.Exists(filePathDir))
{
Directory.CreateDirectory(filePathDir);
}
string filePath = Path.Combine(filePathDir, "STOCK.TXT");
return filePath;
}
//Main Project:
string path = DependencyService.Get<IAccessFile>().GetFileDetails();
string fileDetails = File.ReadAllText(path);

Codename One API to append / merge files

To merge Storage files in Codename One I elaborated this solution:
/**
* Merges the given list of Storage files in the output Storage file.
* #param toBeMerged
* #param output
* #throws IOException
*/
public static synchronized void mergeStorageFiles(List<String> toBeMerged, String output) throws IOException {
if (toBeMerged.contains(output)) {
throw new IllegalArgumentException("The output file cannot be contained in the toBeMerged list of input files.");
}
// Note: the temporary file used for merging is placed in the FileSystemStorage because it offers the method
// openOutputStream(String file, int offset) that allows appending to a stream. Storage doesn't have a such method.
long writtenBytes = 0;
String tempFile = FileSystemStorage.getInstance().getAppHomePath() + "/tempFileUsedInMerge";
for (String partialFile : toBeMerged) {
InputStream in = Storage.getInstance().createInputStream(partialFile);
OutputStream out = FileSystemStorage.getInstance().openOutputStream(tempFile, (int) writtenBytes);
Util.copy(in, out);
writtenBytes = FileSystemStorage.getInstance().getLength(tempFile);
}
Util.copy(FileSystemStorage.getInstance().openInputStream(tempFile), Storage.getInstance().createOutputStream(output));
FileSystemStorage.getInstance().delete(tempFile);
}
This solution is based on the API FileSystemStorage.openOutputStream(String file, int offset), that is the only API that I found to allow to append the content of a file to another.
Are there other API that can be used to append or merge files?
Thank you
Since you end up copying everything to a Storage entry I don't see the value of using FileSystemStorage as an intermediate merging tool.
The only reason I can think of is integrity of the output file (e.g. if failure happens while writing) but that can happen here too. You can guarantee integrity by setting a flag e.g. creating a file called "writeLock" and deleting it when write has finished successfully.
To be clear I would copy like this which is simpler/faster:
try(OutputStream out = Storage.getInstance().createOutputStream(output)) {
for (String partialFile : toBeMerged) {
try(InputStream in = Storage.getInstance().createInputStream(partialFile)) {
Util.copyNoClose(in, out, 8192);
}
}
}

Is there a way in selenium to upload the last downloaded file with dynamic name?

The problem I am facing is I have a file which is having a dynamic number at the last.
For example: Tax_subscription_124.pdf which changes everytime.
Can I upload this particular file as currently I am downloading it in a particular location but not able to upload the same due to dynamic name?
The following code returns the last modified file or folder:
public static File getLastModified(String directoryFilePath)
{
File directory = new File(directoryFilePath);
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
}
}
}
return chosenFile;
}
Note that it required Java 8 or newer due to the lambda expression.
After that
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys(chosenFile);

How to get last downloaded file using selenium

Is there anyway I can get the last downloaded file using selenium. Currently I am downloading an Excel file using selenium, I need to get that file and read it. the reading part is covered, but I need the downloaded file path and file name in order to read it. So far i haven't found anything which can help. I am looking mainly for a google chrome solution, but firefox works too.
Thanks in advance
You can save your download to a fix location by using the profile. Check these discussions:
Downloading file to specified location with Selenium and python
Access to file download dialog in Firefox
As you have mentioned that you have covered the reading part. You can read it from that fixed location.
Below is the code snippet that can help resolve the above query:
**Changes in driver file:**
protected File downloadsDir = new File("");
if (browser.equalsIgnoreCase("firefox"))
{
downloadsDir = new File(System.getProperty("user.dir") + File.separatorChar + "downloads");
if (!downloadsDir.exists())
{
boolean ddCreated = downloadsDir.mkdir();
if (!ddCreated) {
System.exit(1);
}
}
}
/*Firefox browser profile*/
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream");
**Empty the download directory[Can be implemented as #BeforeClass]:**
public void emptyDownloadsDir()
{
// Verify downloads dir is empty, if not remove all files.
File[] downloadDirFiles = downloadsDir.listFiles();
if (downloadDirFiles != null) {
for (File f : downloadDirFiles) {
if (f.exists()) {
boolean deleted = FileUtility.delete(f);
assertTrue(deleted, "Files are not deleted from system local directory" + downloadsDir + ", skipping the download tests.");
}
}
}
}
**Check the Latest downloaded file:**
/*Test file*/
protected static String EXCEL_FILE_NAME= Test_Excel_File.xls;
protected static int WAIT_IN_SECONDS_DOWNLOAD = 60;
// Wait for File download.
int counter = 0;
while (counter++ < WAIT_IN_SECONDS_DOWNLOAD && (downloadsDir.listFiles().length != 1 || downloadsDir.listFiles()[0].getName().matches(EXCEL_FILE_NAME))) {
this.wait(2);
}
// Verify the downloaded File by comparing name.
File[] downloadDirFiles = downloadsDir.listFiles();
String actualName = null;
for (File file : downloadDirFiles) {
actualName = file.getName();
if (actualName.equals(EXCEL_FILE_NAME)) {
break;
}
}
assertEquals(actualName, EXCEL_FILE_NAME, "Last Downloaded File name does not matches.");
import os
import glob
home = os.path.expanduser("~")
downloadspath=os.path.join(home, "Downloads")
list_of_files = glob.glob(downloadspath+"\*.pptx") # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
Simplified solution to get the path to last file in Downloads folder. The above code will get path of the latest .pptx file in Downlodas. Change the extension as required. Or else you can chose not to specify the extension
Note, Shared answer is specific to Chrome Browser and will ONLY return LATEST downloaded file. But we can modify accordingly it for other browsers and for all files as well.
Let say, how we test latest downloaded file in browser.
In existing test browser Open NewTab Window
Go to
downloads (chrome://downloads/)
Check if expected file is there
or not
Now same thing in selenium using java
driver.get("chrome://downloads/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = (WebElement) js.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#mainContainer > iron-list > downloads-item').shadowRoot.querySelector('#content')");
String latestFileName= element.getText();

File exists but program throws a FileNotFoundException

/*
*This program checks type casting from String to int/double from a file
*/
import java.io.*;
import java.lang.String;
public class ConvertingStringsToNums {
public static void main (String[] args){
File dataFile = new File("/files/scores.dat");
FileReader in;
BufferedReader readFile;
String score;
double avgScore, totalScores = 0;
int numScores = 0;
//------------------------------------------------------------
try {
in = new FileReader(dataFile);
readFile = new BufferedReader(in);
while((score = readFile.readLine()) != null) {
numScores += 1;
System.out.println(score);
totalScores += Double.parseDouble(score);
}
avgScore = totalScores / numScores;
readFile.close();
in.close();
} catch(FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
} //end try/catch
}
}
1) If you wish to open a file at an absolute file path on your hard drive:
br = new BufferedReader (
new FileReader(
new File ("/files/scores.dat")));
2) If you wish to open a file at an relative path relative to where you started your app:
br = new BufferedReader (
new FileReader(
new File ("files/scores.dat")));
3) If you wish to open a file at an relative path relative to your class files (particularly relevant for packages and/or for executing from a .jar or a .war):
this.getClass().getResourceAsStream ("files/scores.dat");
'Hope that helps
The reason is can be that you wont be having permission to open the file.
try chmod 755 scores.dat from terminal in order to change the permissions and see if the error still exist.
The answer to this problem exists in the javadocs for the File class:
For UNIX platforms, the prefix of an absolute pathname is always "/". Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix "/" and an empty name sequence.
In your code, you have the following:
File dataFile = new File("/files/scores.dat");
According to the documentation, this is an absolute path, which means Java is looking for a folder at the root of the filesystem called "files" and then looking for scores.dat in that folder.
If you instead expect to search for a files directory that is relative to the current directory, you'd need to omit the first /:
File dataFile = new File("files/scores.dat");
The other option is to use an absolute path to your data file, but you may run into problems if you change the location of your project or put the class files in a JAR file.
Try turning up your logging level to DEBUG or ALL so that you can see exactly where the program is trying to look. This will help you adjust your code to target the right folder.

Resources