I've done this before using C# (here), it worked perfectly for me, but now I intend to program it in Java.
I've searched through Oracle's tutorials and documentations for anything related, but no success.
Please, I have no idea of how I accomplish this.
Thanks in advance for the attention!
Expanding upon #Art_Rebels' answer; To use SIGAR it requires you add the the relevant .jars to your project and the relevant library which is dependent upon on your Operating System.
If you require help setting up SIGAR there are many posts which already exist on Stack Overflow and just a Google away, regardless if you require help just ask!
Once you have SIGAR correctly configured you can use the following snippet to display the disk usage for your C: drive
import org.hyperic.sigar.Sigar;
public class HardDriveUsage
{
public static void main( String[] args ) throws Exception
{
Sigar sigar = new Sigar();
while (true)
{
Thread.sleep( 1000 );
System.out.println( sigar.getDiskUsage("C:") );
}
}
}
I think that the best solution is using SIGAR API https://support.hyperic.com/display/SIGAR/Home . It works for majority OS.
Related
i have a SAP-DLL to enable communication between a Programming interface and the SAP Programm.
I have following example Code for c# in combination with the dll-File:
var loggerService = LoggerService.GetLoggerService("FileLogger");
var itasProxy = SapProxyFactory.CreateSapProxy(SapSystem.Example, loggerService, "Example_User", StringExtension.CreateSecureString("Example_Password"));
var funcResult = sapProxy.SearchSapAddress(clientNo);
if (funcResult.Successfull)
{
funcResult.ReturnValue = withFormatting
? AddressFormatter.SplitStreetHouseNo(funcResult.ReturnValue)
: funcResult.ReturnValue;
}
Now i want the same functionality to be transferred to java. I have absolutely no clue how to do that. I tried the following with Loggerservice as a starter, but it doesn't work:
public class SAPConnector {
public static void main(String[] args) {
// TODO Auto-generated method stub
connectSAP();
}
public void connectSAP()
{
System.load("C://Temp//SapConnector.dll");
Object loggerService = getLoggerService("FileLogger");
}
public native Object getLoggerService(String lcLogger);
}
i just need some kind of information how to call the Functions from the dll or an example how to transfer the C# Code to working Code in Java.
Greetings,
Kevin
DLL is Microsoft format. Java is cross-platform, thus can't acknowledge anything operating-system specific, such as DLL.
One way around that is to use JNI (Java Native Interface), but that's usually not a good solution, as it makes your program platform-dependent.
Instead, I would look for a JAR from SAP, that provides a similar interface.
Maybe something along SAP JCO.
You can see some actual code examples using JCO here, and some technical information on step-by-step download and configure here.
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 have been doing some research, and for the life of me, I cannot find any documentation on how to use the android dropbox SDK. I have authenticated the user, but now I cannot figure out how the get the metadata (file entries) of a folder. I have looked at the Web docs, but the arguments in java are turned around, flipped over, and then some.
In objective-c, the methods are straight forward, and I understand what is going on. Must I port the code from objective-c to java?
As far as I can tell as of Sep 20, 2011, Dropbox still hasn't put the Android SDK documentation. Here are some workarounds:
This guy created his own version based on the official Dropbox SDK. https://github.com/mlamina/DropboxSDK-for-Android
This forum post gives some tips. In particular, they suggest looking at the Python documentation. http://forums.dropbox.com/topic.php?id=25318
[EDIT by anotheranon user]
My friend stumbled upon this official documentation from Dropbox. Don't even know how he found it. Since this thread is also where I gave up I would like to share!
You should be to find your answer here: https://www.dropbox.com/developers. Looks like the SDK is undocumented.
Try making the calls to the API directly.
In the SDK (DropboxSample), this will list the files in the Public folder of the user account:
In DropboxSample.java add:
public void displayFiles(DropboxAPI.Account account) {
if (account != null) {
DropboxAPI.Entry dbe = api.metadata("dropbox", "/Public", 10000, null, true);
List<Entry> contents = dbe.contents;
if (contents != null) {
for (Entry ent:contents) {
Toast.makeText(this, ent.fileName(), Toast.LENGTH_SHORT).show();
}
}
}
}
In LoginAsyncTask.java add:
mDropboxSample.displayFiles(mAccount);
below mDropboxSample.displayAccountInfo(mAccount);
Due to checked exceptions, we can have some problems in production having all exceptions caught in the right place and logged correctly.
I wonder if there is some opensource tool to help with auditing these problems.
For example, is there some AOP tool that would intercept all exceptions thrown and see if they are re-thrown, wrapped or logged? This would help identify the bad catches.
If you've decided that you would like to take the AOP route, the Spring Framework provides an easy to use AOP framework. Essentially, like much of Spring, you would use a combination of a xml config file and some java code to define the AOP functionality you are looking for.
In your case, I believe you would be looking to define an 'After Throwing Advice', in which you would of course have access to the exception thrown.
A good place to start in terms of documentation is the AOP Chapter in the Spring docs:
http://static.springsource.org/spring/docs/2.5.x/reference/aop.html
Oh, and I believe all Spring projects are open source as well =)
I know the question asks for an open source solution. I don't know of one but if the option is there then DynaTrace does exactly what you want. Good luck on your search.
There are tools such as FindBugs, PMD and Checkstyle which can identify some common Exception handling issues. I'm never seen a tool that specifically analyses your exception handling, if anyone knows I'll be interested!
I had this exact question, and I attempted to write something myself, and due to AOP nested proxying and lack of ability to use instrumenation / weaving, I gave up and just did a wide find and replace
One of he tools I did find back then for was AppSight by BMC software, but it's high cost was an issue
IntelliJ's Inspector can check code for many problems as you write it:
http://www.jetbrains.com/idea/documentation/inspections.jsp
But your problem sounds like it's more about education than technology. You need to educate your team on what proper exception handling means, when it should be done, etc. Tools will help, but not putting them into the code is the first place is better.
We use Spring aspects for our production systems to do logging, tracing, performance calculations, etc. Before, after, and exception advice work wonders - they keep the code in one place and give declarative flexibility as to where they are applied.
Just one caution: aspects aren't free. They add cost to each method you apply them to, so don't just pile them on. Moderation in all things is the key.
I didn't though about that yet but one solution, if you do not need to detect exceptions thrown on production envirionment, is to attach to your Java application a custom debugger that can be triggered whenever an exception is raised.
This french blog article talk about how to do it:
http://blog.xebia.fr/2011/12/12/legacy-code-gestion-des-exceptions-avec-jpda/
Here is the code:
Run with debug:
Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
Connect to the JVM:
public static VirtualMachine connect(String port) throws IOException, IllegalConnectorArgumentsException {
AttachingConnector connector = null;
VirtualMachineManager vmManager = Bootstrap.virtualMachineManager();
for (Connector aconnector : vmManager.allConnectors()) {
if ("com.sun.jdi.SocketAttach".equals(aconnector.name())) {
connector = (AttachingConnector) aconnector;
break;
}
}
Map<String, Connector.Argument> args = connector.defaultArguments();
Connector.Argument pidArgument = args.get("port");
pidArgument.setValue(port);
return connector.attach(args);
}
Create your breakpoints. Exemple:
public static void createExceptionBreakPoint(VirtualMachine vm) {
EventRequestManager erm = vm.eventRequestManager();
List<ReferenceType> referenceTypes = vm.classesByName("java.lang.Throwable");
for (ReferenceType refType : referenceTypes){
ExceptionRequest exceptionRequest = erm.createExceptionRequest(refType, true, true);
exceptionRequest.setEnabled(true);
}
}
And then handle the exceptions:
public static void handleExceptionEvent(ExceptionEvent exceptionEvent) throws Exception {
ObjectReference remoteException = exceptionEvent.exception();
ThreadReference thread = exceptionEvent.thread();
List<Value> paramList = new ArrayList<Value>(1);
paramList.add(dumpFileName);
//crer un printStream dans la JVM cible
ObjectReference printStreamRef = printStreamClassType.newInstance(thread, printStreamConstructor, paramList,
ObjectReference.INVOKE_SINGLE_THREADED);
ReferenceType remoteType = remoteException.referenceType();
Method printStackTrace = (Method) remoteType.methodsByName("printStackTrace").get(1);
paramList.clear();
paramList.add(printStreamRef);
remoteException.invokeMethod(thread, printStackTrace, paramList, ObjectReference.INVOKE_SINGLE_THREADED);
Scanner scanner = new Scanner(new File(dumpFileName.value()));
while (scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
}
A bit heavy but it works, now how to catch the exceptions that are logged and the others?
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.