How to send from JAVA String(path of file) to C? - java

i want to send from java some paths to C.
For example i have a folder that have 4 subfoldes... From java i read the length of them from the code below and it returns me 4.
public static int GetLength(){File file = new File("C:\\Registrations");
File[] files = file.listFiles(new FileFilter(){
public boolean accept(File f) {
return f.isDirectory(); }});
return files.length;} }
Now with a thread i start to call the function that connect with C
public Start(){ Thread listeningThread = new Thread(new Runnable(){
public void run(){
new Match(GetDBNumber()); } });
listeningThread.start();}
So far all good. Now from MATCH(int x) class i want to call a C code and every time give the path of the Main folder each time
*PSEUDOCODE* public class Match {
public Match( int len){
System.out.println("subfolders : "+len);
for (i=0; i<len; i++)
{ //Some way call C programm (like an exe)
//with the first,second,third,fourth path
}
.... }
The C code that will recieve the path will be look like that...
int main() {
FILE *fp = fopen(FilePATH, "r");
......
......
return 0; }
I try with ProcessBuilder but i cant send the path every time with this way...
ProcessBuilder p = new ProcessBuilder();
//receive.exe is the exe that Codeblocks create after built the C code
p.command("C:\\Users\\PC\\Documents\\NetBeansProjects\\TEST\\C\\recieve.exe");
try {
p.start();
} catch (Exception e) {System.out.println("Error");
}

As stated by Eric Fitzsimmons,
you will need to use JNI to pass a String value from Java to C.
The C part will need to be in a dll that is available to the Java program.
Wikipedia has a JNI article
Oracle has an in-depth JNI write-up
Edit Concerning JNI.
If you want to send a value between Java and C,
there are only a few ways to do it.
JNI. As stated, Java Native Interface is built for this. This seems to be the best solution.
Use an external Data store. Write something to a data store (maybe a file or a database) on one side and read it on the other side (sides being Java and C).
Write a stand-alone C program that writes to standard out. Launch that program from within Java. Read what was written in java. This is not a great idea.

Depends on a lot of variables. I'll assume that you are building the C code and can change how things are passed, so...
Easiest to hardest:
Pass it in as a command line parameter (only works once per C file execution)
Write/update a text file on your hard drive that the C program can watch
Use TCP/IP and send messages over a pre-designated socket
Build as a shared library or DLL and Use JNI to call the C functions
If you were doing this professionally and this was just the beginning of a larger development effort you'd be wise to look into more professional tooling:
a message bus (Apache has one called ActiveMQ) is designed to do exactly what you are trying to do (and so much more)
a shared cache (Hazlecast can connect Java to C++ and nearly everything else and share data freely)
A shared table in a database that both languages can access.
These are much higher initial investment in time (otherwise free) but they have innumerable features that you could continue to take advantage of as your system grows.

Use jni (Java native interfaces) Make a c++ .dll file and you can easily pass information between both languages.
Good example/explanation for using jni:
https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

Related

How to call Function from an C# dll in Java?

i have a SAP-DLL to enable communication between a Programming interface and the SAP Programm.
I have following example Code for c# in combination with the dll-File:
var loggerService = LoggerService.GetLoggerService("FileLogger");
var itasProxy = SapProxyFactory.CreateSapProxy(SapSystem.Example, loggerService, "Example_User", StringExtension.CreateSecureString("Example_Password"));
var funcResult = sapProxy.SearchSapAddress(clientNo);
if (funcResult.Successfull)
{
funcResult.ReturnValue = withFormatting
? AddressFormatter.SplitStreetHouseNo(funcResult.ReturnValue)
: funcResult.ReturnValue;
}
Now i want the same functionality to be transferred to java. I have absolutely no clue how to do that. I tried the following with Loggerservice as a starter, but it doesn't work:
public class SAPConnector {
public static void main(String[] args) {
// TODO Auto-generated method stub
connectSAP();
}
public void connectSAP()
{
System.load("C://Temp//SapConnector.dll");
Object loggerService = getLoggerService("FileLogger");
}
public native Object getLoggerService(String lcLogger);
}
i just need some kind of information how to call the Functions from the dll or an example how to transfer the C# Code to working Code in Java.
Greetings,
Kevin
DLL is Microsoft format. Java is cross-platform, thus can't acknowledge anything operating-system specific, such as DLL.
One way around that is to use JNI (Java Native Interface), but that's usually not a good solution, as it makes your program platform-dependent.
Instead, I would look for a JAR from SAP, that provides a similar interface.
Maybe something along SAP JCO.
You can see some actual code examples using JCO here, and some technical information on step-by-step download and configure here.

Load java function in Lua

Simple QUESTION : Are there ways to run or load java functions inside Lua?
I am trying to create a phone application that transfers files between server and client using Lua. The server uses Java while client uses Lua.
this is a lua function that receives file
function UDPClientModule.receiveFile()
local data, status
local chunks = {}
while true do
data, status = udp:receive()
print("status: ", status)
if data ~= nil then
table.insert(chunks, data)
--the filename is the last chunk to be received
if string.match(data, ".jpg") then
-- but strangely returns true
break
end
end
socket.sleep(0.5)
end
--combineAndOpenImage(t)
end
No problems so far. However, the chunks sent by the server are encapsulated in a class like this:
public class FileChunk {
private List<Data> dataList;
//functions below
}
public class Data{
private byte[] fileData;
// functions and adding file headers below
} // then UDPServer.java sends bytes of FileChunk
Because of this, packets received by the lua function are strange which also results in string.match(data, ".jpg") returning true. So I want to run java files (eg. UDPClient.java) in order to receive and decipher the chunks, instead of lua.
I don't want to change the server nor migrate the client language to java. I haven't found any resources about this so I need help.
You would need to create a wrapper library, such as the ones in C. I do not know how, but I hope this provides you a sense of direction.

How to run a .m (matlab) file through java and matlab control?

I have 2 .m files. One is the function and the other one (read.m) reads then function and exports the results into an excel file. I have a java program that makes some changes to the .m files. After the changes I want to automate the execution/running of the .m files. I have downloaded the matlabcontrol.jar and I am looking for a way to use it to invoke and run the read.m file that then reads the function.
Can anyone help me with the code? Thanks
I have tried this code but it does not work.
public static void tomatlab() throws MatlabConnectionException, MatlabInvocationException {
MatlabProxyFactoryOptions options =
new MatlabProxyFactoryOptions.Builder()
.setUsePreviouslyControlledSession(true)
.build();
MatlabProxyFactory factory = new MatlabProxyFactory(options);
MatlabProxy proxy = factory.getProxy();
proxy.eval("addpath('C:\\path_to_read.m')");
proxy.feval("read");
proxy.eval("rmpath('C:\\path_to_read.m')");
// close connection
proxy.disconnect();
}
Based on the official tutorial in the Wiki of the project, it seems quite straightforward to start with this API.
The path-manipulation might be a bit tricky, but I would give a try to loading the whole script into a string and passing it to eval (please note I have no prior experience with this specific Matlab library). That could be done quite easily (with joining Files.readAllLines() for example).
Hope that helps something.

How to run vbscript function from java?

From java code i am able to run the vbscript by using this code
Runtime.getRuntime().exec("wscript C:\\ppt\\test1.vbs ");
But want to know how to call the method of vbscript from java..for example in test1.vbs
Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True
Set objPresentation = objPPT.Presentations.Open("C:\ppt\Labo.ppt")
Set objSlideShow = objPresentation.SlideShowSettings.Run.View
sub ssn1()
objPPT.Run "C:\ppt\Labo.ppt!.SSN"
End sub
how to call only ssn1() method from java.Otherwise can we run the macro of a power point from java code..kindly help!!
This should make you happy :) Go to the WScript section : http://technet.microsoft.com/library/ee156618.aspx
Here's my idea... in your vbscript file, make your script listen to a command line parameter that would specify which method to call. Then, in Java, you could only have to use this parameter whenever you want to call a specific method in the file.
Otherwise, if you want to access powerpoint in java, you will need to access its API like you did in vbscript, which is possible if vbscript can do it but the approach / syntax may change.
I'm not so much into the visual basic script side, but if you can expose your visual basic script as a COM object, the you can access the methods of it from java by usage of frameworks such as for example com4j:
http://com4j.java.net/
The PowerPoint application object's .Run method lets you call any public subroutine or function in any open presentation or loaded add-in
This post answers the OP's question:
Otherwise can we run the macro of a power point from java code..kindly help!!
(but does not address the original vbscript question)
There's the JACOB library, which stands for Java COM Bridge, you can find here: http://sourceforge.net/projects/jacob-project/?source=directory
With it you can invoke Excel, Word, Outlook, PowerPoint application object model methods.
I've tried this with Excel but not PowerPoint. (This is just some sample code, one might want to make it more object oriented.)
public class Excel {
private static ActiveXComponent xl = null;
public static Init() {
try {
ComThread.InitSTA();
xl = ActiveXComponent.connectToActiveInstance("Excel.Application.14");
// 14 is Office 2010, if you don't know what version you can do "Excel.Application"
if (xl==null) {
// code to launch Excel if not running:
xl = new ActiveXComponent("Excel.Application");
Dispatch.put(xl, "Visible", Constants.kTrue);
}
}
catch (Exception e) {
ComThread.Release();
}
}
public static String Run(String vbName) {
// Variant v = Dispatch.call(xl, "Run", vbName); // using string name lookup
Variant v = Dispatch.call(xl, 0x103, vbName); // using COM offset
// return Dispatch.get(this, "Name").getString();
return v.getString();
}
public static Variant Run1p(String vbName, Object param) {
// Variant v = Dispatch.call(xl, "Run", vbName, param);
return Dispatch.call(xl, 0x103, vbName, param);
// return Dispatch.get(this, "Name").getString();
}
public static Worksheet GetActiveWorksheet () {
// Dispatch d = xl.getProperty("ActiveSheet").toDispatch();
Dispatch d = Dispatch.get(xl, 0x133).toDispatch ();
return d; // you may want to put a wrapper around this...
}
}
Notes:
For Excel, at least, to get Run to invoke a VBA macro/subroutine several things have to be true:
The Excel workbook containing the macro must be "Active" (i.e. must
be the ActiveWorkbook) otherwise Run will not find the VBA subroutine. (However the workbook does not have to be
screen visible!! This means you can call a VBA Macro that is in an add-in!).
You can then pass the name of the macro using the following syntax as a string literal:
VBAProjectName.VBAModuleName.SubroutineName
For COM object invocations, you can use the name lookup version or the id number version. The id numbers come from the published COM interfaces (which you can find in C++ header files, or possibly have JACOB look them up for you).
If you successfully did the connection to Excel, be sure to call ComThread.Release() when you're done. Put it in some appropriately surrounding finally. If the process of your Java code terminates without calling it, the COM reference count on Excel will be wrong, and the Excel process will never terminate, even after you exit the Excel application. Once that happens, needless to say, Excel starts to behave screwy then (when you try to use it next, it runs but will fail to load any plug-ins/add-ons). If that happens (as it can during debugging esp. if you are bypassing finally's for better debugging) you have to use the task manager to kill the Excel process.

