JAVA - Access file from shared storage without mount - java

I have done set up a NAS server using NAS4Free and share a folder at:
\\NAS_SERVER_IP/SHARE_FOLDER_NAME
In SHARE_FOLDER_NAME directory contains resource files need to share to multiple clients
Now ,from clients , can I using Java to access (read/write) directly file from NAS server without mount shared folder to local clients

Copied from here, but changed the api call argument.
connecting to shared folder in windows with java
String url = "smb://[NAS server-IP or hostname]/file-or-directory-path";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("[company network domain]", "user", "password");
SmbFile dir = new SmbFile(url, auth);
for (SmbFile f : dir.listFiles())
{
System.out.println(f.getName());
}

For observing file/dir changes using JDK 6, you could use:
WatchService for Java 6
For JDK 7, WatchService is part of NIO package:
http://java.dzone.com/news/how-watch-file-system-changes

Finally, this one works with JDK6 as well. This way, we could observe file/dir changes in windows shared drivers without mounting/mapping them as a drive.
I've used following jars in classpath: commons-collections-4.4.0, commons-logging-1.1.2, commons-logging-api-1.1.2, commons-net-3.3, commons-vfs2-2.0, httpclient-4.3.1, jackrabbit-standalone-2.6.5, jcifs-1.3.17, jsch-0.1.51
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;
public class NFSChangeObserver
{
public static void main(String[] args) throws FileSystemException
{
/** need a non-daemon thread, because <code>DefaultFileMonitor</code> is internally marked as a daemon thread.
*/
Thread t = new Thread(new Runnable() {
#Override
public synchronized void run()
{
try
{
while(1!=2)
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}});
t.start();
FileSystemManager manager = VFS.getManager();
FileObject file = manager.resolveFile("\\\\[server-hostname]\\[directory-path]");
DefaultFileMonitor fm = new DefaultFileMonitor(new FileListener()
{
#Override
public void fileChanged(final FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " changed .." );
}
#Override
public void fileCreated(FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " created .." );
}
#Override
public void fileDeleted(FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " deleted .." );
}
});
fm.setDelay(5000);
fm.addFile(file);
FileObject[] children = file.getChildren();
for(FileObject child : children)
{
System.out.println(child.getURL());
}
fm.start();
}
}

Related

Exception found java "java.awt.AWTError:Assistive Technology not found"

My application running on JRE-6 64-bit. I enable Java's assistive technology using:
assistive_technologies=com.sun.java.accessibility.AccessBridge
But the files for JavaAccessBridge-64.dll, JAWTAccessBridge-64.dll, and WindowsAccessBridge-64.dll are not present in JRE 6 path.
I try to customize "java.library.path" path ,i download java access bridge and append folder path in "java.library.path".
I write below code ,
static Toolkit tk ;
static long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK + AWTEvent.MOUSE_EVENT_MASK + AWTEvent.KEY_EVENT_MASK;
public static void main(String[] args)
{
try {
String te= "D:\\AccessBridge" + File.pathSeparator + System.getProperty("java.library.path");
System.setProperty("java.library.path",te);
String library =System.getProperty("java.library.path");
tk = Toolkit.getDefaultToolkit();
} catch (Exception e1) {
e1.printStackTrace();
}
tk.addAWTEventListener(new AWTEventListener()
{
#Override
public void eventDispatched(AWTEvent e)
{
System.out.println(e.getID() + ", " + e);
}
}, eventMask);
}
Found a below exception.
Exception in thread "main" java.awt.AWTError: Assistive Technology not found: com.sun.java.accessibility.AccessBridge
at java.awt.Toolkit.loadAssistiveTechnologies(Toolkit.java:773)
at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:872)
at Automation.MyToolKit.main(MyToolKit.java:73)
Is it possible load this dll from different location instead of copy in to JRE folder?

Apache Commons IO File Monitoring capture events in subfolders

