I have been googling a little and did not find an answer which suited my specific case.
I am working on a project file manager classes, and discovered that it was developped to behave differently on Windows and Unix filesystems.
More specifically, it is compensating for the case-senstivity in Unix: when a file is not found, the manager will look for it in a case-insensitive way.
Before changing this code, I would like to implement some unit tests. However, our development machines and our CIP are both on Windows, and I have no Unix machine available. The machines and IDEs are provided by the customer. Virtualization is not an option, and dual-booting is even less.
Is there a way to test both Windows and Unix mode while being platform-independant for the build? I think the ideal would be to run the whole Test Class in a mode, and then in the other, but even a more hands-on solution would be great.
In production mode, the file managers are initialized using Spring, but they are the lowest level of the chain, using directly java.io.
Versions: Java 6, JUnit 4.9
You can use Jimfs with dependency
<dependency>
<groupId>com.google.jimfs</groupId>
<artifactId>jimfs</artifactId>
<version>1.1</version>
</dependency>
Then you could create a linux, windows and Mac file systems using
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.osX());
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows());
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
example
class FilePathReader {
String getSystemPath(Path path) {
try {
return path
.toRealPath()
.toString();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
class FilePathReaderUnitTest {
private static String DIRECTORY_NAME = "baeldung";
private FilePathReader filePathReader = new FilePathReader();
#Test
#DisplayName("Should get path on windows")
void givenWindowsSystem_shouldGetPath_thenReturnWindowsPath() throws Exception {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows());
Path path = getPathToFile(fileSystem);
String stringPath = filePathReader.getSystemPath(path);
assertEquals("C:\\work\\" + DIRECTORY_NAME, stringPath);
}
#Test
#DisplayName("Should get path on unix")
void givenUnixSystem_shouldGetPath_thenReturnUnixPath() throws Exception {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path path = getPathToFile(fileSystem);
String stringPath = filePathReader.getSystemPath(path);
assertEquals("/work/" + DIRECTORY_NAME, stringPath);
}
private Path getPathToFile(FileSystem fileSystem) throws Exception {
Path path = fileSystem.getPath(DIRECTORY_NAME);
Files.createDirectory(path);
return path;
}
}
All this copied from Baeldung.
You could dualboot Ubuntu easily by installing it with wubi.
I've learnt that unit-test should not access the file system for different reasons (speed being one of them).
For Java 6 look into theese:
http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaFileManager.html
http://docs.oracle.com/javase/6/docs/api/javax/swing/filechooser/FileSystemView.html
If you were to use Java 7 this might help you:
http://download.oracle.com/javase/7/docs/technotes/guides/io/fsp/filesystemprovider.html
you could use a VM to test it on unix. Virtual Box by Oracle is agood virtualization software. Install Ubuntu, or Fedora, or some other unix based OS' Disk Image. Transfer your files to the VM. You can directly check out from your source control into the VM and you should be good to go. Atleast I am assuming that is what you want to do : test your software in both windows and linux, but currently don't have linux at your disposal
Related
I am trying to use JIntellitype to listen to global hotkeys but I get this error:
Exception in thread "main"
com.melloware.jintellitype.JIntellitypeException: Could not load
JIntellitype.dll from local file system or from inside JAR at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:114)
at
com.melloware.jintellitype.JIntellitype.getInstance(JIntellitype.java:177)
at utils.HotKey.(HotKey.java:19) at
ui.Main.Catch_Hotkeys(Main.java:78) at ui.Main.(Main.java:20)
at ui.Main.main(Main.java:15) Caused by: java.io.IOException:
FromJarToFileSystem could not load DLL:
com/melloware/jintellitype/JIntellitype.dll at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:150)
at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:105)
... 5 more Caused by: java.lang.NullPointerException at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:146)
... 6 more
I have loaded the jar file and I also pointed to the folder where the dlls are located through Referenced Libraries.
Here is the code I am trying to run:
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.IntellitypeListener;
import com.melloware.jintellitype.JIntellitype;
public class HotKey extends Thread implements HotkeyListener, IntellitypeListener {
private final int CTRL_C_SHIFT = 10;
public HotKey()
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
if (!JIntellitype.isJIntellitypeSupported())
{
System.exit(1);
}
}
#Override
public void onIntellitype(int arg0)
{
}
#Override
public void onHotKey(int key)
{
if (key == CTRL_C_SHIFT)
{
System.out.println("smg");
}
}
}
Any idea how to fix this?
Your problem will occur because of a version problem between that OS version and the JRE version.
You should check:
Whether an appropriate dll file is installed in your OS system folder.
JIntellitype package has two dll files, one is for 32bit OSs and the other is for 64bit OSs, they have different names.
Check your Java Platform version in the properties of the projects.
You can try to change the Java Platform, if there are more than one types of JDKs.
Make sure about which one is for 64bit or 32bit version.
Have good luck!
I recommend you do something like this:
try
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
MyHotKeyListener hotKeyListener = new MyHotKeyListener();
hotKeyListener.addObserver(new MyEventListener());
JIntellitype.getInstance().addHotKeyListener(hotKeyListener);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
}
catch (JIntellitypeException je)
{
logger.warn("JIntellitype initialization failed.");
// DO WHATEVER (NOTIFY USERS?)
}
I can point to other threads, including one where the creator of this library himself denies problems with the library. However, many users such as myself encounter these sort of problems from time to time where JIntellitype fails to initialize and the only solution is to reboot the computer. Because of this, you should catch the JIntellitype exception (the only exception thrown by the library) and warn users (via dialog window) that the hotkey failed to register. You should give them the option to continue without them, or to reboot the computer and trying again.
Trust me.... unless this is a constant problem (which means you configured it incorrectly), it is your best alternative. This WILL happen from time to time at random.
Environment:
Java API google-api-services-datastore-protobuf v1beta2-rev1-3.0.0.
OS: Windows 7.
Goal:
Start Local Datastore Server using the method:
public void start(String sdkPath, String dataset, String cmdLineOptions)
from com.google.api.services.datastore.client.LocalDevelopmentDatastore.java in order to use it in unit tests.
Steps:
I downloaded gcd tool gcd-v1beta2-rev1-3.0.2.zip and put it to C:\gcd folder
(paths to gcd.cmd and gcd.sh are `C:\gcd).
Also, I set environment variables:
"DATASTORE_HOST"="http://localhost:8080" and
"DATASTORE_DATASET"="myapp".
Problem:
LocalDevelopmentDatastoreException occurs.
Caused by: java.io.IOException: Cannot run program "./gcd.sh" (in directory "C:\gcd"): CreateProcess error=2, The system cannot find the file specified.
Note that it tries to find ./gcd.sh but not gcd.cmd.
Java code:
String datasetName = "myapp";
String hostName = "http://localhost:8080";
DatastoreOptions options = new DatastoreOptions.Builder()
.host(hostName)
.dataset(datasetName).build();
LocalDevelopmentDatastoreOptions localOptions = new LocalDevelopmentDatastoreOptions.Builder()
.addEnvVar("DATASTORE_HOST", hostName)
.addEnvVar("DATASTORE_DATASET", datasetName).build();
LocalDevelopmentDatastore datastore = LocalDevelopmentDatastoreFactory.get().create(options, localOptions);
datastore.start("C:\\gcd", datasetName);
This code is based on the example from LocalDevelopmentDatastore.java documentation.
Please help.
It seems as though the method is only programmed to look for gcd.sh, as it doesn't appear there's anything in your config which could have helped this to not fail. I suggest you open a defect report in the Cloud Platform Public Issue Tracker.
Did you consider gcloud-java for using the Datastore?
It also has an option for programmatically starting the local datastore using LocalGcdHelper which should work on Windows.
I'm maintaining a Java Swing application that requires a connection to an instance of Microsoft SQL Server. For various reasons, I opted to replace the native SQL Server driver being used with jTDS (the aforementioned Microsoft drivers were not working at the time and have apparently failed in the field as well). When I try to run the executable .jar outside of the IDE, I run into issues because I'm missing the appropriate ntlmauth.dll dependency.
Before proceeding, it's important to note that this application is being developed and used in an extremely restrictive (Windows-only) environment:
I cannot install any software that requires Windows UAC authentication
My users cannot install or run any software that requires UAC authentication
This currently means I cannot write files to System32 or JAVA_HOME, and cannot use any sort of ProcessBuilder tomfoolery to start another JVM with whatever command line arguments I need
I cannot use executable wrappers/installers that would only require the UAC permission for the first time installation/setup
The solution I'm trying is a combination of this one and this one to check it--essentially packaging the .dll inside of the .jar, then extracting it and loading it if necessary--as most of the other solutions I've found have been incompatible with the above restrictions; however, I'm running into an issue where even after the native library is ostensibly "loaded," I get an exception saying it isn't.
My pre-startup code:
private static final String LIB_BIN = "/lib-bin/";
private static final String JTDS_AUTH = "ntlmauth";
// load required JTDS binaries
static {
logger.info("Attempting to load library {}.dll", JTDS_AUTH);
try {
System.loadLibrary(JTDS_AUTH);
} catch (UnsatisfiedLinkError e) {
loadFromJar();
}
try {
// do some quick checks to make sure that went ok
NativeLibraries nl = new NativeLibraries();
logger.debug("Loaded libraries: {}", nl.getLoadedLibraries().toString());
} catch (NoSuchFieldException ex) {
logger.info("Native library checker load failed", ex);
}
}
/**
* When packaged into JAR extracts DLLs, places these into
*/
private static void loadFromJar() {
// we need to put DLL in temp dir
String path = ***;
loadLib(path, JTDS_AUTH);
}
/**
* Puts library to temp dir and loads to memory
*/
private static void loadLib(String path, String name) {
name = name + ".dll";
try {
// have to use a stream
InputStream in = net.sourceforge.jtds.jdbc.JtdsConnection.class.getResourceAsStream(LIB_BIN + name);
// always write to different location
File fileOut = new File(System.getProperty("java.io.tmpdir") + "/" + path + LIB_BIN + name);
logger.info("Writing dll to: " + fileOut.getAbsolutePath());
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
System.load(fileOut.toString());
} catch (Exception e) {
logger.error("Exception with native library loader", e);
JOptionPane.showMessageDialog(null, "Exception loading native libraries: " + e.getLocalizedMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
}
}
As you can see, I basically copied the solution from the first link verbatim, with a few minor modifications just to try and get the application running. I also copied the class from the second link and named it NativeLibraries, the invocation of that method is fairly irrelevant but it shows up in the logs.
Anyway here are the relevant bits of the log output on starting up the application:
2015-07-20 12:32:33 INFO - Attempting to load library ntlmauth.dll
2015-07-20 12:32:33 INFO - Writing dll to: C:\Users\***\lib-bin\ntlmauth.dll
2015-07-20 12:32:33 DEBUG - Loaded libraries: [C:\Program Files\Java\jre1.8.0_45\bin\zip.dll, C:\Program Files\Java\jre1.8.0_45\bin\prism_d3d.dll, C:\Program Files\Java\jre1.8.0_45\bin\prism_sw.dll, C:\Program Files\Java\jre1.8.0_45\bin\msvcr100.dll, C:\Program Files\Java\jre1.8.0_45\bin\glass.dll, C:\Program Files\Java\jre1.8.0_45\bin\net.dll, C:\Users\***\lib-bin\ntlmauth.dll]
2015-07-20 12:32:33 INFO - Application startup
***
2015-07-20 12:32:36 ERROR - Database exception
java.sql.SQLException: I/O Error: SSO Failed: Native SSPI library not loaded. Check the java.library.path system property.
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:654) ~[jtds-1.3.1.jar:1.3.1]
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371) ~[jtds-1.3.1.jar:1.3.1]
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184) ~[jtds-1.3.1.jar:1.3.1]
at java.sql.DriverManager.getConnection(Unknown Source) ~[na:1.8.0_45]
at java.sql.DriverManager.getConnection(Unknown Source) ~[na:1.8.0_45]
One can see that the library was, indeed, "loaded," from the third line in the log (it's the last entry, if you don't feel like scrolling). However, I simply used the class that I felt like was probably using the native libraries (I also tried the TdsCore class to no avail), as the example that showed how to do this was just using a random class from the package the library was needed in.
Is there something I'm missing here? I'm not very experienced with the JNI or the inner workings of ClassLoaders, so I might just be loading it wrong. Any advice or suggestions would be greatly appreciated!
Welp I figured out a workaround: I ended up using JarClassLoader. This basically entailed copying all my dependencies, both Java and native, into a "libraries" folder within my main .jar, and disabling .jar signing in the IDE. The application is then run by a new class that simply creates a new JarClassLoader object and running the "invokeMain" method--an example is on the website. The whole thing took about three minutes, after several days of banging my head against a wall.
Hope this helps someone someday!
Ok, I know that System.getProperty("os.name") will give me the name of the OS I'm running under, but that's not a lot of help. What I need to know is if the OS I'm running on is a 'Unix-like' OS, I don't care if it's HP-UX, AIX, Mac OS X or whatever.
From the list of possible os.name values it seems like a quick and dirty way of detecting a 'Unix-like' OS is checking if os.name does not contain "Windows". The false positives that will give me are OSes my code is very unlikely to encounter! Still, I'd love to know a better way if there is one.
Use the org.apache.commons.lang.SystemUtils utility class from Commons Lang, it has a nice IS_OS_UNIX constant. From the javadoc:
Is true if this is a POSIX compilant
system, as in any of AIX, HP-UX, Irix,
Linux, MacOSX, Solaris or SUN OS.
The field will return false if OS_NAME
is null.
And the test becomes:
if (SystemUtils.IS_OS_UNIX) {
...
}
Simple, effective, easy to read, no cryptic tricks.
I've used your scheme in production code on Windows XP, Vista, Win7, Mac OS 10.3 - 10.6 and a variety of Linux distros without an issue:
if (System.getProperty("os.name").startsWith("Windows")) {
// includes: Windows 2000, Windows 95, Windows 98, Windows NT, Windows Vista, Windows XP
} else {
// everything else
}
Essentially, detect Unix-like by not detecting Windows.
File.listRoots() will give you an array of the file system root directories.
If you are on a Unix-like system, then the array should contain a single entry "/" and on Windows systems you'll get something like ["C:", "D:", ...]
Edit: #chris_l: I totally forgot about mobile phones. Some digging turns up that Android returns a "/\0\0" - a slash followed by two null bytes (assumed to be a bug). Looks like we avoid false positives for the time being through luck and coincidence. Couldn't find good data on other phones, unfortunately.
It's probably not a good idea to run the same code on desktops and mobile phones regardless, but it is interesting to know. Looks like it comes down to needing to check for specific features instead of simply the system type.
Javadoc says: On UNIX systems the value of this
* field is '/'; on Microsoft Windows systems it is '\'.
System.out.println( File.separatorChar == '/' ? "Unix" : "Windows" );
System.getProperty("os.name"); is about the best you are going to get.
I agree with #Fuzzy in that I think the only way that Java intended you to be able to get that information was through the os.name property.
The only other things I can think of are:
Have a shell script or batch file wrapper to launch your Java app that passes in OS information using the -D argument to the JVM. Though given your description, this doesn't sound doable.
You could try to check for the existence of an OS-specific directory. For instance, you could assume the directory "/" will always exist on a Unix-like system, but not on Windows and do something like this:
if((new File("/")).exists())
{
System.out.println("I'm on a Unix system!");
}
Try to kick off a Unix-specific command line command like ls and check the return code. If it worked, you're on a Unix-like system, if not you're on Windows.
All of those solutions are really just hacks though and frankly I don't really feel all that great about any of them. You're unfortunately probably best off with your original thought. Fun, eh?
Use File.pathSeparator or File.separator. The first will return ";" in Windows and ":" in Unix. The second will return "\" in Windows and "/" in Unix.
You could try to execute the uname command - should be available on all unixoid systems.
package com.appspot.x19290;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class UnixCheck {
public static void main(String[] args) {
UnixCheck s = UnixCheck.S;
String isUnix = s.unix ? "is Unix" : "not Unix";
try {
System.out.println(isUnix + ", devnull: " + s.devnull.getPath());
} catch (NullPointerException e) {
System.out.println(isUnix + ", devnull: unknown");
}
}
public static final UnixCheck S = new UnixCheck();
public static final UnixCheck TEST = new UnixCheck(true);
public final boolean unix;
public final File devnull;
private UnixCheck() {
this(false);
}
private UnixCheck(boolean testing) {
String path;
path = testing ? "/<dev>/<no><such><null><device>" : "/dev/null";
File devnull = devnullOrNone(path);
if (devnull == null) {
this.unix = false;
path = testing ? "<no><such><null><device>" : "nul";
this.devnull = devnullOrNone(path);
} else {
this.unix = true;
this.devnull = devnull;
}
}
private static File devnullOrNone(String name) {
File file = new File(name);
if (file.isFile())
return null;
if (file.isDirectory())
return null;
try {
FileInputStream i = new FileInputStream(file);
try {
i.read();
} finally {
i.close();
}
} catch (IOException e) {
return null;
}
return file;
}
}
Java is the key here. I need to be able to delete files but users expect to be able to "undelete" from the recycle bin. As far as I can tell this isn't possible. Anyone know otherwise?
Ten years later, with Java 9, finally there is a builtin way to move files to the Trash Bin
java.awt.Desktop.moveToTrash(java.io.File):
public boolean moveToTrash(File file)
Moves the specified file to the trash.
Parameters:
file - the file
Returns:
returns true if successfully moved the file to the trash.
The availability of this feature for the underlying platform can be tested with Desktop.isSupported(Desktop.Action.MOVE_TO_TRASH).
For various reasons Windows has no concept of a folder that simply corresponds to the Recycle Bin.
The correct way is to use JNI to invoke the Windows SHFileOperation API, setting the FO_DELETE flag in the SHFILEOPSTRUCT structure.
SHFileOperation documention
Java example for copying a file using SHFileOperation (the Recycle Bin link in the same article doesn't work)
Java 9 has new method but in my case I am restricted to Java 8.
I found Java Native Access Platform that has hasTrash() and moveToTrash() method. I tested it on Win 10 and Mac OS (Worked) for me.
static boolean moveToTrash(String filePath) {
File file = new File(filePath);
FileUtils fileUtils = FileUtils.getInstance();
if (fileUtils.hasTrash()) {
try {
fileUtils.moveToTrash(new File[] { file });
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
System.out.println("No Trash");
return false;
}
}
Maven Repository
https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform/5.1.0
Don't confuse It is Java Native Access Platform not Java Native Access
See the fileutil incubator project (part of the Java Desktop Integration Components project):
This incubator project is created to host those file utility functionalities, most of which are extensions to the java.io.File class in J2SE. There are frequent requests from Java developers for such features like: sending a file to trash bin, checking free disk space, accessing file attributes etc. This project addresses such frequently requested APIs.
Note, this should work not only on Windows, but on other platforms (Linux, Mac OS X) as well.
My 3 cents - use cmd util Recycle.exe with -f to force recycle (no prompt). Works perfectly.
public class Trash {
public void moveToTrash(File ... file) throws IOException {
moveToTrash(false, file);
}
public void promptMoveToTrash(File ... file) throws IOException {
moveToTrash(true, file);
}
private void moveToTrash(boolean withPrompt, File ... file) throws IOException {
String fileList = Stream.of(file).map(File::getAbsolutePath).reduce((f1, f2)->f1+" "+f2).orElse("");
Runtime.getRuntime().exec("Recycle.exe "+(withPrompt ? "" : "-f ")+fileList);
}
}
In JNA platform, the FileUtils doesn't use Win32 API. You should prefer W32FileUtils which supports Undo (restore the file from recycle bin).
Edit: as of the current version of JNA Platform (5.7.0), with FileUtils.getInstance(), this statement has become incorrect, and FileUtils will use the Win32 API.