Start Minecraft On Mac With Java - java

I am trying to make a java program that will launch minecraft in offline mode with whatever username i want so i can have usernames like Notch and deadmau5 and i am using this code to launch it on mac and windows (Currently Testing on mac):
public void startMacMinecraft(String username) throws IOException,
InterruptedException {
System.out.println(defaultDirectory());
String sysUser = System.getProperty("user.name");
String commandString = "java -cp "
+ defaultDirectory()
+ "/minecraft/bin/minecraft.jar:"
+ defaultDirectory()
+ "/minecraft/bin/lwjgl.jar:"
+ defaultDirectory()
+ "/minecraft/bin/lwjgl_util.jar:"
+ defaultDirectory()
+ "/minecraft/bin/jinput.jar: -Djava.library.path="
+ defaultDirectory()
+ "/minecraft/bin/natives -Xmx1024M -Xms512M net.minecraft.client.Minecraft '"
+ username + "'";
CommandLine command = CommandLine.parse(commandString);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(command);
System.out.println(exitValue);
System.out.println("\nTry Two:\n");
String javaExe = System.getProperty("java.home") + "/bin/java";
}
public void startWinMinecraft(String username) throws IOException,
InterruptedException {
String sysUser = System.getProperty("user.name");
String commandString = "Java -Xms512m -Xmx1024m -cp \"%APPDATA%\\.minecraft\\bin\\*\" -Djava.library.path=\"%APPDATA%\\.minecraft\\bin\\natives net.minecraft.client.Minecraft \""
+ username + "\"";
CommandLine command = CommandLine.parse(commandString);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(command);
System.out.println(exitValue);
}
private static String defaultDirectory() {
String OS = System.getProperty("os.name").toUpperCase();
if (OS.contains("WIN"))
return System.getenv("APPDATA");
else if (OS.contains("MAC"))
return System.getProperty("user.home") + "/Library/Application "
+ "Support";
else if (OS.contains("NUX"))
return System.getProperty("user.home");
return System.getProperty("user.dir");
}
Which i am trying to adapt from this applescript which i have run before and got from https://gaming.stackexchange.com/questions/46608/how-can-i-run-minecraft-in-offline-mode-on-os-x-and-still-have-my-name that i will paste right here:
property user_name : "Player"
display dialog "Enter A User Name" default answer "" buttons {"Cancel", "Continue"} default button 2
set the user_name to text returned of the result
set UsrApp to (path to current user folder)
set UsrApp_unx to POSIX path of UsrApp
set MineScript to "java -cp " & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/minecraft.jar:" & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/lwjgl.jar:" & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/lwjgl_util.jar:" & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/jinput.jar: -Djava.library.path=" & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/natives -Xmx1024M -Xms512M net.minecraft.client.Minecraft '" & user_name & "'"
do shell script MineScript
When i run the applescript it works perfectly fine but when i run my adapted version it gives me a class not found error:
Logging in as: Player
/Users/Connor/Library/Application Support
Exception in thread "main" java.lang.NoClassDefFoundError: Support/minecraft/bin/minecraft/jar:/Users/Connor/Library/Application
Caused by: java.lang.ClassNotFoundException: Support.minecraft.bin.minecraft.jar:.Users.Connor.Library.Application
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:377)
at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:160)
at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:147)
at info.connorbp.GUIApp.LoginPanel.startMacMinecraft(LoginPanel.java:137)
at info.connorbp.GUIApp.LoginPanel$1.actionPerformed(LoginPanel.java:82)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6375)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6140)
at java.awt.Container.processEvent(Container.java:2083)
at java.awt.Component.dispatchEventImpl(Component.java:4737)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Component.dispatchEvent(Component.java:4565)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
at java.awt.Container.dispatchEventImpl(Container.java:2127)
at java.awt.Window.dispatchEventImpl(Window.java:2482)
at java.awt.Component.dispatchEvent(Component.java:4565)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:684)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:643)
at java.awt.EventQueue$1.run(EventQueue.java:641)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:657)
at java.awt.EventQueue$2.run(EventQueue.java:655)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:654)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
does anyone know what i am doing wrong or how to fix it?
EDIT:
Even stranger yet, I went into the events area of the applescript area and found the exact command the applescript was running:
java -cp /Users/Connor/Library/Application\\ Support/minecraft/bin/minecraft.jar:/Users/Connor/Library/Application\\ Support/minecraft/bin/lwjgl.jar:/Users/Connor/Library/Application\\ Support/minecraft/bin/lwjgl_util.jar:/Users/Connor/Library/Application\\ Support/minecraft/bin/jinput.jar: -Djava.library.path=/Users/Connor/Library/Application\\ Support/minecraft/bin/natives -Xmx1024M -Xms512M net.minecraft.client.Minecraft 'username'
and even when a tried running the script that came directly from the applescript i got another java.lang.NoClassDefFoundError error, even though i took the command directly from the applescript that is working.

