Display remote directory/all files in Jtree - file

i have some problem using JSCH to retrieve files/folders and populate them in JTree.
In JSCH to list files using :
Vector list = channelSftp.ls(path);
But i need that lists as java.io.File type. So i can get absolutePath and fileName,
And i don't know how to retrieve as java.io.File type.
Here is my code, and i try it work for local directory.
public void renderTreeData(String directory, DefaultMutableTreeNode parent, Boolean recursive) {
File [] children = new File(directory).listFiles(); // list all the files in the directory
for (int i = 0; i < children.length; i++) { // loop through each
DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());
// only display the node if it isn't a folder, and if this is a recursive call
if (children[i].isDirectory() && recursive) {
parent.add(node); // add as a child node
renderTreeData(children[i].getPath(), node, recursive); // call again for the subdirectory
} else if (!children[i].isDirectory()){ // otherwise, if it isn't a directory
parent.add(node); // add it as a node and do nothing else
}
}
}
Please help me, thanks before :)

you can define some variable in your java bean like
Vector<String> listfiles=new Vector<String>(); // getters and setters
Vector list = channelSftp.ls(path);
setListFiles(list); // This will list the files same as new File(dir).listFiles
in JSCH you can absolute path using ChannelSftp#realpath but unfortunately there no way to get Exact file with extension .But you can use something like this to check whether that file name existed in the target directory or not.
SftpATTRS sftpATTRS = null;
Boolean fileExists = true;
try {
sftpATTRS = channelSftp.lstat(path+"/"+"filename.*");
} catch (Exception ex) {
fileExists = false;
}

