There are a number of ways to obtain a machine's network adapters & related info such as Sigar & java.net's getNetworkInterfaces(). However, using either of these means, I am unable to determine whether a certain adapter is wireless (unless the name/description explicitly says so).
Are there any ways to determine this through code? (I'd like to be able to do so in both Windows & Linux, but I am willing to deal with system specific solutions).
Edit: removed the part that is not relevant
maybe you could use the JNI (java native interface) to call a C-function which gets this flag... with C, this should be possible (though possible that the code would become unportable)
Edit: For linux, i found the following. Downloaded the source-code of wireless-tools, including iwconfig. They included library, iwlib.c, simply extracts the names of the interface from /proc/net/wireless or /proc/net/dev
You can get the sources from here, this is from Fedora. As the library extracts its data from a path of a standardized file-system, the only thing you need to have is kernel-support for procfs.
Now i can only lead you to the file "iwlib.c", function
void iw_enum_devices(int skfd, iw_enum_handler fn, char * args[], int count)
i don't know about those parameters, but the source code is commented. Maybe you will have to compare the list you get from java with the one you receive through this JNI-hack...
Guess it's a lot of work for a "little task"; hope you find your way through...
regards
If you want to build a platform specific JNI implementation of your functionality, the Windows API function you can use to get a list of wireless network interfaces is WlanEnumInterfaces in Wlanapi.h. You'll need to link Wlanapi.lib/.dll. Also, see the documentation.
I'd recommend that you build a little JNI library with two functions:
getWirlessInterfaceCount();
getWirelessInterfaceAddr(int nIf, char *addr);
Where you actually make sure the 6 bytes for the address are allocated on the Java side and just filled in on the native side. That way you don't need to worry about memory management on the native side. You can wrap those two JNI calls in a Java method like
List<NetworkInterface> getWirelesNetworkInterfaces();
.... which calls the two JNI methods, gets the list of all interfaces via the NetworkInterface API and throws out all interfaces whose address was not returned by the JNI methods.
Although this question is quite old, someone may be looking for this solution, so here it goes a simple way to find out in Windows.
In the current NetworkInterface class the function getName() will return unique names that can be things like "eth0", "wlan0" or "net0", always few letters plus a number.
After gathering the list of NetworkInterfaces and selecting the real ones you can then check if the getName() function returns "ethX" for a wired interface or "wlanX" for a wireless interface (X is a number that depends on how many interfaces you have in your computer.)
The following code is an example for how you can make this identification, although is necessary firstly to find what interfaces are real, there are many solutions for this.
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
public class TesteInterfaces {
public static void main(String[] args) {
Enumeration<NetworkInterface> tempNetInterface = null;
try {
tempNetInterface = NetworkInterface.getNetworkInterfaces();
} catch (SocketException ex) {
ex.printStackTrace();
}
for (NetworkInterface iNet : new ArrayList<>(Collections.list(tempNetInterface))) {
try {
if (iNet.getHardwareAddress() != null) { //This verification might not
//be enought to find if a Interface is real.
System.out.println(iNet.getDisplayName());
if (iNet.getName().contains("wlan")) {
System.out.println("It is WIRELESS");
} else {
System.out.println("It is NOT WIRELESS");
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
}
}
}
An output:
Intel(R) Centrino(R) Wireless-N 100
It is WIRELESS
Realtek PCIe GBE Family Controller
It is NOT WIRELESS
Related
I'm developing a "macro" for OpenOffice Calc. As the language, I chose Java, in order to get code assistance in Eclipse. I even wrote a small ant build script that compiles and embeds the "macro" in an *.ods file. In general, this works fine and surprisingly fast; I'm already using some simple stuff quite successfully.
BUT
So often I get stuck because with UNO, I need to "query" an interface for any given non-trivial object, to be able to access data / call methods of that object. I.e., I literally need to guess which interfaces a given object may provide. This is not at all obvious and not even visible during Java development (through some sort of meta-information, reflection or the like), and also sparsely documented (I downloaded tons of stuff, but I don't find the source or maybe JavaDoc for the interfaces I'm using, like XButton, XPropertySet, etc. - XButton has setLabel, but not getLabel - what??).
There is online documentation (for the most fundamental concepts, which is not bad at all!), but it lacks many details that I'm faced with. It always magically stops exactly at the point I need to solve.
I'm willing to look at the C++ code to get a clue what interfaces an object (e.g. the button / event I'm currently stuck with) may provide. Confusingly, the C++ class and file names don't exactly match the Java interfaces. It's almost what I'm looking for, but then in Java I don't really find the equivalent, or calling queryInterface on a given object returns null.. It's becoming a bit frustrating.
How are the UNO Java interfaces generated? Is there some kind of documentation in the code that serves as the origin for the generated (Java) code?
I think I really need to know what interfaces are available at which point, in order to become a bit more fluent during Java-UNO-macro development.
For any serious UNO project, use an introspection tool.
As an example, I created a button in Calc, then used the Java Object Inspector to browse to the button.
Right-clicking and choosing "Add to Source Code" generated the following.
import com.sun.star.awt.XControlModel;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XNameAccess;
import com.sun.star.drawing.XControlShape;
import com.sun.star.drawing.XDrawPage;
import com.sun.star.drawing.XDrawPageSupplier;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
//...
public void codesnippet(XInterface _oUnoEntryObject){
try{
XSpreadsheetDocument xSpreadsheetDocument = (XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class, _oUnoEntryObject);
XSpreadsheets xSpreadsheets = xSpreadsheetDocument.getSheets();
XNameAccess xNameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, xSpreadsheets);
Object oName = xNameAccess.getByName("Sheet1");
XDrawPageSupplier xDrawPageSupplier = (XDrawPageSupplier) UnoRuntime.queryInterface(XDrawPageSupplier.class, oName);
XDrawPage xDrawPage = xDrawPageSupplier.getDrawPage();
XIndexAccess xIndexAccess = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class, xDrawPage);
Object oIndex = xIndexAccess.getByIndex(0);
XControlShape xControlShape = (XControlShape) UnoRuntime.queryInterface(XControlShape.class, oIndex);
XControlModel xControlModel = xControlShape.getControl();
XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xControlModel);
String sLabel = AnyConverter.toString(xPropertySet.getPropertyValue("Label"));
}catch (com.sun.star.beans.UnknownPropertyException e){
e.printStackTrace(System.out);
//Enter your Code here...
}catch (com.sun.star.lang.WrappedTargetException e2){
e2.printStackTrace(System.out);
//Enter your Code here...
}catch (com.sun.star.lang.IllegalArgumentException e3){
e3.printStackTrace(System.out);
//Enter your Code here...
}
}
//...
Python-UNO may be better than Java because it does not require querying specific interfaces. Also XrayTool and MRI are easier to use than the Java Object Inspector.
Basically, I need to check the status of the n/w printer, if its on or not. Is there any way to do this in java?
Is there any third party API or tool for this?
I tried using PrintServiceLookup in java, but it does not give the status, if its on or not.
Also, if its not possible in java, is there any command that can be run in windows that will give the status of the printer?
Then I can run this command in java and check.
According to "How Network Printing Works" it really depends on the type of printer and the protocol which it supports. If you know the ip and the port used by you printer and if your printer supports SNMP (just to pick a protocol) you can use the SNMP protocoll to query your printer for information. There is the Java lib SNMP4j which can help you achive this. I would suggest to not use it unless the printer, the ip and the port will never (!) change for your setup. This is because you can run into several problems
How to discover an unknown printer ?
How to discover the port used by the printer ?
How to discover the protocoll used by the printer ?
Lets assume the questions above wouldn't be much of a problem and lets assume every printer would support SNMP. How to get informations out of it ? Besides using the mentioned java lib, you can use snmpget in linux from an terminal. The syntax is as follows:
snmpget -v1 -c public host-ip OID
The OID is an object identifier for every property of you printer reaching from pagecount to toner-cardridge information. If you don't add an OID you'll get the whole list of available OID's. The crux of the matter is although all OID's are standardized the usage of the OID's differ from brand to brand and from printer-model to printer-model. For my HP the following works:
snmpget -v1 -c public 192.168.1.10 iso.3.6.1.2.1.43.17.6.1.5.1.2
and returns
iso.3.6.1.2.1.43.17.6.1.5.1.2 = STRING: "Ready"
the use OID returns the status of the printer for my HP. But if I use the same OID on my Canon I'll get
Error in packet
Reason: (noSuchName) There is no such variable name in this MIB.
Failed object: iso.3.6.1.2.1.43.17.6.1.5.1.2
Therefore it is not even SNMP generically applicable, not mentioning the other protocols which are available.
Considering all these information, the easiest way in my opinition is just check if you can establish the connection to the printer on one of the common printer ports via this code
boolean available = false;
try {
String serverAddress = "192.168.1.10";
Socket s = new Socket(serverAddress, 9100);
s.close();
available = true;
} catch (IOException e) {
available = false;
}
System.out.println("printer available: " + available);
Of course this only works if you already know the printer ip.
If you know your printer IP you could use this code to ping it and check if it's accepting jobs.
import java.io.IOException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.Attribute;
import javax.print.attribute.AttributeSet;
public class PrinterStatus {
public static void main(String[] args) {
PrintService printer = PrintServiceLookup.lookupDefaultPrintService();
AttributeSet att = printer.getAttributes();
String ip = "0.0.0.0"; // IP Address of your printer
boolean check = false;
for (Attribute a : att.toArray()) {
if (att.get(a.getClass()).toString().equalsIgnoreCase("accepting-jobs")){
check = true;
}
}
if (check && runSystemCommand(ip)) System.out.println("Printer ready!");
}
public static boolean runSystemCommand(String ip) {
ProcessBuilder pb = new ProcessBuilder("ping", "-c 1", ip);
Process p;
try {
p = pb.start();
return p.waitFor() == 0 ? true : false;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
}
Of course you need to change this code a little to use it in your case.
Except native accessing, I don't see better solution.
I don't think Java provide any portable API for you to check the status. Based on your requirement, you may want to check the windows api
https://msdn.microsoft.com/en-us/library/windows/desktop/dd162752(v=vs.85).aspx
call OpenPrinter2() then ClosePrinter()
with a little of JNI codes this will be trivial, you may also want to consider https://github.com/java-native-access/jna to make the native accessing part of your code easier
I can't think of an easy way to do this in java (no doubt someone will come up with a single line of code though!). I'm more familiar with C# and, to answer your Windows question, I'd use Microsoft's WMI, specifically Win32_Printer (https://msdn.microsoft.com/en-us/library/aa394363(v=vs.85).aspx). An old CodeProject site shows how to test for an offline printer in C# using Win32_Printer (http://www.codeproject.com/Articles/6069/How-to-Check-if-your-Printer-is-Connected-using-C).
It might work in your case because this guy (http://henryranch.net/software/jwmi-query-windows-wmi-from-java/) has produced jWMI which can query the WMI systems in java. I'm not sure how exhaustive it is, but you'd imagine it could access Win32_Printer. It uses VBScript which it executes within java via cmd.exe and obtains values from stdout so I've no idea about speed, but he also talks about using WMIC.exe which might suit you better.
From his blurb, it looks as if your code could be as straight forward as:
String status = getWMIValue("Select [printer name] from Win32_Printer", "PrinterStatus");
where 7 (0x7) is offline.
or
String status = getWMIValue("Select [printer name] from Win32_Printer", "Availability");
where various states can be discerened (such as 0x7 = power off, or 0x8 = off line, etc.)
The queries also allow a "Select * from" syntax so you could loop through the printers if you didn't have a name.
Win32_Printer has a property (Network as Boolean) that allows you to check whether the printer is local or network, and this (http://blogs.technet.com/b/heyscriptingguy/archive/2006/08/14/how-can-i-list-all-the-printers-on-a-remote-computer.aspx) is an old, but interesting, read on testing for a network printer in VBScript.
These solutions are pretty long in the tooth (I believe MI is the most recent version of WMI, for example), but if that jWMI library can work for you, it might be an answer.
there is java api to native printing facility !! check out this class
java.awt.Desktop
java2s.com e.g
i have used
String WorkOffline = getWMIValue("Select *
from Win32_Printer
where Name='printer_name'", "WorkOffline");
returns True/False
I've tried to solve this issue by referring possible duplicates but none of them seem to be helpful.
Here's a code that I'm using to call Win API methods in Java to get current Windows User Name, and a native Windows MessageBox, but I'm getting UnsatisfiedLinkError that says that my code is unable to locate the native method I'm trying to call.
public class TestNative
{
public static void main(String[] args)
{
long[] buffer= { 128 };
StringBuffer username = new StringBuffer((int)buffer[0]);
GetUserNameA(username,buffer);
System.out.println("Current User : "+username);
MessageBoxA(0,"UserName : "+username,"Box from Java",0);
}
/** #dll.import("ADVAPI32") */
static native void GetUserNameA(StringBuffer username,long[] buffer);
/** #dll.import("USER32") */
private static native int MessageBoxA(int h,String txt,String title,int style);
}
What can be my possible (relatively simple) solution to call native Windows methods in Java. I realize that it will kill the very reason of Java being a cross-platform language, but I need to work on a project for Windows, to be developed in Java.
Thanks.
Update
As David Heffernan suggested, I've tried changing the method signature of MessageBox to MessageBoxA, but still it's not working.
I would guess it's related to the signatures not matching completely.
The GetUserName function takes two parameters: a LPTSTR and a LPDWORD. Java will likely not handle the StringBuffer acting as a TCHAR array for you.
Also, why bother using the Windows API for this? Java can probably get the user's logon name (quick google says: System.getProperty("user.name")), and Swing can make a message box (even one that looks like a Windows one).
Have you tried https://github.com/twall/jna. I have heard good things and its supposed to make jni that bit easier with many conveniences and simplifications.
Do you have a -Djava.library.path VM arg set with the path to your DLL's? Alternatively, you can have it in your system PATH.
The error is because there is no MessageBox. You presumably mean MessageBoxA.
I need to transfer files to my web server for processing and I'd like to do it in a generic way if possible.
I need to be able to transfer files from the following protocols at a minimum (with more to follow eventually):
HTTP
FTP
SCP
I'd really like to be able to send files to SMTP also
So my question, is there a toolkit available that does this already? If so, it must be open source as this is part of an open source project.
If there isn't a toolkit that already does this, what is the best way to structure an interface that will handle most file transfers?
I've thought about something like this:
public interface FileTransfer {
public void connect(URL url, String userid, String password);
public void disconnect();
public void getFile(String sourceFile, File destFile);
public void putFile(File sourceFile, File destFile);
}
And then a Factory that takes the source URL or protocol and instantiates the correct file handler.
Apache commons VFS speaks to this problem, although a quick check didn't show that it will do SCP or SMTP. Commons NET does SMTP, but I don't know that you could get the common interface out of the box. For SCP, here are some possibilities.
The bottom line seems to be to check out the VFS implementation and see if it does something for you, perhaps you can extend it for different protocols. If it isn't appropriate, regarding your interface, you are probably going to want all remote file references to be Strings rather than File objects, and specifically a string representing a URI pointing to the remote location and telling you what protocol to use.
I'm working at a problem very similar to yours, I couldn't find any open source solution so I'm trying to sketch a solution myself. This is what I've come up with.
I think you should represent inputSources and outputSources as different things, like
public interface Input{
abstract InputStream getFileInputStream();
abstract String getStreamId();
}
//You can have differen implementation of this interface (1 for ftp, 1 for local files, 1 for Blob on db etc)
public interface Output{
abstract OutputStream getOutputStream();
abstract String getStreamId();
}
//You can have differen implementation of this interface (1 for ftp, 1 for local files, 1 for mailing the file etc)
Then you should have a Movement to describe which input should go to which output.
class Movement{
String inputId;
String outputId;
}
A class to describe the list of Movement to make.
class MovementDescriptor{
public addMovement(Movement a);
public Movement[] getAllMovements();
}
And then a class to perform the work itself.
class FileMover{
HashMap<String,Input> inputRegistry;
HashMap<String,Output> outputRegistry;
addInputToRegistry(Input a ){
inputRegistry.put(a.getId(),a);
}
addOutputToRegistry(Output a){
outputRegistry.put(a.getId(),a);
}
transferFiles(MovementDescriptor movementDescriptor){
Movement[] movements =movementDescriptor.getAllMovements();
foreach (Movement movement: movements){
//get the input Id
//find it in the registry and retrieve the associated InputStream
//get the output Id
//find it in the registry and retrieve the associated OutputStream
//copy the stream from the input to the output (you may want to use a temporary file in between)
}
}
}
The code that would use this would operate like this:
FileMover fm=new FileMover();
//Register your sources and your destinations
fm.addInputToRegistry(input);
fm.addOutputToRegistry(output)
// each time you have to make a movement create a MovementDescriptor and call
fm.transferFiles(movementDescriptor)
If you would like to exchange by mail our views on the subject, just send me an e mail at (my nickname)#gmail dot com.
NOTE: The code is just a sketch :-)
I think JSch implements SCP, so that covers that one.
please make use of JCraft . Open "sftp" channel and try that.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
read/write to Windows Registry using Java
I need to access Windows registry from Java.. Also I need to copy some registry entries and may have to enter new registry variables using Java..
some one help me please...
I'd recommend the Java Native Access (JNA) library. It's a pretty nice wrapper around JNI. According to this mailing list post, they've already got a contributed wrapper around the native Windows registry function calls.
If you add the JNA libraries to your project, the relevant source you'll want is the Registry.java class. From there, just call methods on that class to investigate the Windows registry.
As a side note, make sure when you use JNA that you use Platform.isXxx() to make sure your code can actually query the registry on the particular platform.
An example will be like this:
import com.ice.jni.registry.*;
public class DeleteEnvironmentVar{
public DeleteEnvironmentVar(String variable, String value) throws Exception {
RegistryKey machine = Registry.getTopLevelKey("HKEY_LOCAL_MACHINE");
RegistryKey environment = machine.openSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", RegistryKey.ACCESS_WRITE);
try {
if ( value == null ) { //Delete the variable in case value is empty
environment.deleteValue(variable);
}
}
catch( NoSuchValueException nsve ) {}
catch( NoSuchKeyException nske ) {}
}
}
The Preferences class is the Java preferred way of writing to the registry. However, I haven't actually used it, so I don't know if it allows access to the entire registry or just a section specific to the JVM or your application. If it doesn't, then it sounds like for your purpose you'll be needing to look at the JNI solutions posited by others here. If it does work, then you have a platform-independent method of storing off your settings if you ever port it.