PHP/Java Bridge [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Troubleshooting ClassNotFoundException when using PHP/Java bridge
Can anyone please explain me about the PHP/Java Bridge installation.
I already installed bridge in my system.
This is my HelloWorld.java code :
import javax.swing.JOptionPane;
public class HelloWorld
{
public static final String JAVABRIDGE_PORT="8081";
static final php.java.bridge.JavaBridgeRunner runner =
php.java.bridge.JavaBridgeRunner.getInstance(JAVABRIDGE_PORT);
public static void main(String args[]) throws Exception
{
runner.waitFor();
System.exit(0);
}
public void hello(String args[]) throws Exception
{
JOptionPane.showMessageDialog(null, "hello " + args[0]);
}
}
This is my HelloWorld.php code:
<?php
require_once("http://localhost:8081/JavaBridge/java/Java.inc");
$world = new java("HelloWorld");
echo $world->hello(array("from PHP"));
?>
While calling Java class from php, it is not working and it is showing the below error:
Fatal error: Uncaught [[o:Exception]:"java.lang.Exception: CreateInstance failed: new HelloWorld. Cause: java.lang.ClassNotFoundException: HelloWorld VM: 1.5.0_01#http://java.sun.com/" at: #-31 org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1438) #-30 org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1284) #-29 java.lang.ClassLoader.loadClassInternal(Unknown Source) #-28 java.lang.Class.forName0(Native Method) #-27 java.lang.Class.forName(Unknown Source) #-26 php.java.bridge.Util.classForName(Util.java:1518) #-25 php.java.bridge.JavaBridge.CreateObject(JavaBridge.java:445) #-24 php.java.bridge.Request.handleRequest(Request.java:458) #-23 php.java.bridge.Request.handleOneRequest(Request.java:510) #-22 php.java.servlet.PhpJavaServlet.handleLocalConnection(PhpJavaServlet.java:202) #-21 php.java.servlet.PhpJavaServlet.handlePut(PhpJavaServlet.java:250) #-20 php.java.servlet.PhpJavaServlet.doPut(PhpJavaServlet.java:261) #-19 javax.servlet.http.HttpServlet.service(HttpS in http://localhost:8081/JavaBridge/java/Java.inc on line 195
Can you please anyone help me on this.
Thanks in advance.

I am unfamiliar with the package you are trying to use but it looks like you need to give the full path to your class. That is java/lang/ClassNotFoundException for example for the Java Exception that is being thrown and probably something like me/mypackage/HelloWordl for the class you are trying to create.

Related

Error in the webapp while connecting with JVM using jni4net from C#

I'm trying to access a simple java code from inside my C# webapp using jni4net, but it is throwing some errors.
Generated all proxies and dlls to access the java class.
I wrote the code for connecting with JVM inside the 'Program.cs' file.
Later on the custom java function ie. display_msg() is called from the testfunc() which can be called from anywhere inside the bot using Program.testfunc().
I'm attaching the Program.cs file and the exception occurring.
Also I've named my java file as Test.java and it's inside package mypack.
Program.cs
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using net.sf.jni4net;
using System;
using mypack;
namespace ValidationBot
{
public class Program
{
public static void Main(string[] args)
{
var setup = new BridgeSetup();
setup.Verbose = true;
setup.AddAllJarsClassPath("./");
Bridge.CreateJVM(setup);
Bridge.RegisterAssembly(typeof(Test).Assembly);
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((logging) =>
{
logging.AddDebug();
logging.AddConsole();
}).UseStartup<Startup>();
public static void testfunc()
{
Test test = new Test();
test.display_msg();
Console.WriteLine("\nPress any key to quit.");
Console.ReadKey();
}
}
}
Test.java
package mypack;
import java.io.*;
public class Test
{
public static void main(String args[])
{
int s =10;
System.out.println(s);
}
public void display_msg()
{
System.out.println("Hello, I'm inside a java program");
}
}
Exception
Exception thrown: 'System.MissingMethodException' in jni4net.n-0.8.8.0.dll
Exception thrown: 'System.Reflection.TargetInvocationException' in System.Private.CoreLib.dll
Exception thrown: 'System.TypeInitializationException' in jni4net.n-0.8.8.0.dll
An unhandled exception of type 'System.TypeInitializationException' occurred in jni4net.n-0.8.8.0.dll
The type initializer for 'net.sf.jni4net.utils.Registry' threw an exception.
I'm a beginner to C# so please help me out with this.
From the comments we deduced that .NET core 2.1 does not support this method: (and maybe others)
System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)

java: Exception in thread "main" java.lang.UnsatisfiedLinkError: java.net.SocketOutputStream.init()V

It's very interesting to use Class.forName() to load a class and get errors... I write one line code and get an error as above.
class UnsatisfiedLinkErrorTest {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(Class.forName("java.net.SocketOutputStream"));
}
}
When I use java UnsatisfiedLinkErrorTest, I get an error:
> java UnsatisfiedLinkErrorTest
Exception in thread "main" java.lang.UnsatisfiedLinkError: java.net.SocketOutputStream.init()V
at java.net.SocketOutputStream.init(Native Method)
at java.net.SocketOutputStream.<clinit>(SocketOutputStream.java:44)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:259)
at UnsatisfiedLinkErrorTest.main(UnsatisfiedLinkErrorTest.java:3)
But when I run it in Idea, I get:
> java "-javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=49247:/Applications/IntelliJ IDEA.app/Contents/bin" UnsatisfiedLinkErrorTest
class java.net.SocketOutputStream
I don't know why in Idea I can get the true answer, (maybe jni?) I hope someone can tell me the reason. Thanks.
This question has been solved. I then cancelled the initialization of the class, then the error goes. The error is about the initialization, but not about finding the native library. So:
class UnsatisfiedLinkErrorTest {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(Class.forName("java.net.SocketOutputStream", false, null)); // will be okay!
}
}

