Java: List Cameras that are Plugged In - java

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.

Related

actian JCL example

Does anyone have an example of retrieving data using Actian's JCL to a loosely coupled pervasive database in Java? The database I am connecting to only has DAT files. My goal is to create a link between pervasive and MS SQL.
I am not looking for a freebie, but someone to point me in the right direction so I can learn and grow.
Thank you in advanced!
Found this in my archives. Don't know when it was written, whether it works, or if this interface is still supported. You don't say what version of PSQL you're using so I don't even know if this will work with your version.
import pervasive.database.*;
public class VersionTest implements Consts
{
public VersionTest()
{
try
{
Session session = Driver.establishSession();
Database db = session.connectToDatabase("PMKE:");
XCursor xcursor = db.createXCursor(57000);
//Using local TABL.DAT (length 255 assures no leftovers!)
xcursor.setKZString(0,255,"plsetup\\tabl.dat");
//Open the file to load local MKDE
int status = xcursor.BTRV(BTR_OPEN);
System.out.println("Local Open status: " + status);
//Using remote TABL.DAT (length 255 assures no leftovers!)
xcursor.setKZString(0,255,"h:\\basic2c\\develop\\tabl.dat");
//set the buffer size
xcursor.setDataSize(15);
//get version
status = xcursor.BTRV(BTR_VERSION);
System.out.println("Version status: " + status);
// should be 15, always prints 5
System.out.println("Version length: " + xcursor.getRecLength());
System.out.println("Version: " + xcursor.getDString(0,15));
// try with an open file on a server
XCursor xcursor2 = db.createXCursor(57000);
//Using remote TABL.DAT (length 255 assures no leftovers!)
xcursor2.setKZString(0,255,"h:\\basic2c\\develop\\tabl.dat");
//Open the file
status = xcursor2.BTRV(BTR_OPEN);
System.out.println("Remote Open status: " + status);
//set the buffer size
xcursor2.setDataSize(15);
//get version
status = xcursor2.BTRV(BTR_VERSION);
System.out.println("Version status: " + status);
// should be 15, always prints 5
System.out.println("Version length: " + xcursor2.getRecLength());
System.out.println("Version: " + xcursor2.getDString(0,15));
// clean up resources
Driver.killAllSessions();
}catch(Exception exp)
{
exp.printStackTrace();
}
}
public static void main(String[] args)
{
new VersionTest();
}
}
JCL APIs are still supported with Actian PSQL v12 and v13.
You can find more documentation on retrieving data using Actian JCL at
http://docs.pervasive.com/products/database/psqlv12/wwhelp/wwhimpl/js/html/wwhelp.htm#href=jcl/java_api.2.2.html
To link to MS Sql Server you would need to create the data dictionary files(DDFs) for the PSQl data files to use with relational interfaces.

32-bit application works in Eclipse, but not after being deployed. (no errors..)

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?

How to access network paths from Java on OSX?

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.

How to check if a Windows version is Genuine or not?

Is it possible to check whether a Windows installation is Genuine or not programmatically?
Lets just say I want to check Windows 7 from C, C++, Java or Python.
this from CodeProject, in C++ ( Check for Windows Genuine in VC++ )
#include <slpublic.h>
#pragma comment(lib,"Slwga.lib")
bool IsWindowsGenuine()
{
GUID uid;
RPC_WSTR rpc=(RPC_WSTR)_T("55c92734-d682-4d71-983e-d6ec3f16059f");
UuidFromString(rpc,&uid);
SL_GENUINE_STATE state;
SLIsGenuineLocal(&uid,&state,NULL);
return state == SL_GENUINE_STATE::SL_GEN_STATE_IS_GENUINE;
}
From here: Here is a vbscript that does it
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colWPA = objWMIService.ExecQuery _
("Select * from Win32_WindowsProductActivation")
For Each objWPA in colWPA
Wscript.Echo "Activation Required: " & objWPA.ActivationRequired
Wscript.Echo "Description: " & objWPA.Description
Wscript.Echo "Product ID: " & objWPA.ProductID
Wscript.Echo "Remaining Evaluation Period: " & _
objWPA.RemainingEvaluationPeriod
Wscript.Echo "Remaining Grace Period: " & objWPA.RemainingGracePeriod
Wscript.Echo "Server Name: " & objWPA.ServerName
Next
The Java solution is to use Process to run the C++ or VBScript solution as a child process.

Help to quick start NSS

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

Categories