Getting the native word size from Java VM - java

Is there an easy way to get the native sizeof(int) from the Java VM running on a particular platform? The value I want is not Integer.SIZE, in particular - the size of a Java int, but rather what you'd get from sizeof(int) in C on the platform.
I need this because I'm using a particular library that reads and writes binary files, and trying to parse those files, whose interpretation depends in a particular way on the size of the machine int. I'd like it to be portable.
I get the impression that including JNA will give me that capability - but I'd rather not have to include a native library dependency (again, portability), and I don't want to play nasty games like the only solution I could come up with offhand - allocating many direct int buffers and looking at management/memory metrics before and after. That's a hack and not reliable...

A comment suggested a system property so I looked at the list of those - it turns out there is one that gives this value:
System.getProperty("sun.arch.data.model")

Related

Using Java can I programmatically undelete a file under Windows?

I'm successfully using Desktop.getDesktop().moveToTrash(File) under MacOS to delete files and then retrieve them from the Trash folder. I'd like to do the same under Windows. But I don't see a native Java way to access to Recycle Bin so I can undelete them.
Under MacOS I simply rename files from the Trash folder back to where they were. Is there a way I can do that with the Windows Recycle Bin? Or do something similar?
There's nothing in the core API. You have a bunch of options.
But first.. there's trash, and delete
"move to trash" means the file is literally undestroyable - as long as it is remains in the trashcan it remains on your disk. Said differently, if you have a completely filled up harddisk, trash 100GB worth of files, that disk is... still completely filled up. Possibly certain OSes have a 'bot' that runs when needed or on a schedule that truly deletes files in the trashcan that fit certain rules (such as 'deleted more than 30 days ago').
"Actually delete" means the disk space is now available - if you have a full disk, actually delete 100GB worth of files, then there's now 100GB available, but those files are STILL on disk!! - the only thing that 'delete' does, is flag the space. It doesn't overwrite the actual bits on disk with zeroes or random data or whatnot. Further use of this disk will eventually mean some other file is written 'over' the deleted file at which point it truly becomes entirely unrecoverable, but if you have some extremely sensitive data, you delete the files, then you toss the computer in the garbage bin, anybody who gets their hands on that machine can trivially recover your data. Because what 'delete' does is set a flag "I am deleted", nothing more. All you need to do to undo this, is to unset the flag.
The reason I mention this, is because you used the term 'undelete' in your question. Which usually means something else.
Verb
UnVerb
Action
Trash
Recover, Untrash, Restore, Put Back
Disk space remains unavailable. File visible in OS trash can tool
Delete
Undelete
Disk space is now available; data is still on disk but could be overwritten at any time.
Wipe
N/A
Data is overwritten with zeroes. Some wiping tools overwrite 7 times with random data to be really sure1
Trim
N/A
Pulse all cells on an SSD2 - intended to make data unrecoverable, applies only to SSDs
[1] This fights largely hypothetical trickery where you recover data by scanning for minute magnetic differences in potential. If it's doable at all it requires equipment that costs multiple millions. Still, if you're paranoid, you write random data, and repeat that procedure 7 to 30 times.
[2] SSDs are 'weird' in that they are overprovisioned: They can store more data than the label says. It's because SSDs work in 'cells' and there's a limit to how often a cell can be rewritten. Eventually a cell is near death (it's clear it's only got a few rewrites left in it), at which point the data is copied to an unused cell, and the near-death cell is marked off as no longer usable. The SSD is a 'fake harddrive', exposing itself as a simple contiguous block of writable and addressable space. It's like a mini computer, and will map write ranges to available cells. As a consequence, using basic OS/kernel driver calls to tell the SSD to write 7x random data over a given range of bits does not actually work, in that it is possible that there's a cell with the file data that's been marked as not to be used, and it won't be wiped. While somewhat hard to do, you can send special commands, so-called TRIM commands, to most SSDs to explicitly tell them to pulse-clear all cells on the entire drive, even the ones that have been marked as near-death. This low-level call to the SSD firmware is the only way to securely delete anything off of an SSD. Naturally, the whole point of this exercise is that you can't undo it.
So, to be clear, the one and only thing on this list that is meaningfully doable without writing extremely complex software that scans the raw disk out, byte for byte (which is a tool you should not be writing in java, as you'll be programming a lot towards the OS/arch which java is not good at), is the Untrash part: Undoing the 'trash' action.
Not available in basic java
... unfortunately even that is not available normally. There's an API to tell the OS to 'trash' a file, there is no API call to untrash it. That means you'll have to code an implementation for untrashing for each and every OS you want to support. On mac, you could handroll it by moving files out of ~/.Trash. On windows its a little trickier.
One "simple" (heh) way is to use JNI to write C code (targeting the windows API, to be compiled on windows with windows oriented C tools) that does the job, and then use JNI to call this C function (compiled to a .dll) on windows specifically. You can ship the DLL and simply not use it on non-windows OSes. You will have to compile this DLL once for every arch you want to target (presumably, x64, possibly x86 and aarch64 (ARM)). This is all highly complicated and requires some knowledge about how to write fairly low-level windows code.
Use command line tools
You can invoke command line tools. For example, windows has fsutil which can be used to make hard links. I think you can do it - C:\$Recycle.bin is the path, more or less. Where C is itself already a little tricky to attempt to find from java (you can have multiple disks in a system, so do you just scan for C:, D:, etc? But if the machine still has a CD-ROM drive that'll make it spin up which surely you didn't want. You can ask windows about what kind of disk a letter is, but this again requires JNI, it's not baked into java).
You could write most of the untrash functionality in a powershell script and then simply use java's ProcessBuilder to run it, and have it do the bulk of the work.
Use C:\$Recycle.bin
You can try accessing Paths.get("C:\$Recycle.bin") and see what happens. Presumably, you can just move files out of there. But note that each file has associated with it, knowledge of where it used to be. The files still have their extension but their names are mangled, containing only the drive letter they came from + a number. There's a separate mapping file that tells you where the file was deleted from and what its name was. You will have to open this mapping file and parse through it. You'll have to search the web to figure out what the format of this mapping file is. You'll have to take care not to corrupt it, and probably to remove the file you just recovered from it (without corrupting it).
Note that files in the recycle bin have all sorts of flags set, such as the system flag. You may have to write it all in powershell or batch scripts, and start those from java instead, to e.g. run ATTRIB.EXE to change properties first. Hopefully you can do it with the java.nio.file API which exposes some abilities to interact with windows-specific file flag stuff.
Build your own trashcan
In general it's a bad idea to use java to write highly-OS-specific tooling. You can do it, but it'll hurt the entire time. The designers of java didn't make it for this (Project Panama is trying to fix this, but it's not in JDK18 and won't be in 19 either, it's a few years off – and it wasn't really designed for this kind of thing either), and your average java coder wouldn't use it for this, so that means: Few to no libraries, and hard to find support.
Hence, it's a better idea to consider desktop java apps to do things more in its own way than your average desktop tool. Which can include 'having its own trashcan'. Let's say you have a code editor written in java, and it has a 'delete' feature. You're free to implement 'delete' by moving files to a trashcan dir you made, where you track (Via a DB or shadow files) when the delete occurred, who did it, and where the file came from. Then you build code that can move it back, and code that 'empties the trash', possibly on a schedule.
You can do all that simply with Files.move.

Is there any way to change the system volume with a Java Program?

I wrote a Java program to change the volume of an audio clip (a .wav) with a command line argument, but that only seems to be somewhat of a "soft" control in that it doesnt actually change the master volume of the actual machine its running on and I have to manually press the increase or decrease volume buttons on my latop to change it further. Is Java capable of changing the actual computer's volume? If so, how?
I should add, Im on Windows 10.
A crufty, platform-dependent solution:
Download NirCmd.
Ship the exe which as far as I know is 'dependency free' (no installation needed), inside the jar.
To change the volume, unpack this exe from your jar to a temp dir (this is a tad security-wise tricky).
Run it, using ProcessBuilder. It can change the system volume.
It's not great, but, it should work.
NB: Please check the licensing conditions of NirCmd; this may not be quite acceptable, you may have to show that license as part of your app. Dont take legal advice from a stack overflow answer.
I was ready to let this question be until I came across the word impossible. Before giving up, maybe take a look at the JNA library. This library is built specifically for accessing native code.
JNA provides Java programs easy access to native shared libraries
without writing anything but Java code - no JNI or native code is
required. This functionality is comparable to Windows' Platform/Invoke
and Python's ctypes.
JNA allows you to call directly into native functions using natural
Java method invocation.
There is an active forum listed in the git README. If nothing else, you can ask/explore whether this issue is one that fits within the capabilities of the library.
But I have to admit, even if possible, it seems like it would require considerable effort as well as being dubious in concept: the setting of the computer hardware's volume is properly in the hands of the computer operator.
Hopefully Windows 11 will have a feature that allows you to change the master volume. What about trying to get the program to trigger the existing software in Windows 10 that changes the volume when you press the keys?
JavaScript --> Binary Code In Windows 10 --> Master Volume Bypass

In C++ or Java is there a way to get the CPU usage?

I'd like to write a little program just to display the CPU usage as a percent, like the task manager does. I know intermediate C++ and Java. Is there a way to do this with either language? If so, perhaps a short example? I saw some page of a C++ command, but I couldn't make heads or tails of it.
I'm using Windows 7 on one computer and XP on the other. As for the multiple core response, I simply want to display the CPU usage percent as the task manager does, even with a multiple core processor.
double sysLoad = ManagementFactory.
getOperatingSystemMXBean().
getSystemLoadAverage();
does not work on every platform,
returns an average load of the past one minute
EDIT:
Recently found this one
http://sellmic.com/blog/2011/07/21/hidden-java-7-features-cpu-load-monitoring/
In Java 7 you can use com.sun.management package to get process load or system load.
usage:
OperatingSystemMXBean osBean = ManagementFactory
.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class);
// What % CPU load this current JVM is taking, from 0.0-1.0
System.out.println(osBean.getProcessCpuLoad());
// What % load the overall system is at, from 0.0-1.0
System.out.println(osBean.getSystemCpuLoad());
there are some system call functions provided in "windows.h", such as GetProcessorInfo(), CallNTPowerInformation(), GetTickCount(), QueryPerformanceFrequency(), QueryPerformanceCounter() and so on. You can google them, or find them in MSDN. I hope this answer can help you.
The answer is going to be platform specific, and differs between the Java and C++ cases. At some level you need to interface with OS specific APIs to extract the statistics. There are four possible approaches:
Call an appropriate external system monitoring command (system specific) and "scrape" the output of the command. You can do this from Java or C++.
In C++ (or using JNI / JNA in Java ... if you really have to), make calls on the OS-specific native APIs that provide the information used by the external system monitoring.
In Java, use some existing 3rd-party library that deals with the system specific JNI/JNA stuff. Possible examples include JavaSysMon and SIGAR ... though I can't make specific recommendations.
You could use the Java monitoring APIs ... but they don't provide enough information. You can get information about this processes resource usage, and the overall load average, but you can't get information about other processes.
Now the problem with all of the above (except, possibly, the last one) is that porting to a new platform requires work.
CPU usage is an operating system property, not a language property. The way to retrieve it would be specific to the OS you're using (which you fail to identify).
In addition, "CPU usage" is a very nebulous term anymore, with multiple cores, et al.
In Java you can do it using JavaSysMon
Assuming you're using Windows system, you can use Windows Management Instrumentation (WMI). It's powerful once you get it working. I never did it using Java. Of course, it's easier with C# .NET.
A good link is WMI info
If you try this, please tell me. I might be interested in helping you since this is also my interest.
IF you are using the Linux system, consider using shell scripting, like bash. The reason is shell scripting is powerful for operating system calls, like getting process ID and usage (pid command). And IT technicians are more comfortable with bash scripts than Java or C++.

Is it possible to get harddisc size using php or java?

I want to detect the harddisc size of my computer and if possible the the partitions informations(partition size, free memory, used etc).Is it possible in php/java?
For PHP use disk_total_space() function.
For me, getting the total disk space for java is complicated. I haven't tried it.
For Java, finding free disk space used to be a long-standing feature request. It was finally implemented for Java 6 aka Mustang.
You can now use File.getFreeSpace() and getUsableSpace(). See e.g. http://www.javalobby.org/java/forums/t19527.html for explanations and examples.
For Java versions prior to Java 6, there is no (easy, cross-platform) solution, just some ugly hacks.
Note: This will give you the free space on the partition of the File instance. I don't know of any way to get a list of all partitions, at least not in pure Java. At any rate, this is a highly system-specific information, so probably not feasible in pure Java.
Maybe you could describe your problem in more detail, then we can possibly help.

How can I profile Java memory usage without an instumented JVM (Java 1.1.8)

I am currently trying to determine the cause of high memory usage in a Java application running on an exotic platform where I know of no instrumented JVM.
I have the source to the application, and can make changes to the source for the purposes of testing.
How can I debug memory usage under these conditions?
If more info is needed, I'll be happy to provide. I'm just a little lost trying to use such an old jvm without much tooling to speak of.
If I were in your shoes I would approach it with:
Find the functional areas you know
need attention.
Make backup copy of code
Start inserting print statements
with start and end times
See what takes a lot of time and
narrow it down.
For Java 5 and later this can be done using Java agents. For earlier versions - including 1.1.8 - you must load native agents to do this. If you cannot instrument your code, you must do the work needed yourself.
One approach to get most of the way is to use a Java 1.1 compatible version of log4j which allows you to essentially write out strings prepended with a timestamp. This can then be massaged afterwards into extracting answers to whatever you want to know.
If you need memory profiling - and I'd recommend against this - you could start serializing objects out to disk, then measuring disk size as a rough estimate of memory size.
If you really want to dig into where you're usually not supposed to be, try the sun.misc package, although I don't know how much of that was around in 1.1.x.

Categories

Resources