I'm using the following code to capture events in a given folder. It works fine, but my question is how can I capture events in sub folders in my given folder as well?
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class Monitor {
public Monitor() {
}
//path to a folder you are monitoring .
public static final String FOLDER = MYPATH;
public static void main(String[] args) throws Exception {
System.out.println("monitoring started");
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 5 * 1000;
File folder = new File(FOLDER);
if (!folder.exists()) {
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor =
new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
// Is triggered when a file is created in the monitored folder
#Override
public void onFileCreate(File file) {
// "file" is the reference to the newly created file
System.out.println("File created: "+ file.getCanonicalPath());
}
// Is triggered when a file is deleted from the monitored folder
#Override
public void onFileDelete(File file) {
try {
// "file" is the reference to the removed file
System.out.println("File removed: "+ file.getCanonicalPath());
// "file" does not exists anymore in the location
System.out.println("File still exists in location: "+ file.exists());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
}
I've read here enter link description here that this code is suppose to capture events in sub folders as well, but I does not work.
The statement you make regarding the hyperlink after your code is not accurate. The code in Capture events happening inside a directory DOES capture certain events (file create, file delete) in the main/root directory and subfolders. It does not monitor file modification or folder operations (create, delete, rename, etc.).
I have just tested it on 3 levels down (nested subfolders). As such the code you are referring to accomplishes what you are asking for. If you need something different please re-phrase/re-word your question.
If you need more information on the subject you might find this link: https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.html useful. It definitely helped me.

How to check if a folder exists?

I am playing a bit with the new Java 7 IO features. Actually I am trying to retrieve all the XML files in a folder. However this throws an exception when the folder does not exist. How can I check if the folder exists using the new IO?
public UpdateHandler(String release) {
log.info("searching for configuration files in folder " + release);
Path releaseFolder = Paths.get(release);
try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
for (Path entry: stream){
log.info("working on file " + entry.getFileName());
}
}
catch (IOException e){
log.error("error while retrieving update configuration files " + e.getMessage());
}
}
Using java.nio.file.Files:
Path path = ...;
if (Files.exists(path)) {
// ...
}
You can optionally pass this method LinkOption values:
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
There's also a method notExists:
if (Files.notExists(path)) {
Quite simple:
new File("/Path/To/File/or/Directory").exists();
And if you want to be certain it is a directory:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
To check if a directory exists with the new IO:
if (Files.isDirectory(Paths.get("directory"))) {
...
}
isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.
See: documentation.
Generate a file from the string of your folder directory
String path="Folder directory";
File file = new File(path);
and use method exist.
If you want to generate the folder you sould use mkdir()
if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}
You need to transform your Path into a File and test for existence:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
There is no need to separately call the exists() method, as isDirectory() implicitly checks whether the directory exists or not.
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
We can check files and thire Folders.
import java.io.*;
public class fileCheck
{
public static void main(String arg[])
{
File f = new File("C:/AMD");
if (f.exists() && f.isDirectory()) {
System.out.println("Exists");
//if the file is present then it will show the msg
}
else{
System.out.println("NOT Exists");
//if the file is Not present then it will show the msg
}
}
}
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
From SonarLint, if you already have the path, use path.toFile().exists() instead of Files.exists for better performance.
The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.
The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.
Noncompliant Code Example:
Path myPath;
if(java.nio.Files.exists(myPath)) { // Noncompliant
// do something
}
Compliant Solution:
Path myPath;
if(myPath.toFile().exists())) {
// do something
}

Netbeans imported JAR not loading on run

i see this question has been posted many times but it has been solved with adding
-Djava.library.path="./path" to the VM runtime options.
I have to build an app in JAVA which uses the JNotify classes.
this is the sample code:
package test;
import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyListener;
/**
*
* #author
*/
public class Test {
public void jnotifydemo() throws Exception {
// path to watch
String path = System.getProperty("user.home");
// watch mask, specify events you care about,
// or JNotify.FILE_ANY for all events.
int mask = JNotify.FILE_CREATED
| JNotify.FILE_DELETED
| JNotify.FILE_MODIFIED
| JNotify.FILE_RENAMED;
// watch subtree?
boolean watchSubtree = true;
// add actual watch
int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());
// sleep a little, the application will exit if you
// don't (watching is asynchronous), depending on your
// application, this may not be required
Thread.sleep(1000000);
// to remove watch the watch
boolean res = JNotify.removeWatch(watchID);
if (!res) {
// invalid watch ID specified.
}
}
class Listener implements JNotifyListener {
public void fileRenamed(int wd, String rootPath, String oldName,
String newName) {
print("renamed " + rootPath + " : " + oldName + " -> " + newName);
}
public void fileModified(int wd, String rootPath, String name) {
print("modified " + rootPath + " : " + name);
}
public void fileDeleted(int wd, String rootPath, String name) {
print("deleted " + rootPath + " : " + name);
}
public void fileCreated(int wd, String rootPath, String name) {
print("created " + rootPath + " : " + name);
}
void print(String msg) {
System.err.println(msg);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
System.out.println("Hello World");
new Test().jnotifydemo();
}
}
When i run this i get:
Error loading library, java.library.path=C:\Program Files\Java\jdk1.6.0_26\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;(continues)
Exception in thread "main" java.lang.UnsatisfiedLinkError: no jnotify in java.library.path
I have setup a Netbeans project and added the JAR file to the project so that the JAR is correctly in the lib/ folder of my project and everything is set in NETBEANS.
This correctly works if is setup the -Djava.library.path="./path" argument of the java VM, but if i imported my lib in NETBEANS that should be included in the path automatically.
I am doing something wrong or it is necessary to put every .jar in the classpath system variable? I would like to release this app so it can run on other systems that does not have JNotify in their libs.
Thanks
I am using Netbeans 7.2 on Win 7 32Bit
You are messing java jar files as library which has to be added only in netbeans classpath:
Simply in NetBeans on project properties click and adjust Library having your JAR file.
For the native libraries (so,dll,...) you need to have set: -Djava.library.path. As you did in your question.
So you have 2 steps:
1. from http://sourceforge.net/projects/jnotify/files/jnotify/jnotify-0.94/jnotify-lib-0.94.zip/download add jnotify-0.94.jar to your libraries as in picture above (this will update your classpath automatically)
2. jnotify.dll, or jnotify_64bit.dll for 64-bit windows place is some directory and ad this to your -Djava.library.path - add this to VM option of the projects property

javax.usb.UsbException: Properties file javax.usb.properties not found

I used the following code to get the manufacturerCode of the usb device attached to the system. I added the jsr80-1.0.1 jar. And I got the following error javax.usb.UsbException:
Properties file javax.usb.properties not found.
Any suggestions?
import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.usb.*;
public class USBListener {
public static void main(String[] args) {
try{
UsbServices services = UsbHostManager.getUsbServices();
UsbHub root = services.getRootUsbHub();
listDevices(root);
} catch (Exception e) {
System.out.println(e);
}
}
public static void listDevices(UsbHub hub) throws UnsupportedEncodingException, UsbException {
List devices = hub.getAttachedUsbDevices();
Iterator iterator = devices.iterator();
while(iterator.hasNext()) {
UsbDevice device = (UsbDevice)iterator.next();
describe(device);
if(device.isUsbHub()) {
System.out.println("is hub");
}
}
}
public static void describe(UsbDevice device)
throws UnsupportedEncodingException, UsbException {
UsbDeviceDescriptor descriptor = device.getUsbDeviceDescriptor();
byte manufacturerCode = descriptor.iManufacturer();
System.out.println("Manufacturer index: " + manufacturerCode);
System.out.println("Manufacturer String: " + device.getString(manufacturerCode));
System.out.println("USB version: " + decodeBCD(descriptor.bcdUSB()));
System.out.println("Maximum control packet size: " + descriptor.bMaxPacketSize0());
}
public static String decodeBCD(short bcd) {
int upper = (0xFF00 & bcd) >> 8;
int middle = (0xF0 & bcd) >> 4;
int lower = 0x0F & bcd;
return upper + "." + middle + "." + lower;
}
}
You need this file on your classpath. From the docs:
The javax.usb.properties file is a Java properties file that is
required by the API implementation loader class. The properties file
must be loadable by normal means (i.e. it must be in the CLASSPATH)
and it must contain the property javax.usb.services. This property
must be defined. Its value must be the fully qualified class name of a
class that implements the interface javax.usb.UsbServices. This class
will be loaded as the implementation of javax.usb.
And further, if you are seeing this error, you presumably haven't got a javax.usb implementation:
You need a javax.usb implementation; the file is provided by all
javax.usb implementations
See here: http://javax-usb.sourceforge.net/faq.html#what_is_properties_file

Categories

Resources