Exe - Embed JRE to a Standalone EXE? [duplicate] - java

I'm trying to install the most current platform (x64 or x86) appropriate Java Runtime Environment via Inno Setup (along with another application). I've found some script examples for how to detect the version and install if correct and adapted them to my needs but I keep running into this:
Unable to open file "path\to\JREInstall.exe":
CreateProcess failed: Code 5:
Access Is Denied
This is the code strictly responsible for installing the JRE:
[Setup]
AppName="JRE Setup"
AppVersion=0.1
DefaultDirName="JRE Setup"
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
[Files]
Source: "jre-8u11-windows-x64.exe"; DestDir: "{tmp}\JREInstall.exe"; \
Check: IsWin64 AND InstallJava();
Source: "jre-8u11-windows-i586.exe"; DestDir: "{tmp}\JREInstall.exe"; \
Check: (NOT IsWin64) AND InstallJava();
[Run]
Filename: "{tmp}\JREInstall.exe"; Parameters: "/s"; \
Flags: nowait postinstall runhidden runascurrentuser; Check: InstallJava()
[Code]
procedure DecodeVersion(verstr: String; var verint: array of Integer);
var
i,p: Integer; s: string;
begin
{ initialize array }
verint := [0,0,0,0];
i := 0;
while ((Length(verstr) > 0) and (i < 4)) do
begin
p := pos ('.', verstr);
if p > 0 then
begin
if p = 1 then s:= '0' else s:= Copy (verstr, 1, p - 1);
verint[i] := StrToInt(s);
i := i + 1;
verstr := Copy (verstr, p+1, Length(verstr));
end
else
begin
verint[i] := StrToInt (verstr);
verstr := '';
end;
end;
end;
function CompareVersion (ver1, ver2: String) : Integer;
var
verint1, verint2: array of Integer;
i: integer;
begin
SetArrayLength (verint1, 4);
DecodeVersion (ver1, verint1);
SetArrayLength (verint2, 4);
DecodeVersion (ver2, verint2);
Result := 0; i := 0;
while ((Result = 0) and ( i < 4 )) do
begin
if verint1[i] > verint2[i] then
Result := 1
else
if verint1[i] < verint2[i] then
Result := -1
else
Result := 0;
i := i + 1;
end;
end;
function InstallJava() : Boolean;
var
ErrCode: Integer;
JVer: String;
InstallJ: Boolean;
begin
RegQueryStringValue(
HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment', 'CurrentVersion', JVer);
InstallJ := true;
if Length( JVer ) > 0 then
begin
if CompareVersion(JVer, '1.8') >= 0 then
begin
InstallJ := false;
end;
end;
Result := InstallJ;
end;
In the full setup script the same message continues to come up.
How can I get the JRE Setup to run from this scripted setup file?

I was able to figure out the issue:
Evidently I was mistaken in my use of these lines:
Source: "jre-8u11-windows-x64.exe"; DestDir: "{tmp}\JREInstall.exe"; Check: IsWin64 AND InstallJava();
Source: "jre-8u11-windows-i586.exe"; DestDir: "{tmp}\JREInstall.exe"; Check: (NOT IsWin64) AND InstallJava();
and they should have been in place like so:
Source: "jre-8u11-windows-x64.exe"; DestDir: "{tmp}"; DestName: "JREInstall.exe"; Check: IsWin64 AND InstallJava();
Source: "jre-8u11-windows-i586.exe"; DestDir: "{tmp}"; DestName: "JREInstall.exe"; Check: (NOT IsWin64) AND InstallJava();
That seems to have solved the problem.
Also this line I was mistaken in:
Filename: "{tmp}\JREInstall.exe"; Parameters: "/s"; Flags: nowait postinstall runhidden runascurrentuser; Check: InstallJava()
It should have been:
Filename: "{tmp}\JREInstall.exe"; Parameters: "/s"; Flags: nowait runhidden runascurrentuser; Check: InstallJava()
This is the best solution my limited experience with this particular tool is able to come up with. I will look into the PrepareToInstall option when I have a chance but this works for now.

According to the initial question, "How do I install a JRE from an Inno script?", and taking as a starting solution the best proposed one, I propose a solution that I think works more coherently.
I understand that the user wants to install a JRE for their application if the target computer does not have installed a Java runtime environment or its version is lower than the required one. Ok, what I propose is to use the AfterInstall parameter and reorder a bit the distribution files in a different way.
We will first sort the files in the [Files] section in another way, putting first the redist install files.
Source: "redist\jre-8u121-windows-i586.exe"; DestDir: "{tmp}"; DestName: "JREInstaller.exe";\
Flags: deleteafterinstall; AfterInstall: RunJavaInstaller(); \
Check: (NOT IsWin64) AND InstallJava();
Source: "redist\jre-8u121-windows-x64.exe"; DestDir: "{tmp}"; DestName: "JREInstaller.exe"; \
Flags: deleteafterinstall; AfterInstall: RunJavaInstaller(); \
Check: IsWin64 AND InstallJava();
Source: "Myprog.exe"; DestDir: "{app}"; Flags: ignoreversion
The next step we must do is to modify the section [Run] as follows.
[Run]
Filename: "{app}\{#MyAppExeName}"; \
Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; \
Flags: nowait postinstall skipifsilent
And last but not least, we implemented in the [Code] section the RunJavaInstaller() procedure as follows:
[Code]
procedure RunJavaInstaller();
var
StatusText: string;
ResultCode: Integer;
Path, Parameters: string;
begin
Path := '{tmp}\JREInstaller.exe';
{ http://docs.oracle.com/javase/8/docs/technotes/guides/install/config.html#table_config_file_options }
Parameters := '/s INSTALL_SILENT=Enable REBOOT=Disable SPONSORS=Disable REMOVEOUTOFDATEJRES=1';
StatusText:= WizardForm.StatusLabel.Caption;
WizardForm.StatusLabel.Caption:='Installing the java runtime environment. Wait a moment ...';
WizardForm.ProgressGauge.Style := npbstMarquee;
try
if not Exec(ExpandConstant(Path), Parameters, '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then
begin
{ we inform the user we couldn't install the JRE }
MsgBox('Java runtime environment install failed with error ' + IntToStr(ResultCode) +
'. Try installing it manually and try again to install MyProg.', mbError, MB_OK);
end;
finally
WizardForm.StatusLabel.Caption := StatusText;
WizardForm.ProgressGauge.Style := npbstNormal;
end;
end;
You may need to replace the Enabled value with 1 and the Disabled value with 0 if the Java runtime installer is not working properly. I have not experienced any problem doing it this way. Anyways, in the code you have a comment with the Oracle link if you want to take a look.
Finally, since unfortunately we can not receive the installation progress status of the JRE in any way, we show a message and a progress bar so that the user does not have the feeling that the installer has hung.
To do this, we save the state before, execute Exec with the flag ewWaitUntilTerminated, to wait for that installation to finish before continuing with ours, and we restore the previous state once the function execution has finished.

Related

Running java from VBA macro in Windows 7 bypassing System32 / SysWOW64 javaw.exe

Is there a way to bypass the 32-bit java version (maybe a different way to start a proccess in VBA to invoke the 64-bit version cmd, turn off the UAC or some other sort of tweek) that is being "forced" by the following VBA code (this is just an assumption, I am explaining the debugging process below):
handleDbl = Shell("javaw -cp theJar.jar com.java.SampleClass", vbNormalFocus)
The main point here is that I want to share my macro and avoid putting extra instructions on the recipient so I am trying to do everything on the code (I am using late binding on VBA code to avoid to setting References manually and that kind of stuff).
Debugging Process
An error was thrown so I used the following line instead:
handleDbl = Shell("cmd /k java -cp theJar.jar com.java.SampleClass", vbNormalFocus)
And got the error Exception in thread "main" java.lang.UnsupportedClassVersionError: Unsupported major.minor version so I checked the java -version and tried to find out which java was running with:
C:\>where java
C:\Windows\System32\java.exe
C:\Program Files\Java\_anyJava.x.x.x_\bin\java.exe
I went to System32 folder and there was no java there but I knew that redirection happens from there to C:\Windows\SysWOW64 so I compared the previously extracted java version against C:\Windows\SysWOW64\java.exe -version and they matched.
After that I checked my Outlook version and turned out to be a 32-bit installation. That was a hint but it was mostly that and that big *32 next to the cmd.exe in the Task Manager. I don't know if a 64-bit Outlook would make a difference or it would be the same because of the VBA implementation but that's how I concluded the Shell function from VBA is causing 32-bit java call.
Normally there is a JAVA_HOME environment variable set. If so, then you can do something like this:
Dim JavaExe As String
JavaExe = """" & Environ("JAVA_HOME") & "\bin\java.exe"""
handleDbl = Shell("cmd /k " & JavaExe & " -cp theJar.jar com.java.SampleClass", vbNormalFocus)
If it isn't set, you'll have to find it by some searching, before compiling the command.
Sam's answer is great but I just felt uneasy about user going through more settings so I wrote some functions to check java's versions and notify the user if it is not there (would have to install java in that case anyway) so here is my code. It might contain some helpful stuff.
Private Function IsJavaAvailable(ByVal displayMessage As Boolean, Optional ByVal isJavaMandatory As Boolean) As Boolean
Dim availability As Boolean
Dim minJavaVersion As Integer
minJavaVersion = 8
'isJavaSetup is a global variable
If (Not isJavaSetup) Then
javawPathQuoted = GetMinimumJavaVersion(minJavaVersion)
If StrComp(javawPathQuoted, "") <> 0 Then
isJavaSetup = True
End If
SetGlobalVars
End If
If javawPathQuoted = Empty Then
availability = False
Else
availability = True
End If
If (displayMessage) Then
If (isJavaMandatory) Then
If Not availability Then
MsgBox "This functionality is NOT available without Java " & minJavaVersion & "." & _
vbNewLine & vbNewLine & _
"Please install Java " & minJavaVersion & " or higher.", vbCritical, _
"Mimimum Version Required: Java " & minJavaVersion
End If
Else
If Not availability Then
MsgBox "Some features of this functionality were disabled." & _
vbNewLine & vbNewLine & _
"Please install Java " & minJavaVersion & " or higher.", vbExclamation, _
"Mimimum Version Required: Java " & minJavaVersion
End If
End If
End If
IsJavaAvailable = availability
End Function
Private Function GetMinimumJavaVersion(ByVal javaMinimumMajorVersionInt As Integer) As String
'Run a shell command, returning the output as a string
Dim commandStr As String
Dim javawPathVar As Variant
Dim javaPathStr As Variant
Dim javaVersionStr As String
Dim javaMajorVersionInt As Integer
Dim detectedJavaPaths As Collection
Dim javaVersionElements As Collection
Dim javaVersionOutput As Collection
Dim detectedJavaVersions As Collection
Dim suitableJavawPath As String
'Check available javaw executables in the SO
commandStr = "where javaw"
Set detectedJavaPaths = GetCommandOutput(commandStr)
Set detectedJavaVersions = New Collection
For Each javawPathVar In detectedJavaPaths
'Look for java.exe instead of javaw.exe by substituting it in path
' javaw.exe does NOT return version output like java.exe
javaPathStr = StrReverse(Replace(StrReverse(javawPathVar), StrReverse("javaw.exe"), StrReverse("java.exe"), , 1))
commandStr = """" & javaPathStr & """" & " -version"
Set javaVersionOutput = GetCommandOutput(commandStr)
javaVersionStr = javaVersionOutput.item(1)
Debug.Print "Getting java version: ", commandStr
Debug.Print "Version detected: "; javaVersionStr
Set javaVersionElements = SplitOnDelimiter(javaVersionStr, " ")
'Check that output is not an error or something else
'java version "1.8.0_75"
If javaVersionElements.Count > 2 Then
If StrComp(javaVersionElements.item(1), "java", vbTextCompare) = 0 Then
If StrComp(javaVersionElements.item(2), "version", vbTextCompare) = 0 Then
detectedJavaVersions.Add javaVersionStr
'Remove quotes from "1.8.0_75", split on '.', get 2nd item (java major version) and cast it to Integer
javaMajorVersionInt = CInt(SplitOnDelimiter(SplitOnDelimiter(javaVersionElements.item(3), """").item(1), ".").item(2))
'JAR will only run in Java 8 or later
If (javaMajorVersionInt >= javaMinimumMajorVersionInt) Then
'Validate that "javaw.exe" exists since the validation was made with "java.exe"
Debug.Print "Verifying if javaw.exe exists: ", javawPathVar
If Len(Dir(javawPathVar)) > 0 Then
suitableJavawPath = javawPathVar
Debug.Print "A suitable javaw.exe version found: ", suitableJavawPath
Exit For
End If
End If
End If
End If
End If
Next javawPathVar
GetMinimumJavaVersion = suitableJavawPath
End Function
Private Function GetCommandOutput(ByRef commandStr As String) As Collection
'Run a shell command, returning the output as a string
Dim shellObj As Object
Set shellObj = CreateObject("WScript.Shell")
'run command
Dim wshScriptExecObj As Object
Dim stdOutObj As Object
Dim stdErrObj As Object
Set wshScriptExecObj = shellObj.Exec(commandStr)
Set stdOutObj = wshScriptExecObj.StdOut
Set stdErrObj = wshScriptExecObj.StdErr
'handle the results as they are written to and read from the StdOut object
Dim fullOutputCollection As Collection
Set fullOutputCollection = New Collection
Dim lineStr As String
While Not stdOutObj.AtEndOfStream
lineStr = stdOutObj.ReadLine
If lineStr <> "" Then
fullOutputCollection.Add lineStr
End If
Wend
If fullOutputCollection.Count = 0 Then
While Not stdErrObj.AtEndOfStream
lineStr = stdErrObj.ReadLine
If lineStr <> "" Then
fullOutputCollection.Add lineStr
End If
Wend
End If
Set GetCommandOutput = fullOutputCollection
End Function

Ask for password when try to uninstall my java application in Windows

I've made an installer of my java application for Windows. After installing it in Windows everything works perfectly. Now I want to add a feature which should ask for a Password when I try to uninstall my Application without password one must not be able to uninstall it.
One other thing that I want to know is, whether I need to make a separate uninstaller or I can add these functionalities in my installer itself?
Any help would be appreciated.
P.S. Here I'm targeting Windows OS to install applications.
In short, I want that if someone tries to uninstall my application, he prompted for a password and if he enters the right password then
and then he can able to uninstall it.
I don't know to achieve above want, whether I need to change my
installer or I need to create a custom uninstaller.
Finally, after so much effort I found some good source that explains to me all the questions.
In Inno Setup pascal script I can modify some code to achieve password protection like this:
[Setup]
AppName=UninsPassword
AppVerName=UninsPassword
DisableProgramGroupPage=true
DisableStartupPrompt=true
DefaultDirName={pf}\UninsPassword
[Code]
function AskPassword(): Boolean;
var
Form: TSetupForm;
OKButton, CancelButton: TButton;
PwdEdit: TPasswordEdit;
begin
Result := false;
Form := CreateCustomForm();
try
Form.ClientWidth := ScaleX(256);
Form.ClientHeight := ScaleY(100);
Form.Caption := 'Uninstall Password';
Form.BorderIcons := [biSystemMenu];
Form.BorderStyle := bsDialog;
Form.Center;
OKButton := TButton.Create(Form);
OKButton.Parent := Form;
OKButton.Width := ScaleX(75);
OKButton.Height := ScaleY(23);
OKButton.Left := Form.ClientWidth - ScaleX(75 + 6 + 75 + 50);
OKButton.Top := Form.ClientHeight - ScaleY(23 + 10);
OKButton.Caption := 'OK';
OKButton.ModalResult := mrOk;
OKButton.Default := true;
CancelButton := TButton.Create(Form);
CancelButton.Parent := Form;
CancelButton.Width := ScaleX(75);
CancelButton.Height := ScaleY(23);
CancelButton.Left := Form.ClientWidth - ScaleX(75 + 50);
CancelButton.Top := Form.ClientHeight - ScaleY(23 + 10);
CancelButton.Caption := 'Cancel';
CancelButton.ModalResult := mrCancel;
CancelButton.Cancel := True;
PwdEdit := TPasswordEdit.Create(Form);
PwdEdit.Parent := Form;
PwdEdit.Width := ScaleX(210);
PwdEdit.Height := ScaleY(23);
PwdEdit.Left := ScaleX(23);
PwdEdit.Top := ScaleY(23);
Form.ActiveControl := PwdEdit;
if Form.ShowModal() = mrOk then
begin
Result := PwdEdit.Text = 'removeme';
if not Result then
MsgBox('Password incorrect: Uninstallation prohibited.', mbInformation, MB_OK);
end;
finally
Form.Free();
end;
end;
function InitializeUninstall(): Boolean;
begin
Result := AskPassword();
end;
Source of information: this post

Find JRE installation path in Inno Setup

Followings are my requirement:
Check if the Java is installed
Check if it's installed in a custom directory
if it's, then save the directory path in a variable
Otherwise detect the version and save the standard path in a variable
Below is the code that detects the version and save the standard path to a variable
Problems with my code:
If both 32 and 64 bit is installed it detects the both ..My aim is to detect only 64 bit in case both is installed.
if DirExists(ExpandConstant('{pf32}\java\')) then Is this what i can use to detect custom directory?
I don't think the above code is the right way to find custom directory of java. if the user installed in a different folder other than Java. the other problem is if we uninstall java it doesn't delete the folder java/JRE.
I'm using #TLama's code from Need help on Inno Setup script - issue in check the jre install
[Code]
#define MinJRE "1.7.0"
#define WebJRE "http://www.oracle.com/technetwork/java/javase/downloads/jre6downloads-1902815.html"
function IsJREInstalled: Boolean;
var
JREVersion: string;
JREPath:string
begin
{ read JRE version }
Result := RegQueryStringValue(HKLM32, 'Software\JavaSoft\Java Runtime Environment',
'CurrentVersion', JREVersion);
MsgBox('JAVA 32 bit detected.', mbInformation, MB_OK);
JREPath := 'C:\Program Files (x86)\Java'
{ if the previous reading failed and we're on 64-bit Windows, try to read }
{ the JRE version from WOW node }
if not Result and IsWin64 then
Result := RegQueryStringValue(HKLM64, 'Software\JavaSoft\Java Runtime Environment',
'CurrentVersion', JREVersion);
MsgBox('JAVA 64 bit detected.', mbInformation, MB_OK);
JREPath := 'C:\Program Files\Java'
{ if the JRE version was read, check if it's at least the minimum one }
if Result then
Result := CompareStr(JREVersion, '{#MinJRE}') >= 0;
end;
function InitializeSetup: Boolean;
var
ErrorCode: Integer;
begin
Result := True;
{ check if JRE is installed; if not, then... }
if not IsJREInstalled then
begin
{ show a message box and let user to choose if they want to download JRE; }
{ if so, go to its download site and exit setup; continue otherwise }
if MsgBox('Java is required. Do you want to download it now ?',
mbConfirmation, MB_YESNO) = IDYES then
begin
Result := False;
ShellExec('', '{#WebJRE}', '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode);
end;
end;
end;
JRE installation path is stored in registry like this:
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment]
"CurrentVersion"="1.8"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.8]
"JavaHome"="C:\\Program Files\\Java\\jre1.8.0_172"
You can retrieve the installation path of the latest version (with 64-bit preference) using a code like this:
const
JavaKey = 'SOFTWARE\JavaSoft\Java Runtime Environment';
function GetJavaVersionAndPath(
RootKey: Integer; var JavaVersion: string; var JavaPath: string): Boolean;
var
JREVersion: string;
begin
Result :=
RegQueryStringValue(RootKey, JavaKey, 'CurrentVersion', JavaVersion) and
RegQueryStringValue(RootKey, JavaKey + '\' + JavaVersion, 'JavaHome', JavaPath);
end;
{ ... }
var
JavaVersion: string;
JavaPath: string;
begin
if GetJavaVersionAndPath(HKLM64, JavaVersion, JavaPath) then
begin
Log(Format('Java %s 64-bit found in "%s"', [JavaVersion, JavaPath]));
end
else
if GetJavaVersionAndPath(HKLM32, JavaVersion, JavaPath) then
begin
Log(Format('Java %s 32-bit found in "%s"', [JavaVersion, JavaPath]));
end
else
begin
Log('No Java found');
end;
end;
Depending on which JRE you have installed, that registry data may not be there. A more generic solution is probably preferable.
I wanted something I could use across multiple Inno Setup projects, so I wrote a DLL for detecting Java details (home directory, etc.):
https://github.com/Bill-Stewart/JavaInfo
Download from here: https://github.com/Bill-Stewart/JavaInfo/releases
The download includes a sample Inno Setup .iss script that demonstrates how to use the DLL functions.

Run java file in inno setup

I have program in java who are copying some files to home java folders. In cmd it's work. I don't know how use it in Inno Setup.
I tried:
Filename: "{cmd}"; Parameters: "/C ""cd {app}""/C ""java Javaxcomm"; Flags: runhidden waituntilterminated runascurrentuser
Filename: "java"; Parameters: "Javaxcomm"; WorkingDir: "{app}"; Flags: runhidden waituntilterminated runascurrentuser
Filename: "cmd"; Parameters: "/C java {app}\Javaxcomm"
I found another way. Maybe someone this will help. It isn't my code.
[Code]
var
javaVersion: String;
javaPath: String;
function InitializeSetup(): Boolean;
begin
if RegValueExists(HKLM, 'SOFTWARE\JavaSoft\Java Development Kit', 'CurrentVersion') then
begin
RegQueryStringValue(HKLM, 'SOFTWARE\JavaSoft\Java Development Kit', 'CurrentVersion', javaVersion);
MsgBox('Found Java Development Kit version ' + javaVersion, mbInformation, MB_OK);
if RegValueExists(HKLM, 'SOFTWARE\JavaSoft\Java Development Kit\' + javaVersion, 'JavaHome') then
begin
RegQueryStringValue(HKLM, 'SOFTWARE\JavaSoft\Java Development Kit\' + javaVersion, 'JavaHome', javaPath);
MsgBox('Found Java Development Kit java_home: ' + javaPath, mbInformation, MB_OK);
Result := True;
end
else
begin
MsgBox('Java Path not set for JDK' + javaVersion, mbInformation, MB_OK);
MsgBox('RE-install java', mbInformation, MB_OK);
Result := False;
end
end
else if RegValueExists(HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment', 'CurrentVersion') then
begin
RegQueryStringValue(HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment', 'CurrentVersion', javaVersion);
MsgBox('Found Java Runtime Environment version ' + javaVersion, mbInformation, MB_OK);
if RegValueExists(HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment\' + javaVersion, 'JavaHome') then
begin
RegQueryStringValue(HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment\' + javaVersion, 'JavaHome', javaPath);
MsgBox('Found Runtime Environment java_home: ' + javaPath, mbInformation, MB_OK);
Result := True;
end
else
begin
MsgBox('Java Path not set for Java Runtime Environment' + javaVersion, mbInformation, MB_OK);
MsgBox('RE-install java', mbInformation, MB_OK);
Result := False;
end
end
else
begin
MsgBox('v1 has not been found on your computer.'#13#13'Please Install it and try again.', MbError, Mb_Ok);
Result := False;
end
end;
function GetJAVAHome(S: String) : String;
begin
Result := javaPath;
end;
Source: "{#MojaAppZrodla}\commapi\comm.jar"; DestDir: "{code:GetJAVAHome}\lib\ext"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#MojaAppZrodla}\commapi\win32com.dll"; DestDir: "{code:GetJAVAHome}\bin"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#MojaAppZrodla}\commapi\javax.comm.properties"; DestDir: "{code:GetJAVAHome}\lib"; Flags: ignoreversion recursesubdirs createallsubdirs

Application running using os.exec doesn't load java libraries properly

I would really appreciate if you helped me. I'm rewriting a simple Minecraft launcher from Java to Go. Everything is good, in exception of one thing.
I have a start function which executes using os.Exec this command:
java -Xincgc -Xmx1024M -Djava.library.path="/minecraft/bin/natives/" -cp "/minecraft/bin/*" -Dfml.ignoreInvalidMinecraftCertificates=true -Dfml.ignorePatchDiscrepancies=true net.minecraft.launchwrapper.Launch --username user --session session --version 1.6.4 --gameDir "/minecraft" --assetsDir "/minecraft" --tweakClass cpw.mods.fml.common.launcher.FMLTweaker
Everything is fine running this through bash or cmd, but when executed with Go function it returns the following:
Could not find or load main class net.minecraft.launchwrapper.Launch
I think os.exec(Command) cannot properly interpet this part of command:
-cp "/minecraft/bin/*"
Maybe that's because I quoted string "/minecraft/bin/*" with strconv.Quote() function or because of asterisk. I really don't know what's heppening. Ah, btw, the command os.exec has run is correct, though (I read it in stdout with fmt for debugging purposes).
program:
func start(login string, session string, ram string) {
//start game
app := "java"
arg0 := "-Xincgc"
arg1 := "-Xmx" + ram + "M"
arg2 := "-Djava.library.path=" + strconv.Quote(filepath.FromSlash(client+"bin/natives/"))
arg3 := "-cp"
arg4 := strconv.Quote(filepath.FromSlash(client + "bin/*"))
arg5 := "-Dfml.ignoreInvalidMinecraftCertificates=true"
arg6 := "-Dfml.ignorePatchDiscrepancies=true"
arg7 := "net.minecraft.launchwrapper.Launch"
arg8 := "--username"
//arg9 is login
arg10 := "--session"
//arg11 is session
arg12 := "--version 1.6.4"
arg13 := "--gameDir"
arg14 := strconv.Quote(filepath.FromSlash(client))
arg15 := "--assetsDir"
arg16 := strconv.Quote(filepath.FromSlash(client + "assets"))
arg17 := "--tweakClass cpw.mods.fml.common.launcher.FMLTweaker"
cmd := exec.Command(app, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, login, arg10, session, arg12, arg13, arg14, arg15, arg16, arg17)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
fmt.Println(app, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, login, arg10, session, arg12, arg13, arg14, arg15, arg16, arg17)
}
The question "Properly pass arguments to Go Exec" mentions:
exec.Command(...) adds double quotes to the parameters if there is spaces in them, so you only need to escape \" where you need them.
In your case, -cp "/minecraft/bin/*" would be passed to exec.Command as two separate parameters.
If you need quotes within one parameter, you could use a string literal to keep them (as commented in "How do you add spaces to exec.command in golang").
But if, in your case, you need the cp (classpath) to be expended by the shell (as mentioned in "double quotes escaping in golang exec"), then remove the quotes:
exec.Command(..., "-cp", `/minecraft/bin/*`, ...)

Categories

Resources