Executing OS Dependent Commands - java

I have two Java classes that are running commands on the local system. My dev system is a Mac, my QA system is Windows and the Prod system is UNIX. So there are different commands for each one, at the moment I have to go in and comment/uncomment the differences. Both classes are structured the same with executable and command. Here is what I have.
// Linux (QA/Prod)
final String executable = "/user1/Project/Manufacturer/CommandCLI";
// final String executable = "cat"; // Mac Dev
// final String executable = "cmd"; // Windows QA
final String command = "getarray model=" + model + " serialnum=" + serialnum;
// Windows QA(local laptop)
//final String command = "/C c:/Manufacturer/CommandCLI.bat getarray model=" + model + " serialnum=" + serialnum;
//Mac Dev
// final String command = "/TestData/" + computer.getId() + ".xml"
So, as you can see -- I am commenting and uncommenting depending on the environment. One of my main concerns is that I am relying on the model and serialnum variable -- and I don't know if that can somehow be inserted into a property (model and serialnum are given in the method call).
We are using Maven so during "mvn clean package" we are adding the -P flag to specify a properties file.
What is an elegant way to handle this?

I suggest to create 3 different method: one for each os that contains os-specific commands. And you can determine current os using system properties: check this question. And call appropriate method based on this property. Example:
private runOnLinux(int model, int serialNum) { ... }
private runOnWindows(int model, int serialNum) { ... }
private runOnMac(int model, int serialNum) { ... }
// Somewhere in source code...
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("windows")) {
runOnWindows(model, serialNum);
} else if (os.contains("linux") || os.contains("unix")) {
runOnLinux(model, serialNum);
} else {
// Mac!
runOnMac(model, serialNum);
}
Of course I not sure all this checks are correct. Better check answers to the question I mentioned at the beginning. It contains much more useful information.

Related

Quickly find if Java was launched from Windows cmd or Cygwin terminal

