I was creating a Java web service server, using eclipse IDE. that server is the following.
Note: I am working in UBUNTU
package com.tesis.service;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import com.mathworks.engine.*;
/**
* #author root
*
*/
public class CNNPredict
{
public String cNNPredict(int[] Image, int Height, int Width) throws Exception
{
String FilePath = "/home/user/Documents/MATLAB/Project";
char[] CharFilePath = FilePath.toCharArray();
MatlabEngine eng = MatlabEngine.startMatlab();
eng.feval("cd", CharFilePath);
String result = eng.feval("CNNPredict",Image,Height,Width);
return result;
}
}
As you can see I am using MATLAB engine.
Matlab engine documentation. I checked that cNNPredict method is working properly by copying it into a new Java project and It worked perfectly.
I added the .jar files required to run java engine to the Dynamic web project where the web service is located.
Apparently this web service runs without problems Web Service working in local host
If I click on "CnnPredict" link I get the wsdl direction of the class , this direction is what I use to link the client with the server.
this is the client code:
public static void main(String[] args) throws IOException, CNNPredictExceptionException
{
CNNPredictStub stub = new CNNPredictStub();
CNNPredict cnn = new CNNPredict();
BufferedImage img = null;
System.out.println("Reading image ...");
img = ImageIO.read(new File("/home/riosgamarra/Documents/MATLAB/TesisGamarrarios/101_ObjectCategories/laptop/image_0009.jpg"));
int[] UnrolledImage = convertToGray(img);
cnn.setImage(UnrolledImage);
cnn.setWidth(img.getWidth());
cnn.setHeight(img.getHeight());
System.out.println(stub.cNNPredict(cnn).get_return());
}
It has no errors, but when I run it this error message shows up:
Exception in thread "main" org.apache.axis2.AxisFault: <faultstring>com/mathworks/engine/MatlabEngine</faultstring>
at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:513)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:368)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:414)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:150)
at com.tesis.service.CNNPredictStub.cNNPredict(CNNPredictStub.java:197)
at com.tesis.client.CallWS.main(CallWS.java:40)
what I am missing ? do I need to add any special permissions to the server project ? What Am I missing ?
Note: I run the client clicking on the class and selecting Run as > Java application.
at com.tesis.service.CNNPredictStub.cNNPredict(CNNPredictStub.java:197)
is where the exception is but
public class CNNPredict
{
public String cNNPredict(int[] Image, int Height, int Width) throws Exception
{
String FilePath = "/home/user/Documents/MATLAB/Project";
char[] CharFilePath = FilePath.toCharArray();
MatlabEngine eng = MatlabEngine.startMatlab();
eng.feval("cd", CharFilePath);
String result = eng.feval("CNNPredict",Image,Height,Width);
return result;
}
}
is not the stub. First we need to the right code to look at. The matlab api is straight forward. My guess is that the stub is making the wrong call
Related
When the rtu.smallview.xhtml action event is triggered it requests info from the java bean, from the database select and hands it back to the xhtml.
The xhtml was not displaying the data from the database, so I added breakpoints in the java bean to figure out what was going wrong, but when the program loaded it never hit the breakpoint in the bean.
The server output is saying this when the program is loaded:
Info: WELD-000119: Not generating any bean definitions from Beans.RTU.RTU_SmallView_Bean because of underlying class loading error: Type pojo.rtu.RTU_unit not found. If this is unexpected, enable DEBUG logging to see the full error.
So I stopped the server, clean and built the project again, and when it runs for the first time it loads the bean, the information is retrieved and displayed. Though if I clean and build the project again, when it runs the second time it displays the same WELD-000119 error.
I copy and pasted just the code to make the RTU section run to a new project and the server doesn't ever throw this error, and it works every time the bean is requested and every time the server is started.
Edit 1:
When I restart NetBeans and Clean and Build the project after it starts it says this:
Note: C:\Users\Administrator\Documents\NetBeansProjects\OIUSA_1\src\java\Beans\RTU\RTU_SmallView_Bean.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
This is the only java class it says this about, so here is the code I used for that class:
package Beans.RTU;
import Database.RTU.RTU_SmallView_Select;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import pojo.rtu.RTU_unit;
/**
*
* #author Administrator
*/
#Named(value = "rtu_SmallView_Bean")
#RequestScoped
public class RTU_SmallView_Bean {
public RTU_SmallView_Bean() {
try {
RTU_SmallView_Select selectData;
selectData = new RTU_SmallView_Select();
this.smallViewList = selectData.getData();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
List<RTU_unit> smallViewList = new ArrayList();
String unit_type;
int unit_number;
String rig_name;
String location_name;
public List<RTU_unit> getSmallViewList() {
return smallViewList;
}
public void setSmallViewList(List<RTU_unit> smallViewList) {
this.smallViewList = smallViewList;
}
public String getUnit_type() {
return unit_type;
}
public void setUnit_type(String unit_type) {
this.unit_type = unit_type;
}
public int getUnit_number() {
return unit_number;
}
public void setUnit_number(int unit_number) {
this.unit_number = unit_number;
}
public String getRig_name() {
return rig_name;
}
public void setRig_name(String rig_name) {
this.rig_name = rig_name;
}
public String getLocation_name() {
return location_name;
}
public void setLocation_name(String location_name) {
this.location_name = location_name;
}
}
My project structure is as follows:
Sources:
Beans.RTU.RTU_SmallView_Bean.java
Database.RTU.RTU_SmallView_Select.java
pojo.rtu.RTU_unit.java
Webpages:
rtu.rtu_smallview.xhtml
I am thinking it has something to do with the actual server, but I'm not sure where to start looking for this error. If you would like to see the actual code for the beans and what not, let me know and I'll edit the question with all the code. Thanks
Problem has been solved, the file RTU_Unit.java was in a folder called pojo.rtu. I deleted the folder, made it again with a new name pojo.rtus, refactored the file RTU_Unit.java for the new folder and the problem has gone away.
I have a Java program that is able to change the wallpaper taking in input an image using WINAPI.
Everything works fine when I run it inside Eclipse IDE, but when I run the JAR I got the error:
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
public class Main {
//INIT USER32 for WINAPI
public static interface User32 extends Library {
User32 INSTANCE = (User32) Native.loadLibrary("user32",User32.class,W32APIOptions.DEFAULT_OPTIONS);
boolean SystemParametersInfo (int one, int two, String s ,int three);
}
public static void main(String[] args) throws IOException, URISyntaxException {
//Change wallpaper
System.out.println("Change wallpaper");
URL url = Main.class.getResource("/resources/img.jpg");
File f = new File(url.toURI());
String path = f.getPath();
User32.INSTANCE.SystemParametersInfo(0x0014, 0, path , 1);
}
}
The image is shipped within the JAR, so maybe the error is related to this since the program is not able to correctly read to URL inside the JAR.
Is there a way to solve this?
A jar file is just a compressed file when the resource is bundled as a jar java will be treated as a single file, which means it will not access to your resources.
try using this instead getResourceAsStream(...);
I'm trying to modify the jni4net sample code MyCSharpDemoCalc, and make the sample as a bridge between a .Net DLL and the Java layer. Here is the C# code:
using System;
using Dynamsoft.DotNet.TWAIN;
namespace MyCSharpDemoCalc
{
public interface ICalc
{
int MySuperSmartFunctionIDontHaveInJava(string question);
bool IsShowUI();
}
public class DemoCalc : ICalc
{
private readonly Random r = new Random();
private DynamicDotNetTwain dynamicDotNetTwain;
public DemoCalc()
{
dynamicDotNetTwain = new Dynamsoft.DotNet.TWAIN.DynamicDotNetTwain();
}
public int MySuperSmartFunctionIDontHaveInJava(string question)
{
if (question == "Answer to the Ultimate Question of Life, the Universe, and Everything")
{
return 42;
}
return r.Next();
}
public bool IsShowUI()
{
return dynamicDotNetTwain.IfShowUI;
}
}
}
In order to build it successfully, I added the following references:
System.Windows.Forms
DynamicDotNetTWAIN
Then typed in the command
proxygen.exe MyCSharpDemoCalc.dll -wd work
to generate MyCSharpDemoCalc.j4n.jarand MyCSharpDemoCalc.j4n.dll.
Now, I can import DynamicDotNetTWAIN.dll, MyCSharpDemoCalc.j4n.dll, jni4net.n.w64.v20-0.8.6.0.dll, jni4net.n-0.8.6.0.dll, jni4net.j-0.8.6.0.jar and MyCSharpDemoCalc.j4n.jar to Java project.
Java code:
import net.sf.jni4net.Bridge;
import java.io.IOException;
import mycsharpdemocalc.DemoCalc;
import mycsharpdemocalc.ICalc;
public class Program {
public static void main(String arsg[]) throws IOException {
Bridge.setClrVersion("v20");
Bridge.init();
Bridge.LoadAndRegisterAssemblyFrom(new java.io.File("DynamicDotNetTWAIN.dll"));
Bridge.LoadAndRegisterAssemblyFrom(new java.io.File("MyCSharpDemoCalc.j4n.dll")); // crashed
ICalc calc = new DemoCalc();
final int result = calc.MySuperSmartFunctionIDontHaveInJava("Answer to the Ultimate Question of Life, the Universe, and Everything");
System.out.printf("Answer to the Ultimate Question is : " + result);
System.out.printf("If show UI : " + calc.IsShowUI());
}
}
When I tried to run the application, it crashed at
Bridge.LoadAndRegisterAssemblyFrom(new
java.io.File("MyCSharpDemoCalc.j4n.dll"));
Exception in thread "main" System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark)
at System.Reflection.Assembly.GetTypes()
at net.sf.jni4net.utils.Registry.RegisterAssembly(Assembly assembly, Boolean bindJVM, ClassLoader classLoader)
at net.sf.jni4net.Bridge.RegisterAssembly(Assembly assembly, ClassLoader classLoader)
at net.sf.jni4net.Bridge.LoadAndRegisterAssemblyFromClassLoader(File assemblyFile, ClassLoader classLoader)
at net.sf.jni4net.Bridge.LoadAndRegisterAssemblyFrom(File assemblyFile)
at net.sf.jni4net.__Bridge.LoadAndRegisterAssemblyFrom3(IntPtr __envp, JniLocalHandle __class, JniLocalHandle assemblyFile)
at net.sf.jni4net.Bridge.LoadAndRegisterAssemblyFrom(Native Method)
at com.main.Program.main(Program.java:68)
How can I fix it? Thanks!
The JNI4NET will attempt to load the image from where the JNI4NET libraries were located at, the only workaround (AFAIK) was to copy the whole libraries to your source directory, and compile your package using the copied libraries, then it will work.
I'm new with webservices. I am trying to access a webservice in java using netbeans.
I followed some tutorials and created a web application project, then created a web service client. Netbeans created an index.jsp file, where I can access the webservice perfectly, but I want to access the webservice thru a java class.
I created a java class file where I put the same code I have in the jsp page and I get the error :
"Exception in thread "main" javax.xml.ws.WebServiceException: Failed to access the WSDL at: http://...... It failed with:
Invalid WSDL http://..... , expected {http:// schemas.xmlsoap. org/wsdl/}definitions found HTML at (lineLine number = 1"
If I debug the jsp page, I get no errors, but I can't compile in java class. I don't understand!
This is my jsp code that works perfectly:
<%-- start web service invocation --%>
<%
try {
com.epq.tipocambio.TipoCambio service = new com.epq.tipocambio.TipoCambio();
com.epq.tipocambio.TipoCambioSoap port = service.getTipoCambioSoap();
com.epq.tipocambio.InfoVariable result = port.tipoCambioDia();
Float cambio = result.getCambioDolar().getVarDolar().get(0).getReferencia();
out.println("Cambio = " + cambio);
} catch (Exception ex) {
//TODO handle custom exceptions here
System.out.println(ex);
}
%>
And this is my java class code that is giving me the errors:
package com.epq.tipocambio;
public class EPQTipoCambioDia {
private static InfoVariable tipoCambioDia() {
com.epq.tipocambio.TipoCambio service = new com.epq.tipocambio.TipoCambio();
com.epq.tipocambio.TipoCambioSoap port = service.getTipoCambioSoap();
return port.tipoCambioDia();
}
public static void main(String[] args){
InfoVariable c = EPQTipoCambioDia.tipoCambioDia();
Float cambio = c.getCambioDolar().getVarDolar().get(0).referencia;
System.out.print(cambio);
}
}
Any Ideas of what could be the problem?
Knowing nothing of web services, I'm just trying to call some "isAlive" service that is described by a wsdl.
This seems to me like something that should take no more than 2-5 lines of code but I can't seem to find anything but huge long examples involving 3rd party packages etc.
Anyone has any ideas? If it is always suppose to be long maybe a good explanation as to why it has to be so complicated will also be appreciated.
I'm using Eclipse and the wsdl is SOAP.
JDK 6 comes with jax-ws, everything you need to develop a client for a web service.
I'm unable to find some simple enough examples to post , but start at https://jax-ws.dev.java.net/
Edit: here's a simple example - a client for this web service: http://xmethods.com/ve2/ViewListing.po?key=427565
C:\temp> md generated
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\wsimport -keep -d generated http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl
Create PrimeClient.java which look like:
import javax.xml.ws.WebServiceRef;
import com.microsoft.webservices.*;
//the above namespace is from the generated code from the wsdl.
public class PrimeClient {
//Cant get this to work.. #WebServiceRef(wsdlLocation="http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl")
static PrimeNumbers service;
public static void main(String[] args) {
try {
service = new PrimeNumbers();
PrimeClient client = new PrimeClient();
client.doTest(args);
} catch(Exception e) {
e.printStackTrace();
}
}
public void doTest(String[] args) {
try {
System.out.println("Retrieving the port from the following service: " + service);
PrimeNumbersSoap pm = service.getPrimeNumbersSoap();
System.out.println("Invoking the getPrimeNumbersSoap operation ");
System.out.println(pm.getPrimeNumbers(100));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Compile and run:
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\javac -cp generated PrimeClient.java
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\java -cp .;generated PrimeClient
Retrieving the port from the following service: com.microsoft.webservices.PrimeN
umbers#19b5393
Invoking the getPrimeNumbersSoap operation
1,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
There are plugins for IDE's which generate the needed code to consume a web service for you.
After the plugin generates you the base methods you simply call a web service like that:
TransportServiceSoap service = new TransportServiceLocator().getTransportServiceSoap();
service.getCities();
Have a look at http://urbas.tk/index.php/2009/02/20/eclipse-plug-in-as-a-web-service-client/
There are three ways to write a web service client
Dynamic proxy
Dynamic invocation interface (DII)
Application client
Example for Dynamic Proxy Client
import java.net.URL;
import javax.xml.rpc.Service;
import javax.xml.rpc.JAXRPCException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceFactory;
import dynamicproxy.HelloIF;
public class HelloClient {
public static void main(String[] args) {
try {
String UrlString = "Your WSDL URL"; //
String nameSpaceUri = "urn:Foo";
String serviceName = "MyHelloService";
String portName = "HelloIFPort";
System.out.println("UrlString = " + UrlString);
URL helloWsdlUrl = new URL(UrlString);
ServiceFactory serviceFactory =
ServiceFactory.newInstance();
Service helloService =
serviceFactory.createService(helloWsdlUrl,
new QName(nameSpaceUri, serviceName));
dynamicproxy.HelloIF myProxy =
(dynamicproxy.HelloIF)
helloService.getPort(
new QName(nameSpaceUri, portName),
dynamicproxy.HelloIF.class);
System.out.println(myProxy.sayHello("Buzz"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I hope , this would solve your question.
The easiest I've found so far to use is the Idea IntelliJ wizard which - using Metro libraries - generate a very small code snippet which works fine with Java 6.