Using Windows API call in Java using "native"

I've tried to solve this issue by referring possible duplicates but none of them seem to be helpful.
Here's a code that I'm using to call Win API methods in Java to get current Windows User Name, and a native Windows MessageBox, but I'm getting UnsatisfiedLinkError that says that my code is unable to locate the native method I'm trying to call.
public class TestNative
{
public static void main(String[] args)
{
long[] buffer= { 128 };
StringBuffer username = new StringBuffer((int)buffer[0]);
GetUserNameA(username,buffer);
System.out.println("Current User : "+username);
MessageBoxA(0,"UserName : "+username,"Box from Java",0);
}
/** #dll.import("ADVAPI32") */
static native void GetUserNameA(StringBuffer username,long[] buffer);
/** #dll.import("USER32") */
private static native int MessageBoxA(int h,String txt,String title,int style);
}
What can be my possible (relatively simple) solution to call native Windows methods in Java. I realize that it will kill the very reason of Java being a cross-platform language, but I need to work on a project for Windows, to be developed in Java.
Thanks.
Update
As David Heffernan suggested, I've tried changing the method signature of MessageBox to MessageBoxA, but still it's not working.
I would guess it's related to the signatures not matching completely.
The GetUserName function takes two parameters: a LPTSTR and a LPDWORD. Java will likely not handle the StringBuffer acting as a TCHAR array for you.
Also, why bother using the Windows API for this? Java can probably get the user's logon name (quick google says: System.getProperty("user.name")), and Swing can make a message box (even one that looks like a Windows one).
Have you tried https://github.com/twall/jna. I have heard good things and its supposed to make jni that bit easier with many conveniences and simplifications.
Do you have a -Djava.library.path VM arg set with the path to your DLL's? Alternatively, you can have it in your system PATH.
The error is because there is no MessageBox. You presumably mean MessageBoxA.

Categories

Resources