I have a Java application that will be used both from the Windows Command Prompt and the Cygwin terminal. The program uses and manipulates file paths. It we be very useful to have a sep variable that would be / when the program is launched from Cygwin but \\ when the program is launched from Windows.
Looking here, I'm not sure it will be possible, but I want to ask.
I will post a small, compilable app that shows the issue in a few minutes. For now, I'll just say that I want a set of functions that something like:
// in main
...
String sep = getSeparatorToUse();
...
// member functions
...
private boolean wasLaunchedFromWinCmd()
{
if (<something-here-that-knows-it-was-cmd-not-cygwin>)
return true;
return false;
}//endof: private boolean wasLaunchedFromWinCmd()
private String getSeparatorToUse()
{
if (wasLaunchedFromWinCmd)
return "\\"
return "/"
}//endof: private String getSeparatorToUse()
Thanks #Raphael_Moita. Those are very useful, and I will likely use them in the Linux version of the app that I will be using. #Luke_Lee, I feel dumb not having realized it. I think you two might have solved my problem while I was getting the compilable code ready. There's still one issue when the program run from a batch script - when it is fed a filename from a find command. I hope what I show will illustrate that.
Examples
All examples are as run from Cygwin.
Works: the way most volunteers use the code, just the filename that's in the same directory as the java code.
$ java FileSeparatorExample pic_4.jpg
Here, something will be done with the file,
C:\Users\bballdave025\Desktop\pic_4.jpg
Works: with relative filepaths and spaces in filenames/file paths
$ java FileSeparatorExample pretty\ pictures/pic\ 1.jpg
Here, something will be done with the file,
C:\Users\me\Desktop\pretty pictures/pic 1.jpg
$ java FileSeparatorExample ../pic_5.jpg
Here, something will be done with the file,
C:\Users\me\Desktop\../pic_5.jpg
DOESN'T WORK. Sometimes, the output of a find command will come with the complete filepath in Cygwin/UNIX format:
$ java FileSeparatorExample /cygdrive/c/David/example/pic.jpg
The file:
C:\Users\bballdave025\Desktop\/cygdrive/c/David/example/pic.jpg
doesn't exist
Compilable Code
I'm just cutting down from my original code, so I'm sorry if it seems too big.
/**********************************
* #file FileSeparatorExample.java
**********************************/
// Import statements
import java.io.File;
import java.io.IOException;
public class FileSeparatorExample
{
// Member variables
private static String sep;
public static void main(String[] args)
{
////****** DOESN'T WORK AS DESIRED ******////
sep = java.io.File.separator;
////** I want **////
// sep = getFileSeparator();
String imageToLoad = null;
boolean argumentExists = ( args != null && args.length != 0 );
if (argumentExists)
{
boolean thereIsExactlyOneArgument = ( args.length == 1 );
if (thereIsExactlyOneArgument)
{
imageToLoad = args[0];
}//endof: if (thereIsExactlyOneArgument)
else
{
// do some other stuff
}
}//endof: if (argumentExists)
String filenamePath = getFilenamePath(imageToLoad);
String filenameFile = getFilenameFile(imageToLoad);
imageToLoad = filenamePath + sep + filenameFile;
File f = new File(imageToLoad);
if (! f.exists())
{
System.err.println("The file:");
System.err.println(imageToLoad);
System.err.println("doesn\'t exist");
System.exit(1);
}//endof: if (! f.exists())
System.out.println("Here, something will be done with the file,");
System.out.println(imageToLoad);
}//endof: main
// member methods
/**
* Separates the filename arg into: full path to directory; bare filename
*/
private static String[] splitFilename(String imageToLoad)
{
String[] fileParts = new String[2];
int indexOfLastSep = imageToLoad.lastIndexOf(sep);
boolean fullFilenameHasSeparator = ( indexOfLastSep != -1 );
if (fullFilenameHasSeparator)
{
fileParts[0] = imageToLoad.substring(0, indexOfLastSep);
fileParts[1] = imageToLoad.substring(indexOfLastSep + 1);
}//endof: if (fullFilenameHasSeparator)
else
{
// Use the user's directory as the path
fileParts[0] = System.getProperty("user.dir");
fileParts[1] = imageToLoad;
}//endof: if/else (fullFilenameHasSeparator)
return fileParts;
}//endof: private static String[] splitFilename(String imageToLoad)
/**
* Gives the full path to the file's directory (from the filename arg)
* but not the bare filename
*/
private static String getFilenamePath(String imageToLoad)
{
String[] fileParts = splitFilename(imageToLoad);
return fileParts[0];
}//endof: private static String getFilenamePath(String imageToLoad)
/**
* Gives the bare filename (no path information)
*/
private static String getFilenameFile(String imageToLoad)
{
String[] fileParts = splitFilename(imageToLoad);
return fileParts[1];
}//endof: private static String getFilenamePath(String imageToLoad)
}//endof: public class FileSeparatorExample
You don't need to know which SO is under your Java. If your goal is to find the correct file separator to use, call this:
java.io.File.separator;
Anyway ... to find out which SO java is running over (not sure how cygwin is detected by this), try:
boolean isWindows = System.getProperty("os.name").startsWith("win");
Here is an answer I've come up with that almost answers my original question. It tries to determine the launcher of the Java code based on the filename argument. A big thanks to #Raphael_Moita and #Luke_Lee, who actually pretty much solved my problem. Their solutions didn't answer the original question, but that's partly because I didn't post the original question completely. As I said, this answer doesn't answer the original question completely. If someone knows the complete solution, please let me know.
My solution was a few methods. As they stand, they only work for my case - Cygwin on Windows. (What they do is tell you if the filename argument for the Java application was consistent with being launched from Windows cmd or not.) I plan on posting a more portable group of methods, i.e. other Operating Systems.
I'm sure there are issues. Please point them out to me.
// in main
...
sep = java.io.File.separator; // Thanks #Luke_Lee
if (args != null && args.length != 0)
sep = getSeparatorToUse(args[0]);
...
// member functions
...
private boolean wasLaunchedFromWinCmd(String firstArg)
{
boolean isWindows = System.getProperty("os.name").startsWith("win");
if (! isWindows) return false; // Thanks #Raphael_Moita
else
{
String launchDir = System.getProperty("user.dir");
String rootOfLaunchDir = getRoot(launchDir);
// This will come back with something like "C:\" or "P:\"
String rootOfArgument = getRoot(firstArg);
if (rootOfArgument.equals("/"))
{
String cygwinBase = "/cygdrive/";
char letterOfRoot = rootOfLaunchDir.charAt(0);
// For, e.g., "/Users/me/Desktop/pic_314.jpg"
if (firstArg.startsWith(cygwinBase))
{
int charsToCut = cygwinBase.length();
letterOfRoot = firstArg.substring(charsToCut,
charsToCut + 1);
}//endof: if (firstArg.startsWith(cygwinBase))
System.out.println("The root directory of your argument will be:");
System.out.println(Character.toUpperCase(letterOfRoot) + ":\\");
System.out.println("In Cygwin, that will be:");
System.out.println(cygwinBase +
Character.toLowerCase(letterOfRoot) + "/");
return false;
// Not always correct, e.g. if someone in Cygwin uses
// $ java FileSeparatorExample "C:\pic_137.jpg"
}//endof: if (rootOfArgument.equals("/"))
return true;
}//endof: if/else (! isWindows)
}//endof: private boolean wasLaunchedFromCmd()
private String getRoot(String fileOrDir)
{
File file = new File(fileOrDir).getAbsoluteFile();
File root = file.getParentFile();
while (root.getParentFile() != null)
root = root.getParentFile();
return root.toString();
}//endof: private String getRoot();
private String getSeparatorToUse(String firstArg)
{
if (wasLaunchedFromWinCmd(firstArg))
return "\\"
return "/"
}//endof: private String getSeparatorToUse(String firstArg)
Parts of this solution are due to #Raphael_Moita and #Luke_Lee, but I also need to reference this SO post. This last one helped with my specific situation, where the files are not all hosted on the C:\ drive.
Note
I won't be accepting mine as the correct solution, because it doesn't answer my original question. I hope it might help someone with answering the original question.