In the default launcher, whatever username you provide gets used for offline mode, so writing a separate launcher is pointless.
In any case, decompiling the launcher should give us a pretty good idea of how to launch the game.
There is a lot of code so I recommend decompiling it yourself. For mac, JD-GUI does an alright job. For windows, I can't recommend a decompiler, but thats what google is for :)
After you get the launcher source code, have a peek at public void login(String userName, String password) in net.minecraft.LauncherFrame. Also relevant is net.minecraft.Launcher.
Reading through that should give you a pretty good idea of how to launch minecraft.

Oops, forgot about this question. I was actually just missing some of the code that was needed in order to launch minecraft.

Related

Java code: add registry entry with cmd isnt working

Hello guys i want to add an autostart entry in windows registry with java:
String cmd[] = { "regex.exe add ","\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"", " /v ","\"Test\"", " /t ", "REG_SZ", " /d ", value };
Runtime.getRuntime().exec(cmd);
sysout(value): "javaw -jar C:\Users\name\eclipse-workspace\project\myjar.jar"
sysout(cmd): [regex.exe add , "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", /v , "Test", /t , REG_SZ, /d , "javaw -jar C:\Users\name\eclipse-workspace\project\myjar.jar"]
If i run my code i get some errors:
*Cannot run program "regex.exe add ": CreateProcess error=2, Cannot find your file
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at java.base/java.lang.Runtime.exec(Runtime.java:589)
at java.base/java.lang.Runtime.exec(Runtime.java:448)
at Logger.log.main(log.java:23)
Caused by: java.io.IOException: CreateProcess error=2,
at java.base/java.lang.ProcessImpl.create(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:483)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:158)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 4 more*
What did i wrong? I just want to add my jar into windows startup/autostart
Code example of my advice to start cmd.exe and use the OutputStream to send in the regex command:
Process proc = Runtime.getRuntime().exec("runas /Marcel/user:Administrator cmd.exe");
PrintStream ps = new PrintStream(proc.getOutputStream());
String cmd = "regex.exe add " + " \"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\","
+" /v , \"Test\", /t , REG_SZ, /d , \"javaw -jar " + "C:\Users\name\eclipse-workspace\project\myjar.jar\" ";
ps.println(cmd);
//you should probably also listen for results of the above from the output and error streams

Activating virtualenv via Java ProcessBuilder