What are environment properties for Payara InitialContext from free standing Java Client

I've abandoned GlassFish 4-point-anything in favor of Payara41. Amazingly GF has unresolved JDBC and JMS Resources configuration bugs. See:
Glassfish Admin Console throws java.lang.IllegalStateException when creating JDBC Pool
Payara perfectly fixed the JMS configuration issues. So all I need are the environment properties my standalone Java Client needs to get an InitialContext(env) to lookup() those Resources.
Note: InitalContext() doesn't work in a standalone. Only in an EJB Container that can look up the {Payara Home}/glassfish/lib/jndi-properties file. That file has one property so that's what I have in my code below:
Key: "java.naming.factory.initial"
Value: "com.sun.enterprise.naming.impl.SerialInitContextFactory"
That set off a series of NoClassDerfinitionFound Exceptions that led me to add these jars with these classes to my client's buildpath, and to /glassfish/lib/. They are in the order I encountered them.
"glassfish-naming.jar" w/ "com.sun.enterprise.naming.impl.SerialInitContextFactory"
"internal-api-3.1.2.jar" w/ "org.glassfish.internal.api.Globals"
" hk2-api-2.1.46.jar " w/ "org.glassfish.hk2.api.ServiceLocator"
"appserv-rt.jar" from glassfish/lib added to client build path
But now my code throws a java.lang.NoSuchMethodError for Globals.getDefaultHabitat(). Please note, below the Exception doesn't get caught in my catch block. (And I don't see it in Payara's service.log either.)
I know my client finds Globals.class, because adding it caused the NoClassDefinitionFound for ServiceLocator. Are there two "Globals.class" out there ... one w/ and one w/o that method. Or is the "Lorg" in console output really different from "org", i.e. is there a "Lorg/glassfish/hk2/api/ServiceLocator"?
I'm stuck. And this seems such a bread and butter kind of need -- environment properties a standalone Java client needs to get Payara's InitialContext -- it would be nice to be able to add it here for everyone to use (in addition to the jars I've already located.) I'd love to see Payara soar, because I love its Admin Console compared to JBoss and MayFly's XML orientation. Any suggestions? I'm stumped.Code and console output follows:
Code
package org.america3.testclasses;
import java.util.Properties;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.america3.toolkit.U;
public class Test2 implements MessageListener {
static final Properties JNDI_PROPERTIES = new Properties() {
private static final long serialVersionUID = 1L;
{/*This property key:vlaue pair is specified in Payara41/glassfish/lib/jndi-properties*/
/*The class it calls for is in Payara41/glassfish/lib/glassfish-naming.jar*/
this.put ("java.naming.factory.initial","com.sun.enterprise.naming.impl.SerialInitContextFactory");}
};
//constructor
public Test2 () {
String iAmM = U.getIAmMShort(Thread.currentThread().getStackTrace());
System.out.println(iAmM + "beg");
try {
Context jndiContext = (Context) new InitialContext(JNDI_PROPERTIES);
} catch (Exception e) {
System.out.println(" " + iAmM + "InitialContext failed to instantiate");
System.out.println(" " + iAmM + "Exception : " + e.getClass().getName());
System.out.println(" " + iAmM + "e.getMessage(): " + e.getMessage());
System.out.println(" " + iAmM + "e.getMessage(): " + e.getCause());
e.printStackTrace();
}
System.out.println(iAmM + "end");
}
public static void main(String[] args) {
Test2 messageCenter = new Test2 ();
}
public void onMessage(Message arg0) {
// TODO Auto-generated method stub
}
}
Console
Test2.<init> () beg
Exception in thread "main" java.lang.NoSuchMethodError: org.glassfish.internal.api.Globals.getDefaultHabitat()Lorg/glassfish/hk2/api/ServiceLocator;
at com.sun.enterprise.naming.impl.SerialInitContextFactory.<init>(SerialInitContextFactory.java:126)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.<init>(Unknown Source)
at org.america3.testclasses.Test2.<init>(Test2.java:24)
at org.america3.testclasses.Test2.main(Test2.java:36)
PS: Could someone with enough points add a "Paraya" tag below. I mean with Glassfish's console throwing exceptions when used to configure any JNDI or JMS Resource I think many people will switch.
JAR internal-api-3.1.2.jar is for Glassfish v3, and its Globals class has a method getDefaultHabitat() that returns Habitat:
public static Habitat getDefaultHabitat() {
return defaultHabitat;
}
However, Glassfish v4 has changed method signatures, and you have to use new Glassfish v4 internal API whose Globals class has appropriate method getDefaultHabitat() that returns ServiceLocator:
public static ServiceLocator getDefaultHabitat() {
return defaultHabitat;
}
In other words, replace internal-api-3.1.2.jar with internal-api-4.1.jar which can be found on Maven Central here
You should add ${PAYARA-HOME}/glassfish/lib/gf-client.jar to your classpath as this references all the other required jars in it's META-INF/MANIFEST.MF. Please note, it uses relative path references so you really need to install Payara on the client machine.

Java DPAPI JNI error java.lang.UnsatisfiedLinkError:

Exception in thread "main" java.lang.UnsatisfiedLinkError: dpapi.DPAPI.CryptProtectData(Ljava/lang/String;[BZ)[B
at dpapi.DPAPI.CryptProtectData(Native Method)
at dpapi.DataProtector.protect(DataProtector.java:60)
at dpapi.Main.main(Main.java:36)
code
public class Main {
static {
System.load(new File("jdpapi-native-1.0.dll").getAbsolutePath());
}
public static void main(String[] args) {
DataProtector p = new DataProtector();
String x ="abc";
String y = p.protect(x).toString();
}
}
I know the library is loaded but i have no idea why i am still getting the execption.
link:http://jdpapi.sourceforge.net/
check your Java CPU architecture (32bit or 64bit) equals you dll.
32-bit windows process can't load 64-bit dll and via versa...

Error while trying to setup a Jython interpreter

I wanted to boot up a Jython interpreter inside the plugin, then execute files inside the interpreter.
package com.jakob.jython;
import org.bukkit.plugin.java.JavaPlugin;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
public class EmbeddedJython extends JavaPlugin {
private static final Logger log = Logger.getLogger("Minecraft");
private PythonInterpreter interpreter;
private PyObject plugin;
public void onEnable() {
log.info("JythonTest enabled");
this.interpreter = new PythonInterpreter();
log.info("Jython interpreter fired up and cooking on gas");
log.info("Loading Python Plugin");
InputStream pythonScript = EmbeddedJython.class.getResourceAsStream("MyPlugin.py");
this.interpreter.execfile(pythonScript, "MyPlugin.py");
log.info("Getting plg method.");
this.plugin = this.interpreter.get("plg");
log.info("Plugin loaded");
log.info(plugin.invoke("onEnable").toString());
}
public void onDisable() {
log.info(plugin.invoke("onDisable").toString());
log.info("Jython disabled");
}
}
In other tests I can get the Jython interpreter up and running strings I hand it but when I use the above snippet I end up with an exception that looks something like this:
11:03:38 [SEVERE] Error occurred while enabling JythonTest v0.12 (Is it up to da
te?): null
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at org.python.core.ParserFacade.adjustForBOM(ParserFacade.java:371)
at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:298)
at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:288)
at org.python.core.ParserFacade.parse(ParserFacade.java:183)
at org.python.core.Py.compile_flags(Py.java:1717)
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:235
)
at com.jakob.jython.EmbeddedJython.onEnable(EmbeddedJython.java:26)
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:125)
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader
.java:750)
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManage
r.java:253)
at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:132)
at org.bukkit.craftbukkit.CraftServer.loadPlugins(CraftServer.java:110)
at net.minecraft.server.MinecraftServer.e(MinecraftServer.java:218)
at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:205)
at net.minecraft.server.MinecraftServer.init(MinecraftServer.java:145)
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:265)
at net.minecraft.server.ThreadServerApplication.run(SourceFile:394)
java.io.IOException: java.io.IOException: Stream closed
at org.python.core.PyException.fillInStackTrace(PyException.java:70)
at java.lang.Throwable.<init>(Throwable.java:181)
at java.lang.Exception.<init>(Unknown Source)
at java.lang.RuntimeException.<init>(Unknown Source)
at org.python.core.PyException.<init>(PyException.java:46)
at org.python.core.PyException.<init>(PyException.java:43)
at org.python.core.Py.JavaError(Py.java:481)
at org.python.core.ParserFacade.fixParseError(ParserFacade.java:104)
at org.python.core.ParserFacade.parse(ParserFacade.java:186)
at org.python.core.Py.compile_flags(Py.java:1717)
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:235
)
at com.jakob.jython.EmbeddedJython.onEnable(EmbeddedJython.java:26)
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:125)
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader
.java:750)
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManage
r.java:253)
at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:132)
at org.bukkit.craftbukkit.CraftServer.loadPlugins(CraftServer.java:110)
at net.minecraft.server.MinecraftServer.e(MinecraftServer.java:218)
at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:205)
at net.minecraft.server.MinecraftServer.init(MinecraftServer.java:145)
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:265)
at net.minecraft.server.ThreadServerApplication.run(SourceFile:394)
Caused by: java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at org.python.core.ParserFacade.adjustForBOM(ParserFacade.java:371)
at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:298)
at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:288)
at org.python.core.ParserFacade.parse(ParserFacade.java:183)
... 13 more
Could it be I'm using execfile wrong?
Or is it an error or something I'm missing in how InputStream works?
Are you sure that EmbeddedJython.class.getResourceAsStream("MyPlugin.py"); is finding the resource?
If it can't find the resource, getResourceAsStream will return a null, and it is possible that the Jython interpreter will treat that as an empty (closed) stream.
Your application should probably check this, rather than assuming that getResourceAsStream has succeeded.
If I private File pythonFile = new File('MyScirpt.py'); and then hand getResourceAsStream(pythonFile.getAbsolutePath());
That won't work. The getResourceAsStream method looks for resources on the classloader's classpath, and expects a path that can be resolved relative to some entry on the classpath.
You probably want to do this:
private File pythonFile = new File('MyScirpt.py');
InputStream is = new FileInputStream(pythonFile);
and pass the is to the interpreter. You also need to arrange that the stream is always closed when the interpreter has finished ... by whatever mechanism that happens.
I see in the stacktrace, there is a reference to adjustForBOM (BOM = Byte Order Mark).
This could mean that your file MyPlugin.py is stored in a different encoding to other files that are working for you.
Can you try re-saving the file with a different encoding, say UTF-8?

Categories

Resources