Get OS Information Correctly in Java or C#

I want to get OS name with edition using java or C# as mentioned in below example :
Example : Microsoft Windows 8.1 Enterprise
I have tried below :
In java tried System.getProperty("os.name")
=> It does not provide OS edition
One ways is to get OS name from registry
Getting "ProductName" from \HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion
I also tried SYSTEMINFO command, it provides OS Name. but since it shows output different language. its not possible to check variable name from output.
But I want to find a way other than finding from registry, so that even if in future versions of OS, registry path changes, App should provide correct OS name.
Is there any other reliable way to find OS name with edition ?
Have a look at the apache commons lang library - OS_ARCH, OS_NAME, OS_VERSION
maybe it retrieves what you need. Below is a link to its javadocs:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.4/org/apache/commons/lang/SystemUtils.html
Finally I used below code because I analysed that most probably registry path will not be changed.
private final String STR_OS_NAME_REGISTRY_QUERY = "reg query \"HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\" /v \"ProductName\"";
// Get OS name
objProcessName = Runtime.getRuntime().exec(STR_OS_NAME_REGISTRY_QUERY);
objProcessName.waitFor();
objBufferReader = new BufferedReader(new InputStreamReader(objProcessName.getInputStream()));
lstJavaInfo = new ArrayList<>();
while ((sLine = objBufferReader.readLine()) != null)
{
lstJavaInfo.add(sLine);
}
objProcessName.waitFor();
if(lstJavaInfo.size() < 3)
{
return "-";
}
String[] sarr = lstJavaInfo.get(2).split("\\s+");
for(int nIndex = 3 ; nIndex < sarr.length ; nIndex++)
{
sOSArchitecture = sOSArchitecture + sarr[nIndex] + " ";
}

Elevate Java application while running