Try this (linux in remote server):
public static void cargarRTree(String remotePath, DefaultMutableTreeNode parent) throws SftpException {
//todo: change "/" por remote file.separator
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remotePath); // List source directory structure.
for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.
DefaultMutableTreeNode node = new DefaultMutableTreeNode(oListItem.getFilename());
if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
parent.add(node); // add as a child node
} else{
if (!".".equals(oListItem.getFilename()) && !"..".equals(oListItem.getFilename())) {
parent.add(node); // add as a child node
cargarRTree(remotePath + "/" + oListItem.getFilename(), node); // call again for the subdirectory
}
}
}
}
After you can invoque this method as:
DefaultMutableTreeNode nroot = new DefaultMutableTreeNode(sshremotedir);
try {
cargarRTree(sshremotedir, nroot);
} catch (SftpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
yourJTree = new JTree(nroot);

Related

How do I save multiple files in a package folder from a SwiftUI Document Based App?

I'm developing a SwiftUI document-based app that contains some easily serializable data plus multiple images. I'd like to save the document as a package (i.e, a folder) with one file containing the easily serialized data and a subfolder containing the images as separate files. My package directory should look something like this:
<UserChosenName.pspkg>/. // directory package containing my document data and images
PhraseSet.dat // regular file with serialized data from snapshot
Images/ // subdirectory for images (populated directly from my app as needed)
Image0.png
Image1.png
....
I've created a FileWrapper subclass that sets up the directory structure and adds the serialized snapshot appropriately but when I run the app in an iOS simulator and click on "+" to create a new document the app runs through the PkgFileWrapper init() and write() without error but returns to the browser window without apparently creating anything. I have declared that the Exported and Imported Type Identifiers conform to "com.apple.package". Can anyone suggest a way to get this working?
The PkgFileWrapper class looks like this:
class PkgFileWrapper: FileWrapper {
var snapshot: Data
init(withSnapshot: Data) {
self.snapshot = withSnapshot
let sWrapper = FileWrapper(regularFileWithContents: snapshot)
let dWrapper = FileWrapper(directoryWithFileWrappers: [:])
super.init(directoryWithFileWrappers: ["PhraseSet.dat" : sWrapper,
"Images" : dWrapper ])
// NOTE: Writing of images is done outside
// of the ReferenceFileDocument functionality.
}
override func write(to: URL,
options: FileWrapper.WritingOptions,
originalContentsURL: URL?) throws {
try super.write(to: to, options: options,
originalContentsURL: originalContentsURL)
}
required init?(coder inCoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The solution is to not override PkgFileWrapper.write(...). If the directory structure is set up correctly in the init(...) then the files and directories will be created automatically. The overridden write(...) function above has now been corrected.
If you want to write an image to the Images subdirectory, you could do something like the following:
func addImage(image: UIImage, name: String) {
let imageData = image.pngData()!
imageDirWrapper.addRegularFile(withContents: imageData,
preferredFilename: name)
}
The value of imageDirWrapper is the directory wrapper corresponding to the directory that holds your images, as created in PkgFileWrapper.init() above. A key concept you need to keep in mind here is that the "write" function will get called automatically at the appropriate time - you don't explicitly write out your image data. The ReferenceFileDocument class will arrange for that and will also arrange for your app to be passed the appropriate URL for setting up your file wrappers.
The imageDirWrapper variable is set in the required init(...) for the ReferenceFileDocument protocol:
required init(configuration: ReadConfiguration) throws {
phraseSet = PhraseSet()
if configuration.file.isDirectory {
if let subdir = configuration.file.fileWrappers {
// first load in the phraseSet
for (name, wrapper) in subdir {
if name == PkgFileWrapper.phraseSetFileName {
if let data = wrapper.regularFileContents {
phraseSet = try PhraseSet(json: data)
}
}
}
// next load in the images and put them into the phrases.
for (name, wrapper) in subdir {
if name == PkgFileWrapper.imageDirectoryName {
if let imageDir = wrapper.fileWrappers {
imageDirWrapper = wrapper
for (iName, iWrapper) in imageDir {
print("image file: \(iName)")
if let d = iWrapper.regularFileContents {
for p in phraseSet.phrases {
if p.imageName == iName {
// TBD: downsample
var uiD = ImageData(data: d)
if doDownSample {
uiD.uiimageData = downsample(data: d,
to: imageSize)
} else {
_ = uiD.getUIImage()
}
images[iName] = uiD
}
}
}
}
}
}
}
}
} else {
throw CocoaError(.fileReadCorruptFile)
}
You can see here how imageDirWrapper is set by looking through the passed-in directory's subdirectories for the image directory name. Also some bonus code: it first looks through the passed-in directory for the data file and loads it in; then it looks for the image directory and processes it.

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

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;
}

Fuse- Implementing Write operation

I am writing a custom fuse Mirror File System (in Ubuntu using FUSE-JNA). By mirror I mean, It will read from and write into a directory of local file system.
I implemented getattr, create, and read operation as below. All these work perfectly.
...
private final String mirroredFolder = "./target/mirrored";
...
...
public int getattr(final String path, final StatWrapper stat)
{
File f = new File(mirroredFolder+path);
//if current path is of file
if (f.isFile())
{
stat.setMode(NodeType.FILE,true,true,true,true,true,true,true,true,true);
stat.size(f.length());
stat.atime(f.lastModified()/ 1000L);
stat.mtime(0);
stat.nlink(1);
stat.uid(0);
stat.gid(0);
stat.blocks((int) ((f.length() + 511L) / 512L));
return 0;
}
//if current file is of Directory
else if(f.isDirectory())
{
stat.setMode(NodeType.DIRECTORY);
return 0;
}
return -ErrorCodes.ENOENT();
}
below create method creates new file in mirrored folder
public int create(final String path, final ModeWrapper mode, final FileInfoWrapper info)
{
File f = new File(mirroredFolder+path);
try {
f.createNewFile();
mode.setMode(NodeType.FILE, true, true, true);
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
read method reads file from mirrored folder
public int read(final String path, final ByteBuffer buffer, final long size, final long offset, final FileInfoWrapper info)
{
String contentOfFile=null;
try {
contentOfFile= readFile(mirroredFolder+path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String s = contentOfFile.substring((int) offset,
(int) Math.max(offset, Math.min(contentOfFile.length() - offset, offset + size)));
buffer.put(s.getBytes());
return s.getBytes().length;
}
But my write operation is not working.
Below is my Write method, which is incomplete.
public int write(final String path, final ByteBuffer buf, final long bufSize, final long writeOffset,
final FileInfoWrapper wrapper)
{
return (int) bufSize;
}
When I run it in Debugger mode, the path arguments shows Path=/.goutputstream-xxx (where xxx is random alphanumeric each time write method is called)
Please guide me how to correctly implement write operation.
Just write to the filename you're given. How do I create a file and write to it in Java?
The reason you're seeing path=/.goutputstream-xxx is because of https://askubuntu.com/a/151124. This isn't a bug in fuse-jna.

Getting path of audio file from sdcard

In my app I tried to pass the file path from one activity to another activity using intent.In my receiving activity I got the file path as "null".But when I print the file in first activity it prints the path.From my second activity I attach that file to mail using Gmailsender.This was the code I tried,
private void startRecord()
{
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
try
{
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
audioRecord.startRecording();
while(recording)
{
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++)
{
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
audioRecord.release();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String audiofile;
audiofile=file.getAbsolutePath();
System.out.println("File Path::::"+audiofile);
}
Intent is,
Intent sigout=new Intent(getApplicationContext(),WeeklyendActivity.class);
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
startActivity(sigout);
In my receiving activity,
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
System.out.println("paathhhy frfom ::"+patty);
It prints null.Can anyone help me how to get the file path.And more thing I am not sure whether the audio would save in that file correctly?
Please anyone help me!!!Thanks in advance!
Based on your information that audioFile is a variable of type File, when you do this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
you are putting a File object in the extras Bundle. Then, when you try to get the extra from the Bundle you do this:
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
However, the object in this extra is of type File, not type String. This is why you are getting null.
If you only want to pass the name of the file, then put the extra like this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile.getAbsolutePath());

Google Drive API - too slow.

I've just working on Google Drive API. I have one problem, it's too slow. I use methods like in the Documentation. For example:
List<File> getFilesByParrentId(String Id, Drive service) throws IOException {
Children.List request = service.children().list(Id);
ChildList children = request.execute();
List<ChildReference> childList = children.getItems();
File file;
List<File> files = new ArrayList<File>();
for (ChildReference child : childList) {
file = getFilebyId(child.getId(), service);
if (file == null) {
continue;
} else if (file.getMimeType().equals(FOLDER_IDENTIFIER)) {
System.out.println(file.getTitle() + " AND "
+ file.getMimeType());
files.add(file);
}
}
return files;
}
private File getFilebyId(String fileId, Drive service) throws IOException {
File file = service.files().get(fileId).execute();
if (file.getExplicitlyTrashed() == null) {
return file;
}
return null;
}
QUESTION: that method works, but too slow, for about 30 second.
How can I optimize this? For example, not to get all files (Only folder, or only files). or something like that.
you can use the q parameter and some stuff like :
service.files().list().setQ(mimeType != 'application/vnd.google-apps.folder and 'Id' in parents and trashed=false").execute();
This will get you all the files that are not folder, not trashed and whose parent has the id Id. All in one request.
And BTW, the API is not slow. Your algorithm, which makes too many of request, is.
public void getAllFiles(String id, Drive service) throws IOException{
String query="'"+id + "'"+ " in parents and trashed=false and mimeType!='application/vnd.google-apps.folder'";
FileList files = service.files().list().setQ(query).execute();
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
}

Resources