Getting the following when trying to programmatically activate Python's virtualenv via the code below:
java.io.IOException: Cannot run program "." (in directory "/Users/simeon.../..../reporting"): error=13, Permission denied
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at VirtualEnvCreateCmdTest.runCommandInDirectory(VirtualEnvCreateCmdTest.java:30)
at VirtualEnvCreateCmdTest.createVirtEnv(VirtualEnvCreateCmdTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at ......
Caused by: java.io.IOException: error=13, Permission denied
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
at java.lang.ProcessImpl.start(ProcessImpl.java:134)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 25 more
Code:
public class VirtualEnvCreateCmdTest {
private final static Logger LOG = LoggerFactory.getLogger(VirtualEnvCreateCmdTest.class);
private void runCommandInDirectory(String path,String ... command) throws Throwable
{
LOG.info("Running command '"+String.join(" ",command)+"' in path '"+path+"'");
ProcessBuilder builder = new ProcessBuilder(command)
.directory(new File(path))
.inheritIO();
Process pr = builder.start();
final String failureMsg = format("Failed to run '%s' in path '%s'. Got exit code: %d", join(" ",command), path, pr.exitValue());
LOG.info("prepared message {}: ", failureMsg);
if(!pr.waitFor(120, TimeUnit.SECONDS))
{
throw new Exception(failureMsg);
}
int output = IOUtils.copy(pr.getInputStream(), System.out);
int exitCode=pr.exitValue();
if(exitCode!=0)
throw new Exception(failureMsg);
}
#Test
public void createVirtEnv() throws Throwable {
String path = "/Users/simeon/.../reporting";
String [] commands = new String[]{".", "activate"};
//String [] commands = new String [] {"/bin/bash", "-c", ". /Users/simeon/..../venv2.7/bin/activate"};
runCommandInDirectory(path, commands);
}
Changing permissioning on the file, doesn't seem to work:
chmod u+x ./bin/activate
Doing it via /bin/bash still doesn't work though with a different error.
At the same time the following works fine on the command line:
. /Users/simeon/.../venv2.7/bin/activate
Any samples of how one would invoke python virtualenv activate command from within Java?
=== What worked: =====
The following ended up working for me:
private void runDjangoMigrate() throws Throwable {
final String REPORTING_PROJECT_LOCATION = "/Users/simeon.../.../reporting";
final String UNIX_SHELL_LOCATION = "/bin/bash";
final String PYTHON_VIRTUALENV_ACTIVATOR_COMMAND =". /Users/simeon.../.../venv2.7/bin/activate;";
final String PYTHON_VIRTUALENV_ACTIVATOR_COMMAND =". " + PYTHON_VIRTUALENV_ACTIVATE_SCRIPT_LOCATION + ";";
final String DJANGO_MANAGE_MODULE = " manage.py";
final String[] DJANGO_MIGRATE_COMMAND = new String[] { UNIX_SHELL_LOCATION, "-c", PYTHON_VIRTUALENV_ACTIVATOR_COMMAND
+ PYTHON_INTERPRETER + DJANGO_MANAGE_MODULE + " migrate --noinput --fake-initial" };
runCommandInDirectory(REPORTING_PROJECT_LOCATION, DJANGO_MIGRATE_COMMAND);
}
private void runCommandInDirectory(String path, String... command) throws Throwable {
LOG.info(format("Running '%s' command in path '%s'", join(" ",command),path));
ProcessBuilder builder = new ProcessBuilder(command).directory(new File(path)).inheritIO();
Process pr = null;
pr = builder.start();
IOUtils.copy(pr.getInputStream(), System.out);
boolean terminated = pr.waitFor(SPAWNED_PYTHON_PROCESS_TTL_SEC, SECONDS);
int exitCode = -1;
if (terminated) {
exitCode = pr.exitValue();
}
if (exitCode != 0) {
final String failureMsg = format("Failed to run '%s' in path '%s'. Got exit code: %d", join(" ", command),
path, pr.exitValue());
throw new Exception(failureMsg);
}
}
and producing the following expected output:
[java] System check identified some issues:
[java]
[java] WARNINGS:
[java] ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace
[java] Building permissions...
[java] Operations to perform:
[java] Apply all migrations: admin, auth, contenttypes, sessions
[java] Running migrations:
[java] No migrations to apply.
[java] System check identified some issues:
[java]
[java] WARNINGS:
[java] ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace
[java] Building permissions...
[java] User exists, exiting normally due to --preserve
[java] System check identified some issues:
[java]
You can activate a Python virtual environment in bash (and perhaps zsh) and Python, but not in Java or any other environment. The main thing to understand is that virtual environment activation doesn't do some system magic — the activation script just changes the current environment, and Python virtual environments are prepared to changes shell or Python but nothing else.
In terms of Java it means that when you call runCommandInDirectory() it runs a new shell, that new shell briefly activates a virtual env, but then the shell exits and all changes that "activates" the virtual env are gone.
This in turn means that if you need to run some shell or Python commands in a virtual env you have to activate the environment in every runCommandInDirectory() invocation:
String [] commands1 = new String [] {"/bin/bash", "-c", ". /Users/simeon/..../venv2.7/bin/activate; script1.sh"};
runCommandInDirectory(path, commands)
String [] commands2 = new String [] {"/bin/bash", "-c", ". /Users/simeon/..../venv2.7/bin/activate; script2.sh"};
runCommandInDirectory(path, commands)
For Python scripts it's a bit simpler as you can run python from the environment and it automagically activates the environment:
String [] commands = new String [] {"/Users/simeon/..../venv2.7/bin/python", "script.py"};
runCommandInDirectory(path, commands)

Run time error in java code [duplicate]

This question already has answers here:
How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version
(51 answers)
Closed 9 years ago.
Hello I am a newbie to java and i am going along alone from a book, wherein there is a code called pharseomatic, which basically selects a random words from a list of word list and prints to the output.
The is as below :
public class phraseomatic{
public static void main( String[] agrs){
String[] wordlistone = { "Hello ", "whats up ", "How ", " U doing " };
String[] wordlisttwo = { "I am ", " Am Interseted ", "Learning ", "Java" };
String[] wordlisttre = { "C sharp ", "C plus plus ", "C and Unix ", "Linux "};
int wlen1 = wordlistone.length;
int wlen2 = wordlisttwo.length;
int wlen3 = wordlisttre.length;
int rand1 = (int) ( Math.random() * wlen1 );
int rand2 = (int) ( Math.random() * wlen2 );
int rand3 = (int) ( Math.random() * wlen3 );
String phrase = " " + wordlistone[rand1] + wordlisttwo[rand2] + wordlisttre[rand3] ;
System.out.println("The Result is --->" + phrase );
}
}
I was able to compile the code using javac phraseomatic.java command, and everything was good but when i run the code by using command java phraseomatic, I got the following output or errors, please let me know whether I am doing it right or my code is worng or both...? Thanks in advance. The errors is as below :
root#ubuntu:~/java# java phraseomatic
Exception in thread "main" java.lang.UnsupportedClassVersionError: phraseomatic : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
The java version during compiling the code is different during running.Mean compiled with higher version than running version of JAVA.Make sure the version of running jvm is lower than compiled version.
java.lang.UnsupportedClassVersionError is occur in below case
Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.
So you need to change your compiler to running version of java...
It's better go to Update one like java7

jstack not working on server

We use jstack on servers to detect if java apps are getting deadlocked. It's not working on one of our Linux servers. I think O/S version is:
$cat /etc/issue.net
Red Hat Enterprise Linux Server release 5.6 (Tikanga)
Kernel \r on an \m
Java version running on server:
java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02, mixed mode)
When I try:
jstack 19114
I get:
19114: Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding
When I try:
jstack -F 19114
I get:
Attaching to process ID 19114, please wait...
Debugger attached successfully.
Deadlock Detection:
No deadlocks found.
Thread 19180: (state = BLOCKED)
Error occurred during stack walking:
sun.jvm.hotspot.debugger.DebuggerException: sun.jvm.hotspot.debugger.DebuggerException: get_thread_regs failed for a lwp
at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal$LinuxDebuggerLocalWorkerThread.execute(LinuxDebuggerLocal.java:152)
at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.getThreadIntegerRegisterSet(LinuxDebuggerLocal.java:466)
at sun.jvm.hotspot.debugger.linux.LinuxThread.getContext(LinuxThread.java:65)
at sun.jvm.hotspot.runtime.linux_amd64.LinuxAMD64JavaThreadPDAccess.getCurrentFrameGuess(LinuxAMD64JavaThreadPDAccess.java:92)
at sun.jvm.hotspot.runtime.JavaThread.getCurrentFrameGuess(JavaThread.java:256)
at sun.jvm.hotspot.runtime.JavaThread.getLastJavaVFrameDbg(JavaThread.java:218)
at sun.jvm.hotspot.tools.StackTrace.run(StackTrace.java:76)
at sun.jvm.hotspot.tools.StackTrace.run(StackTrace.java:45)
at sun.jvm.hotspot.tools.JStack.run(JStack.java:60)
at sun.jvm.hotspot.tools.Tool.start(Tool.java:221)
at sun.jvm.hotspot.tools.JStack.main(JStack.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.tools.jstack.JStack.runJStackTool(JStack.java:118)
at sun.tools.jstack.JStack.main(JStack.java:84)
Caused by: sun.jvm.hotspot.debugger.DebuggerException: get_thread_regs failed for a lwp
at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.getThreadIntegerRegisterSet0(Native Method)
at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.access$800(LinuxDebuggerLocal.java:51)
at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal$1GetThreadIntegerRegisterSetTask.doit(LinuxDebuggerLocal.java:460)
at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal$LinuxDebuggerLocalWorkerThread.run(LinuxDebuggerLocal.java:127)
Anyone know what is causing this?
It is required to run jstack as the same user that started the java process. This resolves the above stacktrace error. See this posting: jstack thread dump error: get_thread_regs failed for a lwp for more detail. As soon as I sudoed the jstack command, the error disappeared.
The syntax is simply:
sudo -u USERID jstack PID
Example:
sudo -u tomcat7 jstack 2498
Try using kill -3 <pid> instead to get the stacktrace of your VM.
Can use a jsp that gives you similar output instead.
Following jsp prints the thread stack info to screen but you could change the output to a file as well or use in a regular POJO class.
<%# page import="java.util.*" %><%
Map<Thread,StackTraceElement[]> map = Thread.getAllStackTraces();
Set tt = map.keySet();
Iterator<Thread> ti = tt.iterator();
Thread thrd = null;
final String br = "<" + "br" + ">";//website does not parse it
try{
int cnt = 1;
StackTraceElement[] st = null;
while(ti.hasNext() ){
thrd = ti.next();
out.print(br + "<" + "hr" + ">" + br + cnt + " \"" + thrd.getName());
out.println("\", priority :" + thrd.getPriority() + ", state :" + thrd.getState());
out.print(", id :" + thrd.getId() + ", hex :" + Long.toHexString(thrd.getId()) );
out.print(" alive :" + thrd.isAlive() + ", daemon :" + thrd.isDaemon() );
out.print(" interrupted :" + thrd.isInterrupted() + ", daemon :" + thrd.isDaemon() );
out.print(".\n" + br);
st = thrd.getStackTrace();
for(int sti = 0; sti < st.length; sti++){
out.println(br + " " + st[sti].getClassName() + "." + st[sti].getMethodName());
out.println("(" + st[sti].getFileName());
if(st[sti].getLineNumber() < 1){
out.print("Native method");
}else{
out.print(":" + st[sti].getLineNumber());
}
out.println(")");
}
out.println("");
cnt++;
}
}catch(Exception e){
out.println(br + "err " + e + br);
}
%>
Sample output:
121 "Thread-40", priority :6, state :WAITING , id :134, hex :86 alive :true, daemon :false interrupted :false, daemon :false.
java.lang.Object.wait (Object.java Native method)
java.lang.Object.wait (Object.java :485)
org.jpos.iso.ISOMUX$Receiver.run (ISOMUX.java :326)
java.lang.Thread.run (Thread.java :662)
122 "Thread-48", priority :5, state :TIMED_WAITING , id :142, hex :8e alive :true, daemon :false interrupted :false, daemon :false.
java.lang.Thread.sleep (Thread.java Native method)
org.jpos.apps.qsp.QSP.monitorConfigFile (QSP.java :301)
org.jpos.apps.qsp.QSP.run (QSP.java :346)
java.lang.Thread.run (Thread.java :662)

PHP/Java bridge problem

I am using tomcat 6 on windows. Here is the code I am testing.
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.StringReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
* Create and run THREAD_COUNT PHP threads, concurrently accessing a
* shared resource.
*
* Create 5 script engines, passing each a shared resource allocated
* from Java. Each script engine has to implement Runnable.
*
* Java accesses the Runnable script engine using
* scriptEngine.getInterface() and calls thread.start() to invoke each
* PHP Runnable implementations concurrently.
*/
class PhpThreads {
public static final String runnable = new String("<?php\n" +
"function run() {\n" +
" $out = java_context()->getAttribute('sharedResource', 100);\n" +
" $nr = (string)java_context()->getAttribute('nr', 100);\n" +
" echo \"started thread: $nr\n\";\n" +
" for($i=0; $i<100; $i++) {\n" +
" $out->write(ord($nr));\n" +
" java('java.lang.Thread')->sleep(1);\n" +
" }\n" +
"}\n" +
"?>\n");
static final int THREAD_COUNT = 5;
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
Thread threads[] = new Thread[THREAD_COUNT];
ScriptEngine engines[] = new ScriptEngine[THREAD_COUNT];
ByteArrayOutputStream sharedResource = new ByteArrayOutputStream();
StringReader runnableReader = new StringReader(runnable);
// create THREAD_COUNT PHP threads
for (int i=0; i<THREAD_COUNT; i++) {
engines[i] = manager.getEngineByName("php-invocable");
if (engines[i] == null)
throw new NullPointerException ("php script engine not found");
engines[i].put("nr", new Integer(i+1));
engines[i].put("sharedResource", sharedResource);
engines[i].eval(runnableReader);
runnableReader.reset();
// cast the whole script to Runnable; note also getInterface(specificClosure, type)
Runnable r = (Runnable) ((Invocable)engines[i]).getInterface(Runnable.class);
threads[i] = new Thread(r);
}
// run the THREAD_COUNT PHP threads
for (int i=0; i<THREAD_COUNT; i++) {
threads[i].start();
}
// wait for the THREAD_COUNT PHP threads to finish
for (int i=0; i<THREAD_COUNT; i++) {
threads[i].join();
((Closeable)engines[i]).close();
}
// print the output generated by the THREAD_COUNT concurrent threads
String result = sharedResource.toString();
System.out.println(result);
// Check result
Object res=manager.getEngineByName("php").eval(
"<?php " +
"exit((int)('10011002100310041005'!=" +
"#system(\"echo -n "+result+"|sed 's/./&\\\n/g'|sort|uniq -c|tr -d ' \\\n'\")));" +
"?>");
System.exit(((Number)res).intValue());
}
}
I have added all the libraries. When I run the file I get the following error -
run:
Exception in thread "main" javax.script.ScriptException: java.io.IOException: Cannot run program "php-cgi": CreateProcess error=2, The system cannot find the file specified
at php.java.script.InvocablePhpScriptEngine.eval(InvocablePhpScriptEngine.java:209)
at php.java.script.SimplePhpScriptEngine.eval(SimplePhpScriptEngine.java:178)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:232)
at PhpThreads.main(NewClass.java:53)
Caused by: java.io.IOException: Cannot run program "php-cgi": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
at java.lang.Runtime.exec(Runtime.java:593)
at php.java.bridge.Util$Process.start(Util.java:1064)
at php.java.bridge.Util$ProcessWithErrorHandler.start(Util.java:1166)
at php.java.bridge.Util$ProcessWithErrorHandler.start(Util.java:1217)
at php.java.script.CGIRunner.doRun(CGIRunner.java:126)
at php.java.script.HttpProxy.doRun(HttpProxy.java:63)
at php.java.script.CGIRunner.run(CGIRunner.java:111)
at php.java.bridge.ThreadPool$Delegate.run(ThreadPool.java:60)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
... 8 more
What am I missing?
Just add this to your command line:
-Dphp.java.bridge.php_exec=/usr/bin/php
Problem solved!
copy the correct VERSION of the PHP of php5ts.dll and php-cgi.exe to "WEB-INF\cgi\amd64-windows" directory. then restart Tomcat. good luck.
...php-cgi...The system cannot find the file specified
I'm guessing that manager.getEngineByName("php-invocable") should return a wrapper around a system call to run PHP - but that wrapper doesn't know where to find the PHP executable.
A quick glance at the website for the PHP/Java bridge, and I infer that the path is hard coded in the Java - "For further information please see the INSTALL.J2EE file from the documentation download"
The Javadoc is decidedly vague on the topic.
You need to specifically make the -cgi version of PHP at compile time, assuming you've done that, and it is called php-cgi, then as a quick hack you could perpper your filesystem with links named "php-cgi" (its probably expected to be in /bin, /usr/bin/, /usr/local/bin, or the Java may be smart enough to check $PATH)
C.
when you get error like
Fatal Error: Failed to start PHP ["php-cgi", "-v"], reason: java.io.IOException:
Cannot run program ""php-cgi"" (in directory "C:\Documents and Settings\Adminis
trator"): CreateProcess error=2, The system cannot find the file specified
Could not start FCGI server: java.io.IOException: PHP not found. Please install
php-cgi. PHP test command was: [php-cgi, -v]
php.java.bridge.http.FCGIConnectException: Could not connect to server
at php.java.bridge.http.NPChannelFactory.test(NPChannel`enter code here`Factory.java:64)
at php.java.bridge.http.FCGIConnectionPool.<init>(FCGIConnectionPool.jav
a:175)
at php.java.bridge.http.FCGIConnectionPool.<init>(FCGIConnectionPool.jav
a:189)
at php.java.servlet.ContextLoaderListener.createConnectionPool(ContextLo
aderListener.java:541)
at php.java.servlet.ContextLoaderListener.contextInitialized(ContextLoad
erListener.java:185)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContex
t.java:4135)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4
630)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase
.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:77
1)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.jav
a:1041)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.j
ava:964)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502
)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java
:321)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(Lifecycl
eSupport.java:119)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445
)
at org.apache.catalina.core.StandardService.start(StandardService.java:5
19)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710
)
at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: java.io.IOException: File \\.\pipe\C:\Documents and Settings\Administ
rator\Desktop\softwares\apache-tomcat-6.0.29\temp\JavaBridge3144995283109409611.
socket not writable
at php.java.bridge.http.FCGIConnectException.<init>(FCGIConnectException
.java:37)
... 29 more
Caused by: java.io.IOException: PHP not found. Please install php-cgi. PHP test
command was: [php-cgi, -v]
at php.java.bridge.Util$Process.start(Util.java:1145)
at php.java.servlet.fastcgi.FCGIProcess.start(FCGIProcess.java:68)
at php.java.bridge.http.NPChannelFactory.doBind(NPChannelFactory.java:94
)
at php.java.bridge.http.FCGIConnectionFactory.runFcgi(FCGIConnectionFact
ory.java:88)
at php.java.bridge.http.FCGIConnectionFactory$1.run(FCGIConnectionFactor
y.java:109)
with the JavaBridge.war deployment in (windows, tomcat)
please specify the path for the php installation in your environment variable.

Categories