A nasty problem popped out with my software. I am making a program that interacts with another existing software (a game). User has reported that he runs the game with administrator privileges and under that circumstances, my program stops working for him.
Short investigation revealed that some people really need to run the game under administrator account and some don't. It would be great if my program would be able to detect this and warn user if the game is running under administrator account:
If the user clicks "Elevate", I'd like to ask windows to elevate the java.exe running my jar file and invoke the typical UAC dialog.
Obviously, this time the question would not be about java updater but JRE
My question is: Is this possible? Can windows elevate my java.exe instance's privilege? Does java have a way to do it? Or can I use command line command?
I want to avoid restarting the program (though it wouldn't probably be such a big deal).
Edit:
If you look in the comments, you'll see that there's no avoiding the restart of an application - process can only start elevated, not become elevated. This kinda shifts the question, unfortunately. Basically, it now sounds more like: "How to restart my application with admin rights?". Unless, of course, there's a trick like two java.exe sharing one jar...
If still of interest: In Windows 7 my JavaElevator works. It elevates a running Java process when used in the main method of the Java application. Simply add -elevate as last program parameter and use the elevator in the main method.
The elevator class:
package test;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
/**
* Elevates a Java process to administrator rights if requested.
*/
public class JavaElevator {
/** The program argument indicating the need of being elevated */
private static final String ELEVATE_ARG = "-elevate";
/**
* If requested, elevates the Java process started with the given arguments to administrator level.
*
* #param args The Java program arguments
* #return The cleaned program arguments
*/
public static String[] elevate(String[] args) {
String[] result = args;
// Check for elevation marker.
boolean elevate = false;
if (args.length > 0) {
elevate = args[args.length - 1].equals(ELEVATE_ARG);
}
if (elevate) {
// Get the command and remove the elevation marker.
String command = System.getProperty("sun.java.command");
command = command.replace(ELEVATE_ARG, "");
// Get class path and default java home.
String classPath = System.getProperty("java.class.path");
String javaHome = System.getProperty("java.home");
String vm = javaHome + "\\bin\\java.exe";
// Check for alternate VM for elevation. Full path to the VM may be passed with: -Delevation.vm=...
if (System.getProperties().contains("elevation.vm")) {
vm = System.getProperty("elevation.vm");
}
String parameters = "-cp " + classPath;
parameters += " " + command;
Shell32.INSTANCE.ShellExecute(null, "runas", vm, parameters, null, 0);
int lastError = Kernel32.INSTANCE.GetLastError();
if (lastError != 0) {
String errorMessage = Kernel32Util.formatMessageFromLastErrorCode(lastError);
errorMessage += "\n vm: " + vm;
errorMessage += "\n parameters: " + parameters;
throw new IllegalStateException("Error performing elevation: " + lastError + ": " + errorMessage);
}
System.exit(0);
}
return result;
}
}
Usage in the main method of the Java application:
public static void main(String[] args) {
String[] args1 = JavaElevator.elevate(args);
if (args1.length > 0) {
// Continue as intended.
...
I know, this is a very basic implementation - sufficient for one of my daily hiccups: Starting an elevated process from Eclipse. But maybe it points someone in some dicrection...
As has been pointed in comments, sadly the Java (or any other process) cannot be elevated while running. While in the case of JWM, it could be theoretically possible to move whole program context from normal user java.exe to elevated one, I don't think it's possible. I hope some day someone will come and tell me I'm wrong.
Surprisingly, even with restart in place, this was a tricky task that took me a while to figure out.
The non java part
First, how do we exactly run a program elevated from command line? There's an answer and you can see it's not simple. But we can break it to this VBS script:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "program name", "command line parameters", "working directory", "runas", 1
Soon, it also turns out that we won't have any success running java.exe from VBS script. In the end, I decided to run a helper batch file. Finally, here (answer to question in the last link) we have a complete set of two scripts which really run the given .jar file elevated. Here's improved version that allows quick testing by drag'n'dropping the Jar file on it:
' Require first command line parameter
if WScript.Arguments.Count = 0 then
MsgBox("Jar file name required.")
WScript.Quit 1
end if
' Get the script location, the directorry where it's running
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
'MsgBox(strFolder)
' Create the object that serves as runnable something
Set UAC = CreateObject("Shell.Application")
' Args:
' path to executable to run
' command line parameters - first parameter of this file, which is the jar file name
' working directory (this doesn't work but I use it nevertheless)
' runas command which invokes elevation
' 0 means do not show the window. Normally, you show the window, but not this console window
' which just blinks and disappears anyway
UAC.ShellExecute "run-normally.bat", WScript.Arguments(0), strFolder, "runas", 0
WScript.Quit 0
The Java part
Java part is more straightforward. What we need to do is to open new process and execute the prepared scripts in it.
/**
* Start this very jar file elevated on Windows. It is strongly recommended to close any existing IO
* before calling this method and avoid writing anything more to files. The new instance of this same
* program will be started and simultaneous write/write or read/write would cause errors.
* #throws FileNotFoundException if the helper vbs script was not found
* #throws IOException if there was another failure inboking VBS script
*/
public void StartWithAdminRights() throws FileNotFoundException, IOException {
//The path to the helper script. This scripts takes 1 argument which is a Jar file full path
File runAsAdmin = new File("run-as-admin.vbs");;
//Our
String jarPath;
//System.out.println("Current relative path is: " + s);
try {
jarPath = "\""+new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getAbsolutePath()+"\"";
} catch (URISyntaxException ex) {
throw new FileNotFoundException("Could not fetch the path to the current jar file. Got this URISyntax exception:"+ex);
}
//If the jar path was created but doesn't contain .jar, we're (most likely) not running from jar
//typically this happens when running the program from IDE
//These 4 lines just serve as a fallback in testing, should be deleted in production
//code and replaced with another FileNotFoundException
if(!jarPath.contains(".jar")) {
Path currentRelativePath = Paths.get("");
jarPath = "\""+currentRelativePath.toAbsolutePath().toString()+"\\AutoClient.jar\"";
}
//Now we check if the path to vbs script exists, if it does we execute it
if(runAsAdmin.exists()) {
String command = "cscript \""+runAsAdmin.getAbsolutePath()+"\" "+jarPath;
System.out.println("Executing '"+command+"'");
//Note that .exec is asynchronous
//After it starts, you must terminate your program ASAP, or you'll have 2 instances running
Runtime.getRuntime().exec(command);
}
else
throw new FileNotFoundException("The VBSScript used for elevation not found at "+runAsAdmin.getAbsolutePath());
}
This is my version. It creates a VBScript script, then executes it. This only works if the program that is being run is in a jar file, so you will have to run your IDE as administrator to actually test your program.
public static void relaunchAsAdmin() throws IOException {
relaunchAsAdmin(ThisClass.class); //Change ThisClass to the class that this method is in
}
public static void relaunchAsAdmin(Class<?> clazz) throws IOException {
if(isCurrentProcessElevated()) {
return;
}
final String dir = System.getProperty("java.io.tmpdir");
final File script = new File(dir, "relaunchAsAdmin" + System.nanoTime() +
".vbs");
try {
script.createNewFile();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(script));
osw.append("Set s=CreateObject(\"Shell.Application\")" + ln + "s.ShellExecute \"" +
System.getProperty("java.home") + "\\bin\\java.exe" + "\",\"-jar \"\"" +
new File(clazz.getProtectionDomain().getCodeSource(
).getLocation().toURI()).getAbsolutePath() + "\"\"\",,\"runas\",0" +
ln + "x=createObject(\"scripting.fileSystemObject\").deleteFile(" +
"WScript.scriptfullname)");
osw.close();
if(System.getenv("processor_architecture").equals("x86")) {
Runtime.getRuntime().exec("C:\\Windows\\System32\\wscript.exe \"" +
script.getAbsolutePath() + "\"");
} else {
Runtime.getRuntime().exec("C:\\Windows\\SysWoW64\\wscript.exe \"" +
script.getAbsolutePath() + "\"");
}
} catch(URISyntaxException e) {
e.printStackTrace();
}
Runtime.getRuntime().exit(0);
}
Note that it is a bit messy. I have been using this method before, so it has been line wrapped to 100 characters (except the comment I wrote for this answer). The
isCurrentProcessElevated()
method will have to be implemented in one way or another. You could try using JNI, or you could use a pure Java method, such as writing in the Program Files or System32 directory and seeing if it failed.
Obviously, this solution will only work on Windows. I never needed to elevate on Linux or Mac systems (mainly because I don't have any Mac systems, and I don't use Linux - I just play with it).

Can Java launch the Windows UAC?

As the title says, I'm wondering if it is possible for a program written in Java (and only java) to relaunch himself (preferably a .jar) with administrator privileges, showing in the way the native Windows UAC (in order to make it more trustable for the user), i did my homework and found out that it is possible to accomplish this using bridges between c++ and java, but i would really like to do this as a pure java project.
P.S: In the remote case that this result to be impossible, can someone show me the "easy" way to do this using another language (i mean, I've found tutorials, but they are to complicated for something I think it should not be that complicated).
P.S2: In case it is possible to accomplish this, would it work, on other platforms (OS X, Linux)
It cannot be done in pure java.
Best bet would be to write this to a file:
#echo Set objShell = CreateObject("Shell.Application") > %temp%\sudo.tmp.vbs
#echo args = Right("%*", (Len("%*") - Len("%1"))) >> %temp%\sudo.tmp.vbs
#echo objShell.ShellExecute "%1", args, "", "runas" >> %temp%\sudo.tmp.vbs
#cscript %temp%\sudo.tmp.vbs
and save it as something.bat in Windows temp directory (as we have access to this).
You would then execute this from your application using Runtime or ProcessBuilder and exit your application (System.exit(0);).
You should add an immediate start up check to your application that checks if the program has elevation, if it has proceed if not re-run the batch and exit.
Here is an example I made (this must be run when compiled as a Jar or it wont work):
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
*
* #author David
*/
public class UacTest {
public static String jarName = "UacTest.jar", batName = "elevate.bat";
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
if (checkForUac()) {//uac is on
JOptionPane.showMessageDialog(null, "I am not elevated");
//attempt elevation
new UacTest().elevate();
System.exit(0);
} else {//uac is not on
//if we get here we are elevated
JOptionPane.showMessageDialog(null, "I am elevated");
}
}
private static boolean checkForUac() {
File dummyFile = new File("c:/aaa.txt");
dummyFile.deleteOnExit();
try {
//attempt to craete file in c:/
try (FileWriter fw = new FileWriter(dummyFile, true)) {
}
} catch (IOException ex) {//we cannot UAC muts be on
//ex.printStackTrace();
return true;
}
return false;
}
private void elevate() {
//create batch file in temporary directory as we have access to it regardless of UAC on or off
File file = new File(System.getProperty("java.io.tmpdir") + "/" + batName);
file.deleteOnExit();
createBatchFile(file);
runBatchFile();
}
private String getJarLocation() {
return getClass().getProtectionDomain().getCodeSource().getLocation().getPath().substring(1);
}
private void runBatchFile() {
//JOptionPane.showMessageDialog(null, getJarLocation());
Runtime runtime = Runtime.getRuntime();
String[] cmd = new String[]{"cmd.exe", "/C",
System.getProperty("java.io.tmpdir") + "/" + batName + " java -jar " + getJarLocation()};
try {
Process proc = runtime.exec(cmd);
//proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void createBatchFile(File file) {
try {
try (FileWriter fw = new FileWriter(file, true)) {
fw.write(
"#echo Set objShell = CreateObject(\"Shell.Application\") > %temp%\\sudo.tmp.vbs\r\n"
+ "#echo args = Right(\"%*\", (Len(\"%*\") - Len(\"%1\"))) >> %temp%\\sudo.tmp.vbs\r\n"
+ "#echo objShell.ShellExecute \"%1\", args, \"\", \"runas\" >> %temp%\\sudo.tmp.vbs\r\n"
+ "#cscript %temp%\\sudo.tmp.vbs\r\n"
+ "del /f %temp%\\sudo.tmp.vbs\r\n");
}
} catch (IOException ex) {
//ex.printStackTrace();
}
}
}
Use a batch file and the runas command.
I doubt "only Java". At best you would have to have a JNI wrapper around the MSFT module. Unless just invoking the exe using ProcessBuilder counts as "only Java" -- your code to bring up the user console would be only Java but not what it invokes. IOW, Win does not come with a Java API
To relaunch your application elevated, you have to call ShellExecute or ShellExecuteEx function from Windows API and use runas verb.
You can use these API in pure Java with JNA library.
To relaunch yourself, you would have to know the full path to java.exe or javaw.exe, the command-line parameters (class path, if any, and the path to your jar). Obviously you can get this information by using Windows API.
What do you mean by remote case?
You cannot start remote elevated process this way.
You can re-launch your application elevated from a network share. Yet it won't work with mapped drives: after elevation there's no access to user's mapped drives.
No, this can't work on other platforms. UAC is a Windows feature. It's similar to sudo in Linux in some ways, so for Linux you can use sudo $pathtojava/java.exe <yourparameters>. However this won't work nicely if your application is not started from a console. Window Managers usually have wrappers which prompt for password in a GUI dialog.
Just do this with Hackaprofaw (v29). Also it was released in 2002 and started development in 1997 soooooo ye. in 2021 its on version 29.10.7 but-
if raw ram = 0
disable "featureII" program = "JAVA(math = any)"
run on "Hackaprofaw (math = v29(x))
when "featureII" disabled
end

Java Cross-Platform OS detection to declare file path location

I currently comprise the following code which fails to compile. The else if statement reports that ';' expected. I don't understand why I can't use a else if for this scenario?
public class FileConfiguration {
private String checkOs() {
String path = "";
if (System.getProperty("os.name").startsWith("Windows")) {
// includes: Windows 2000, Windows 95, Windows 98, Windows NT, Windows Vista, Windows XP
path = "C://Users//...";
}
elseif (System.getProperty("os.name").startsWith("Mac")) {
path = "///Users//...";
}
return path;
}
// declare paths for file source and destination
String destinationPath = path;
String sourcePath = path;
It would be better if you were to use user.name and user.home. You can also get the separator using file.separator. Check this out. Those properties will really help you do this more cleanly without checking the OS.
Then there's also the matter of you needing to change to using else if, not elseif...
elseif does not exist in java. You must use else if as:
if (a) {
// code
} else if (b) {
// code
}
There is no elseif keyword in java.
You should say else if (pay attention on the space)

Categories

Resources