I try to access a network folder / UNC path from Java on Mac OSX. On Windows, the following test program works fine (at least one of the tested paths):
public class PathTest {
public static void main(String[] args) {
for (String path : Arrays.asList(
"\\\\myserver\\transfer", "//myserver/transfer", "file://myserver/transfer", "smb://myserver/transfer")) {
File f = new File(path);
System.out.println(path + ": " + f.getAbsolutePath() + ", " + f.exists());
Path p = Paths.get(path);
System.out.println(path + ": " + p.toAbsolutePath() + ", " + Files.exists(p));
}
}
}
on Mac OS it fails to reach the folders:
\\myserver\transfer: /Users/tim/IdeaProjects/PathTest/\\myserver\transfer, false
//myserver/transfer: /myserver/transfer, false
file://myserver/transfer: /Users/tim/IdeaProjects/PathTest/file://myserver/transfer, false
smb://myserver/transfer: /Users/tim/IdeaProjects/PathTest/smb://myserver/transfer, false
When I use Finder, I can access the Folder (using the Guest user), by using "smb://myserver/transfer". What's wrong?
EDIT added NIO.2 test
Either mount the partition and access it as any local directory or use a specialized library such as JCIFS or Apache Commons VFS.
Related
I have a directory: <dir>\Report\<env>\Log_XXX\Logs
where XXX is randomly created at run time, so I have to create a file inside Logs folder.
Following is what I tried to generate the Logs folder:
new File(System.getProperty("user.dir") + "/Report/" + System.getProperty("env") + "/" + Pattern.compile("^Log_") + "/Logs").mkdirs();
Based on your comments, it appears you are trying to locate the one and only subdirectory whose base name starts with Log_. You can accomplish this with Files.list:
Path logParent = Paths.get(
System.getProperty("user.dir"),
"Report",
System.getProperty("env"));
Path logDir;
try (Stream<Path> listing = Files.list(logParent)) {
Optional<Path> match = listing.filter(p -> Files.isDirectory(p) &&
p.getFilename().toString().startsWith("Log_")).findFirst();
logDir = match.orElseThrow(() -> new RuntimeException(
"No log directory found in " + logParent));
}
I need help. I am writing a Java FX application in Eclipse, with the use of e(fx)clipse. I am using it's generic build.fxbuild to generate the ant script needed to develop my .EXE file.
The application works perfectly in Eclipse IDE. And when packaged with a 64-bit JDK, it even works perfectly after being deployed as an .EXE.
My problem arises when I package it with a 32-bit JDK for a 32-bit install. With the 32-bit JDK, it still runs perfectly in Eclipse. When I create the .EXE, it seemingly runs fine. The problem is... the software is made to take an excel file of addresses, compare them to a sql database of addresses, and then append the excel file with recommendations of "ID"'s from the SQL database to give customer service a reference of which address (from excel) may exist in our database. The only thing the software doesn't do is the appending. But, it creates the XSSFWorkbook, and resaves the workbook and opens it. So it's getting the beginning code of this segment, as well as the end. But something is happening in the middle for 32-bit vs 64-bit.
Need help!
public static void writeMatchedRecords(XSSFWorkbook wb, HashMap<Integer, ExcelAddress> excelRecords,
HeaderTemplate template) {
if (Defaults.DEBUG) {
System.out.println("Writing " + excelRecords.size() + " excel records");
}
// Variable to allow writing to excel file
CreationHelper createHelper = wb.getCreationHelper();
// Iterate through every row of the excel sheet
for (Row row : wb.getSheetAt(0)) {
if (excelRecords.containsKey(row.getRowNum() + 1)) {
ExcelAddress excelTemp = excelRecords.get(row.getRowNum() + 1);
HashMap<Double, ArrayList<ShipTo>> matchedShipTos = excelTemp.getMatchedShipTos();
if (Defaults.DEBUG) {
System.out.print(row.getCell(template.getColName()) + " from Excel matches with " + excelTemp.getName() + " from HASH with " + matchedShipTos.size() + " matches.");
}
if (matchedShipTos.isEmpty() == false) {
if (Defaults.DEBUG) {
System.out.println(" (non-zero confirmed)");
}
// If Matched Ship contains 100% matches remove all other
// matches
if (matchedShipTos.containsKey(1d)) {
HashMap<Double, ArrayList<ShipTo>> tempHM = new HashMap<Double, ArrayList<ShipTo>>();
tempHM.put(1d, matchedShipTos.get(1d));
matchedShipTos.clear();
matchedShipTos.putAll(tempHM);
}
Map<Double, ArrayList<ShipTo>> sortedShipTos = new TreeMap<Double, ArrayList<ShipTo>>(matchedShipTos).descendingMap();
for (Map.Entry<Double, ArrayList<ShipTo>> entry : sortedShipTos.entrySet()) {
for (ShipTo shipTo : entry.getValue()) {
if (Defaults.DEBUG) {
System.out.print("Ship to Match: ");
System.out.print(shipTo.getName());
System.out.print(" P: " + entry.getKey() + "\n");
}
if (row.getLastCellNum() == wb.getSheetAt(0).getRow(0).getLastCellNum()) {
// Create additional headers
wb.getSheetAt(0).getRow(0).createCell(row.getLastCellNum())
.setCellValue(createHelper.createRichTextString("Probability"));
wb.getSheetAt(0).getRow(0).createCell(row.getLastCellNum() + 1)
.setCellValue(createHelper.createRichTextString("P21 - Ship to ID"));
wb.getSheetAt(0).getRow(0).createCell(row.getLastCellNum() + 2)
.setCellValue(createHelper.createRichTextString("P21 - Ship to Name"));
wb.getSheetAt(0).getRow(0).createCell(row.getLastCellNum() + 3).setCellValue(
createHelper.createRichTextString("P21 - Ship to Address Line 1"));
}
row.createCell(row.getLastCellNum()).setCellValue(entry.getKey());
row.createCell(row.getLastCellNum())
.setCellValue(createHelper.createRichTextString(Integer.toString(shipTo.getId())));
row.createCell(row.getLastCellNum())
.setCellValue(createHelper.createRichTextString(shipTo.getName()));
row.createCell(row.getLastCellNum())
.setCellValue(createHelper.createRichTextString(shipTo.getAddress1()));
}
}
}
}
}
Date date = new Date();
int rand = (int) (Math.random() * 10);
File file = new File(System.getProperty("user.home") + "/Desktop/"
+ String.format("%1$s %2$tF%3$s", template.getTemplateName(), date, " (" + rand + ").xlsx"));
try
{
FileOutputStream fileout = new FileOutputStream(file);
wb.write(fileout);
fileout.close();
Desktop.getDesktop().open(file);
} catch (
Exception e)
{
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}
I got a similar problem with SWT
The general problem is when you need some native functions (like screen system), which depend on a particular jar.
related discussions about FX:
Creating 32 bit JavaFx Native Bundle in 64 bit machine
https://github.com/javafx-maven-plugin/javafx-maven-plugin/issues/81
Does JavaFX work in 32-bit Windows? (or with a 32-bit JVM)?
My way:
1 find the JAR
Finding javafx jar file for windows
2 embark the 2 jars in you app
3 at runtime, check 32/64
Properties prop=java.lang.System.getProperties();
String 32_64=prop.getProperty("sun.arch.data.model");
// => 32 or 64
4 load the "good" jar at runtime (check before is already loaded)
How should I load Jars dynamically at runtime?
I receive this warning
[javac] SSLTunnelSocketFactory.java:120: warning:
sun.net.www.protocol.http.HttpURLConnection is Sun proprietary API and
may be removed in a future release
[javac] + sun.net.www.protocol.http.HttpURLConnection.userAgent
for
if(NetworkUtils.isIPV6Compatible()&& NetworkUtils.isValidIPV6Address(host)){
msg = "CONNECT [" + host + "]:" + port + " HTTP/1.0\n"
+ "User-Agent: "
+ sun.net.www.protocol.http.HttpURLConnection.userAgent
+ "\r\n\r\n";
}
Do you have an idea what can I use instead (preferably not a an external jar but from the installed JVM)?
By default that variable is defined as follows:
String javaVersion = "Java/" + System.getProperty("java.version");
String userAgent = System.getProperty("http.agent") == null ? javaVersion : System.getProperty("http.agent") + " " + javaVersion;
So you can replace that variable with this one or with the name of your application or with any other string you like (since the resulting string is not the User-Agent of a common browser I assume that no JavaScript or any other code will check for it).
My program currently gets a list of drives plugged into the computer with File.listRoots(). But, when I plug a camera or an MP3 player into the computer directly (instead of inserting the memory card), it's not listed, nor does it have a drive letter in Windows Explorer. For example, here's the location of my camera:
Computer\Canon PowerShot SD750\Removable storage
How can I also list cameras/other devices that do not have a drive letter? I assume this will require a JNI library of some sort, but I don't know for sure obviously.
Thanks!
P.S. Out of desperation, I did try to list the contents of Computer\; it didn't work of course.
Update: I found this question here: Portable Device Path on Windows ; that's exactly the problem I'm having, but there is no solution laid out there.
Java 7 has some promising looking classes in this area, like this one:
http://download.java.net/jdk7/docs/api/java/nio/file/FileSystem.html
Assuming that you need it to work on Java 6 as well, I would suggest running a shell script and parsing its output.
On Windows you could run mountvol, on Unix/MacOS X mount etc. Of course parsing the output would be somewhat tedious and you would have to worry about every OS your app runs on, but hey, at least... not sure what.... it works?
Here is some sample code which seems helpful on Windows:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Volume")
For Each objItem In colItems
WScript.Echo "Automount: " & objItem.Automount
WScript.Echo "Block Size: " & objItem.BlockSize
WScript.Echo "Capacity: " & objItem.Capacity
WScript.Echo "Caption: " & objItem.Caption
WScript.Echo "Compressed: " & objItem.Compressed
WScript.Echo "Device ID: " & objItem.DeviceID
WScript.Echo "Dirty Bit Set: " & objItem.DirtyBitSet
WScript.Echo "Drive Letter: " & objItem.DriveLetter
WScript.Echo "Drive Type: " & objItem.DriveType
WScript.Echo "File System: " & objItem.FileSystem
WScript.Echo "Free Space: " & objItem.FreeSpace
WScript.Echo "Indexing Enabled: " & objItem.IndexingEnabled
WScript.Echo "Label: " & objItem.Label
WScript.Echo "Maximum File Name Length: " & objItem.MaximumFileNameLength
WScript.Echo "Name: " & objItem.Name
WScript.Echo "Quotas Enabled: " & objItem.QuotasEnabled
WScript.Echo "Quotas Incomplete: " & objItem.QuotasIncomplete
WScript.Echo "Quotas Rebuilding: " & objItem.QuotasRebuilding
WScript.Echo "Serial Number: " & objItem.SerialNumber
WScript.Echo "Supports Disk Quotas: " & objItem.SupportsDiskQuotas
WScript.Echo "Supports File-Based Compression: " & _
objItem.SupportsFileBasedCompression
WScript.Echo
Next
Here is the output I got for my ebook reader:
Automount: True
Block Size: 4096
Capacity: 999120896
Caption: G:\
Compressed:
Device ID: \\?\Volume{8e3b4ce5-a124-11e0-9d2b-e30c5839642d}\
Dirty Bit Set: False
Drive Letter: G:
Drive Type: 2
File System: FAT32
Free Space: 663683072
Indexing Enabled:
Label: PocketBook9
Maximum File Name Length: 255
Name: G:\
Quotas Enabled:
Quotas Incomplete:
Quotas Rebuilding:
Serial Number: 1276177233
Supports Disk Quotas: False
Supports File-Based Compression: False
The solution to above problem using JMTP library on
http://code.google.com/p/jmtp/
Here is my code
package jmtp;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import java.io.*;
import java.math.BigInteger;
import jmtp.PortableDevice;
import jmtp.*;
public class Jmtp {
public static void main(String[] args) {
PortableDeviceManager manager = new PortableDeviceManager();
PortableDevice device = manager.getDevices()[0];
// Connect to my mp3-player
device.open();
System.out.println(device.getModel());
System.out.println("---------------");
// Iterate over deviceObjects
for (PortableDeviceObject object : device.getRootObjects()) {
// If the object is a storage object
if (object instanceof PortableDeviceStorageObject) {
PortableDeviceStorageObject storage = (PortableDeviceStorageObject) object;
for (PortableDeviceObject o2 : storage.getChildObjects()) {
//
// BigInteger bigInteger1 = new BigInteger("123456789");
// File file = new File("c:/JavaAppletSigningGuide.pdf");
// try {
// storage.addAudioObject(file, "jj", "jj", bigInteger1);
// } catch (Exception e) {
// //System.out.println("Exception e = " + e);
// }
//
System.out.println(o2.getOriginalFileName());
}
}
}
manager.getDevices()[0].close();
}
}
Donot forget add jmtp.dll files (that comes up with jmtp download) as a native library for more info see my answer on
http://stackoverflow.com/questions/12798530/including-native-library-in-netbeans
This may not be the answer you're looking for, but is assigning them to a drive letter not an option? You can usually manually do this with USB devices on Windows using My Computer > right-click > Manage > Storage.
It's possible that CaptureDeviceManager in JMF (java media framework) could help you but I kind of doubt it.
Maybe you can take a look at Morena Framework http://www.gnome.sk/Twain/jtp.htmlv (seems to be open source, but a little expensive; though there is a free evaluation version), it is for TWAIN compatible scanners/cameras (Windows/MAC) or SANE compatible (Linux or other unix flavor), to get a list of connected devices, you can do this:
import SK.gnome.morena.*;
import SK.gnome.twain.*;
public class Test
{
public static void main(String[] args) throws Exception
{
TwainSource[] sources=TwainManager.listSources();
if(sources == null) return;
for(int i = 0; i < sources.length; i++)
{
System.out.println("Twain source is: " + ts.toString());
}
}
}
Maybe that could help,if not I think maybe JMF is a possible solution.
I am starting into NSS and I managed to build it. The outcome was placed in a folder named dist and has several subfolders that contain several exe's dlls etc.
dist
/WINNT6.0_DBG.OBJ
/bin
/include
/lib
I am trying to try it but I am not sure what is the nssLibraryDirectory and nssSecmodDirectory .
For the nssLibraryDirectory should I copy everything in the dist in a single file and refer to it from nssLibraryDirectory? What about nssSecmodDirectory? I'm not sure how I am suppose to configure to start using sun's pkcs11.
For example this trivial:
String configName = "nss.cfg";
Provider p = new sun.security.pkcs11.SunPKCS11(configName );
Where nss.cfg is:
name = NSS
nssLibraryDirectory = E:\NSS\nss-3.12.4-with-nspr-4.8\mozilla\dist\WINNT6.0_DBG.OBJ\lib
nssDbMode = noDb
Gives exception
Caused by: java.io.IOException: The
specified module could not be found.
at
sun.security.pkcs11.Secmod.nssLoadLibrary(Native
Method)
nssLibraryDirectory should only contain the lib subdirectory.
Its also has to appear in PATH - either by modifying environment variable or specifying it in JVM parameters.
Some note from my hard trying.... I think it would help anyone who want to use NSS.
I tend to construct a String in Java code to know in which line the error occurs. I must say it's better because Eclipse can eliminate all String construction errors. Then you pay attention to values to fill in.
I use these code:
String config = "xxxxxxx" +
"xxxxxxx" +
"xxxxxxx" +
"\n";
provider = new SunPKCS11(new ByteArrayInputStream(config.getBytes()));
Security.insertProviderAt(provider, 1);
All flags for Provider config:
(from http://j7a.ru/_config_8java_source.html,
seems like openjdk 8 sun.security.pkcs11.Config.java.)
name=xxxxxx //some text, " must be escaped with \
library=/location/of/your/.so/or/.dll/file //not compatible with NSS mode, must be quoted if contains space, and if quoted, " must be escaped
description=
slot= //not compatible with NSS mode
slotListIndex= //not compatible with NSS mode
enableMechanisms=
disableMechanisms=
attributes=
handleStartupErrors=
insertionCheckInterval=
showInfo=true/false
keyStoreCompatibilityMode=
explicitCancel=
omitInitialize=
allowSingleThreadedModules=
functionList=
nssUseSecmod=true/false //not campatible with 'library'
nssLibraryDirectory= //not campatible with 'library'
nssSecmodDirectory= //not campatible with 'library'
nssModule=some text //not campatible with 'library'
nssDbMode=readWrite, readOnly, noDb //not campatible with 'library'
nssNetscapeDbWorkaround=true/false //not campatible with 'library'
nssArgs="name1='value1' name2='value2' name3='value3' ... " //not compatible with NSS mode
nssUseSecmodTrust=true/false
Examples of nssArgs=: (separated by space)
"nssArgs=\"configdir='" + NSS_JSS_Utils.getFireFoxProfilePath() + "' "
+ "certPrefix='' "
+ "keyPrefix='' "
+ "secmod='secmod.db' "
+ "flags='readOnly'\""
Some example of escaping in Java code:
String config = "name=\"NSS Module\"\n" +
"......" +
"\n";
If with space, must be quoted with " ". ' ' is not able to be used. Every " must be escaped with \.
Now, some real examples.
To use Firefox security modules via NSS:
String config = "name=\"NSS Module\"\n"
+ "attributes=compatibility\n"
+ "showInfo=true\n"
+ "allowSingleThreadedModules=true\n"
+ "nssLibraryDirectory=" + NSS_JSS_Utils.NSS_LIB_DIR + "\n"
+ "nssUseSecmod=true\n"
+ "nssSecmodDirectory=" + NSS_JSS_Utils.getFireFoxProfilePath();
To use libsoftokn3.so (I don't know what it's used for, but I see someone have used it like this with nssArgs):
String config = "library=" + NSS_JSS_Utils.NSS_LIB_DIR + "/libsoftokn3.so" + "\n"
+ "name=\"Soft Token\"\n";
+ "slot=2\n"
+ "attributes=compatibility\n"
+ "allowSingleThreadedModules=true\n"
+ "showInfo=true\n"
+ "nssArgs=\"configdir='" + NSS_JSS_Utils.getFireFoxProfilePath() + "' "
+ "certPrefix='' "
+ "keyPrefix='' "
+ "secmod='secmod.db' "
+ "flags='readOnly'\""
+ "\n";
NSS_JSS_Utils.NSS_LIB_DIR returns the directory where all the NSS library libs are. Sometimes they are installed by default(e.g., in my RedHat 7.2), but sometimes you must install them manually.
NSS_JSS_Utils.getFireFoxProfilePath() returns where your FireFox profile are located. If you use modutil shipped with NSS/NSPR, you can see your installed security modules are stored in the secmod.db in this folder. If you cannot find them, you may have taken the wrong file.
More info about how to fill these values:
NSS PKCS#11 Spec