iocp.setPresolve(GLPKConstants.GLP_ON); rises an error - java

Here is my code :
public void solve(String[] arg) throws FileNotFoundException {
glp_prob lp = null;
glp_tran tran;
glp_iocp iocp;
String fname;
//String res = null;
int skip = 0;
int ret;
// listen to callbacks
GlpkCallback.addListener(this);
// listen to terminal output
GlpkTerminal.addListener(this);
fname = new String(arg[0]);
System.out.println(fname);
lp = GLPK.glp_create_prob();
System.out.println("Problem created");
tran = GLPK.glp_mpl_alloc_wksp();
ret = GLPK.glp_mpl_read_model(tran, fname, skip);
if (ret != 0) {
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
System.out.println(ret);
throw new RuntimeException("Model file not found: " + fname);
}
// generate model
GLPK.glp_mpl_generate(tran, null);
// build model
GLPK.glp_mpl_build_prob(tran, lp);
// set solver parameters
iocp = new glp_iocp();
GLPK.glp_init_iocp(iocp);
iocp.setPresolve(GLPKConstants.GLP_ON);
// do not listen to output anymore
GlpkTerminal.removeListener(this);
// solve model
ret = GLPK.glp_intopt(lp, iocp);
// postsolve model
if (ret == 0) {
GLPK.glp_mpl_postsolve(tran, lp, GLPKConstants.GLP_MIP);
write_lp_solution(lp);
}
// free memory
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
// do not listen for callbacks anymore
GlpkCallback.removeListener((GlpkCallbackListener) this);
// check that the hook function has been used for terminal output.
if (!hookUsed) {
System.out.println("Error: The terminal output hook was not used.");
System.exit(1);
}
}
when i run it i have this error :
Exception in thread "main" java.lang.UnsatisfiedLinkError: org.gnu.glpk.GLPKJNI.GLP_USE_AT_get()I
at org.gnu.glpk.GLPKJNI.GLP_USE_AT_get(Native Method)
at org.gnu.glpk.GLPKConstants.<clinit>(GLPKConstants.java:74)
at glpk.Optimisation.solve(Optimisation.java:58)
The line 58 corresponds to
iocp.setPresolve(GLPKConstants.GLP_ON);
This code worked well before but since i changed the model to be solved i have this error.
But when i run it with my terminal
glpsol --model -mymodel.mod
All works well, the linear problem is solved.
I have to admit that i have no idea from where this error comes.
If anyone can help me...

Looks like the JNI library is missing in the classpath. Have a look at http://glpk-java.sourceforge.net/architecture.html.

Related

execute julia scripts from Java

I'm coding Julia script with ZeroMQ.
My goal is to communicate with ZMQ between two scripts. Here is an example:
# script1
using ZMQ
ctx = ZMQ.Context()
sockDealer = ZMQ.Socket(ctx, DEALER)
ZMQ.set_identity(sockDealer, "idA")
ZMQ.connect(sockDealer, "tcp://localhost:5555")
ZMQ.send(sockDealer, "hello world!")
ZMQ.close(sockDealer)
ZMQ.close(ctx)
#script2
using ZMQ
function pollrecv(socket::ZMQ.Socket,zmsg::Message)
rc = -1
while true
rc = ccall((:zmq_msg_recv, ZMQ.zmq), Cint, (Ptr{Message}, Ptr{Void}, Cint),
&zmsg, socket.data, ZMQ.ZMQ_DONTWAIT)
if rc == -1
# Base.Libc.EAGAIN = 11
# Problem unsolved: Failure to find Base.Libc.EAGAIN
if !(ZMQ.zmq_errno() == 11)
throw(ZMQ.StateError(ZMQ.jl_zmq_error_str()))
end
return false
else
ZMQ.get_events(socket) != 0 && notify(socket)
break
end
end
return true
end
ctx = ZMQ.Context()
sockRouter = ZMQ.Socket(ctx, ROUTER)
ZMQ.bind(sockRouter, "tcp://*:5555")
fini = false
while !fini
println("listening...")
idSock = Message()
while pollrecv(sockRouter, idSock)
msg = ZMQ.recv(sockRouter)
println("msg recv: " * bytestring(msg))
fini = true
end
sleep(1)
end
ZMQ.close(sockRouter)
ZMQ.close(ctx)
I can execute them with Julia on the command prompt. Everything goes fine. Script 2 can receive the message of Script 1.
Now, I need to execute them from Java. Meaning that I need to create a java project which is just like a controller. Here is my Java project:
public class Container {
private Vector<String[]> commands;
public Container() {
this.commands = new Vector<String[]>();
}
public void addCommand(String[] strs) {
this.commands.addElement(strs);
}
public void execute() {
for(int i = 0; i < this.commands.size(); i++) {
try {
Process p = Runtime.getRuntime().exec(this.commands.get(i));
if(p.waitFor() != 0){
System.err.println("exit value = " + p.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while((line = in.readLine()) != null){
stringBuffer.append(line + "-");
}
System.out.println(stringBuffer.toString());
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch(InterruptedException e){
System.err.println(e);
}
}
}
}
//main
public class Main {
public static void main(String[] args) {
Container c = new Container();
String[] script1 = {"/usr/bin/julia", "/home/thomas/Julia/script1.jl"};
String[] script2 = {"/usr/bin/julia", "/home/thomas/Julia/script2.jl"};
c.addCommand(script1);
c.addCommand(script2);
c.execute();
}
}
However, when I run my java project, I can see that it keeps running but I can't see anything on the console: no result, no message, no error.
I think there is something wrong in my java project.
You'll want to run the two scripts concurrently: script2 is the server script, so it should be running when you run script1. As it is now, Process.waitFor() will wait for script1, the client script, to complete, before executing the server script script2 in the next for iteration.
You could start them as such:
String[] clientScript = { "/usr/bin/julia", "/home/thomas/Julia/script1.jl" };
String[] serverScript = { "/usr/bin/julia", "/home/thomas/Julia/script2.jl" };
Process server = Runtime.getRuntime().exec(serverScript);
Process client = Runtime.getRuntime().exec(clientScript);
and instantiate two threads to read their outputs:
(new ProcessReader(server)).start();
(new ProcessReader(client)).start();
using
public class ProcessReader extends Thread {
private Process p;
public ProcessReader(Process p) {
this.p = p;
}
#Override
public void run() {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {
String line;
while ((line = in.readLine()) != null) {
System.out.println("Read: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Although, since the clientScript doesn't produce any output, you could just
start the scripts, and only read the output from the server script - no thread needed.
There's one more thing to consider: the serverScript must be listening... before the clientScript attempts to connect. So you may want to do this:
Process server = Runtime.getRuntime().exec(serverScript);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
if ( in.readLine().equals("listening...") ) {
Process client = Runtime.getRuntime().exec(clientScript);
String line;
while ( (line=in.readLine()) != null )
System.out.println("Read: " + line );
}
Since this is not a specific answer to your question, this may help to you or other users that attempt to similar jobs.
JuliaCaller is an early stage library for calling Julia from Java. It executes the Julia executable as a Java process and runs a script in the Julia side. This script opens a TCP server that listens on a given port number. Every command, statement or expression sent from Java is then executed and results are sent back to Java in JSON format.
This library also implements the standard javax.script interface, that means, Julia libraries, functions, and programs can run like a scripting language that is implemented in Java (mimics).
Here is the example:
Constants.setProperties(Constants.JULIA_PATH, "/usr/local/bin/julia");
Constants.setProperties(Constants.JULIA_PORT, "8001");
// Creating a scripting interface for Julia
manager = new ScriptEngineManager();
engine = manager.getEngineByName("Julia");
// Sending command 'a = 3' to Julia from Java
engine.eval("a = 3");
// Handling the result in Java
Object a = engine.get("a");
More examples are given in the GitHub page.
Source code with Apache License

Glpk java and .mod file

I've got a .mod file and I can run it in java(Using netbeans).
The file gets data from another file .dat, because the guy who was developing it used GUSEK. Now we need to implement it in java, but i dont know how to put data in the K constant in the .mod file.
Doesn't matter the way, can be through database querys or file reading.
I dont know anything about math programming, i just need to add values to the already made glpk function.
Here's the .mod function:
# OPRE
set K;
param mc {k in K};
param phi {k in K};
param cman {k in K};
param ni {k in K};
param cesp;
param mf;
var x {k in K} binary;
minimize custo: sum {k in K} (mc[k]*phi[k]*(1-x[k]) + cman[k]*phi[k]*x[k]);
s.t. recursos: sum {k in K} (cman[k]*phi[k]*x[k]) - cesp <= 0;
s.t. ocorrencias: sum {k in K} (ni[k] + (1-x[k])*phi[k]) - mf <= 0;
end;
And here's the java code:
package br.com.genera.service.otimi;
import org.gnu.glpk.*;
public class Gmpl implements GlpkCallbackListener, GlpkTerminalListener {
private boolean hookUsed = false;
public static void main(String[] arg) {
String[] nomeArquivo = new String[2];
nomeArquivo[0] = "C:\\PodaEquipamento.mod";
System.out.println(nomeArquivo[0]);
GLPK.glp_java_set_numeric_locale("C");
System.out.println(nomeArquivo[0]);
new Gmpl().solve(nomeArquivo);
}
public void solve(String[] arg) {
glp_prob lp = null;
glp_tran tran;
glp_iocp iocp;
String fname;
int skip = 0;
int ret;
// listen to callbacks
GlpkCallback.addListener(this);
// listen to terminal output
GlpkTerminal.addListener(this);
fname = arg[0];
lp = GLPK.glp_create_prob();
System.out.println("Problem created");
tran = GLPK.glp_mpl_alloc_wksp();
ret = GLPK.glp_mpl_read_model(tran, fname, skip);
if (ret != 0) {
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
throw new RuntimeException("Model file not found: " + fname);
}
// generate model
GLPK.glp_mpl_generate(tran, null);
// build model
GLPK.glp_mpl_build_prob(tran, lp);
// set solver parameters
iocp = new glp_iocp();
GLPK.glp_init_iocp(iocp);
iocp.setPresolve(GLPKConstants.GLP_ON);
// do not listen to output anymore
GlpkTerminal.removeListener(this);
// solve model
ret = GLPK.glp_intopt(lp, iocp);
// postsolve model
if (ret == 0) {
GLPK.glp_mpl_postsolve(tran, lp, GLPKConstants.GLP_MIP);
}
// free memory
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
// do not listen for callbacks anymore
GlpkCallback.removeListener(this);
// check that the hook function has been used for terminal output.
if (!hookUsed) {
System.out.println("Error: The terminal output hook was not used.");
System.exit(1);
}
}
#Override
public boolean output(String str) {
hookUsed = true;
System.out.print(str);
return false;
}
#Override
public void callback(glp_tree tree) {
int reason = GLPK.glp_ios_reason(tree);
if (reason == GLPKConstants.GLP_IBINGO) {
System.out.println("Better solution found");
}
}
}
And i'm getting this in the console:
Reading model section from C:\PodaEquipamento.mod...
33 lines were read
Generating custo...
C:\PodaEquipamento.mod:24: no value for K
glp_mpl_build_prob: invalid call sequence
Hope someone can help, thanks.
The best way would be to read the data file the same way you read the modelfile.
ret = GLPK.glp_mpl_read_data(tran, fname_data, skip);
if (ret != 0) {
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
throw new RuntimeException("Data file not found: " + fname_data);
}
I resolved just copying the data block from the .data file into the .mod file.
Anyway,Thanks puhgee.

How to access file path with spaces from command prompt in Java

I am trying to run a batch file from a Java program.
For instance: I have a batch "abc.bat" in a folder in "Program Files".
I want to execute this batch from my Java Program. I am using CommandLine class, Commons-exec jar.
CommandLine cmdLine = CommandLine.parse("cmd");
cmdLine.addArgument("/c start \"\" \"C:\\Program Files\\abc.bat\"");
DefaultExecutor exec = new DefaultExecutor();
Process p = Runtime.getRuntime().exec(cmdLine.toString());
exec.execute(cmdLine);
The above code throws an error saying "Windows cant find the file. Make sure you typed the name correctly, and try again". And, that is because of the spaces in the path.
So, I tried the answer provided here by #brso05 and that works. But I want it to be in a Future Class. Please find my code below and help me fix it.
final CommandLine cmdLine = CommandLine.parse("cmd.exe");
cmdLine.addArgument("/c");
cmdLine.addArgument("start");
cmdLine.addArgument("\""+ batchFileExecute.getParent().toString() + "\"");
ExecutorService es = Executors.newFixedThreadPool(1);
Future<?> future = es.submit(new Runnable() {
public void run() {
DefaultExecutor exec = new DefaultExecutor();
try {
Process p = Runtime.getRuntime().exec(cmdLine.toString());
exec.execute(cmdLine);
System.out.println(p.waitFor());
}
catch (IOException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
String thread_status = null;
try
{
thread_status = future.get().toString();
System.out.println(thread_status+" completed the execution");
}
catch (NullPointerException e)
{
System.out.println("The execution of the received project is complete.");
// In here I want to do some processing again.
}
The code I mentioned works but it doesnt work if my batch file has a spaces in the path. Can you help me fix this?
Becuase the snippet you've given works but then I cant put it into Future. It doesnt work in the desired manner.
Thanks in advance!
This is an alternative way:
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start \"\" \"C:\\Program Files\\abc.bat\"");
Have you tried with single quotes? According to this, it should work.
I had the same filenames with spaces issue while using ImageMagick. Here is the code to solve the issue:
String imageOutput = null;
ByteArrayOutputStream identifyStdout = new ByteArrayOutputStream();
ByteArrayOutputStream identifyStderr = new ByteArrayOutputStream();
try
{
DefaultExecutor identifyExecutor = new DefaultExecutor();
// End the process if it exceeds 60 seconds
ExecuteWatchdog identifyWatchdog = new ExecuteWatchdog(60000);
identifyExecutor.setWatchdog(identifyWatchdog);
PumpStreamHandler identifyPsh = new PumpStreamHandler(identifyStdout, identifyStderr);
identifyExecutor.setStreamHandler(identifyPsh);
identifyExecutor.setExitValue(0); //0 is success
CommandLine identifyCommandline = new CommandLine("identify");
identifyCommandline.addArgument(destFile.getAbsolutePath(), false);
DefaultExecuteResultHandler identifyResultHandler = new DefaultExecuteResultHandler();
identifyExecutor.execute(identifyCommandline, identifyResultHandler);
identifyResultHandler.waitFor();
if (identifyResultHandler.getExitValue() != 0)
{
String output = identifyStdout.toString();
_logger.debug("Standard Out = " + output);
_logger.debug("Standard Err = " + identifyStderr.toString());
String msg = "ImageMagick overlay encountered an error. ImageMagick returned a value of " + identifyResultHandler.getExitValue();
throw new Exception(msg);
}
else
{
imageOutput = identifyStdout.toString();
_logger.debug("Standard Out = " + imageOutput);
identifyStdout.close();
identifyStderr.close();
}
}
catch(Exception e)
{
_logger.debug("Error: " + e.getLocalizedMessage(), e);
}
finally
{
identifyStdout.close();
identifyStderr.close();
}
The important part here is:
identifyCommandline.addArgument(destFile.getAbsolutePath(), false);
This line allows a filepath with spaces to process correctly.
When using the CommandLine class addArgument method without defining the boolean handleQuoting, it will set handleQuoting to true for you, basically adding quotes to the argument. This is the method invoking:
public CommandLine addArgument(String argument) {
return this.addArgument(argument, true);
}
public CommandLine addArgument(String argument, boolean handleQuoting) {
if (argument == null) {
return this;
} else {
if (handleQuoting) {
StringUtils.quoteArgument(argument);
}
this.arguments.add(new Argument(argument, handleQuoting));
return this;
}
}
Changing my method from:
CommandLine cmd = new CommandLine("pdfinfo");
cmd.addArgument("-box");
cmd.addArgument(pdfFile.getAbsolutePath());
To:
CommandLine cmd = new CommandLine("pdfinfo");
cmd.addArgument("-box");
cmd.addArgument(pdfFile.getAbsolutePath(), false); <-- change here
Solved the issue for me. No quotes were added and the CommandLine was able to find the file.

Java blocks after calling runtime.exec()

First some code:
Runtime runtime = Runtime.getRuntime();
String args[] = new String[2];
// args[0] = "/bin/bash";
// args[1] = "-c";
// args[2] = "/usr/bin/rpm2cpio "+archiveFile.getCanonicalPath()+" | /bin/cpio -idmv";
args[0] = "/usr/bin/rpm2cpio";
args[1] = archiveFile.getCanonicalPath();
Process rpm2cpioProcess = runtime.exec(args, null, dir);
// System.out.println("started rpm2cpio");
String args2[] = new String[3];
args2[0] = "/bin/cpio";
args2[1] = "-idmu";
args2[2] = "--quiet";
Process cpioProcess = runtime.exec(args2, null, dir);
// System.out.println("started cpio");
InputStream fromRpm2cpio = rpm2cpioProcess.getInputStream();
new ProcessInputStreamer(rpm2cpioProcess.getErrorStream());
OutputStream fromCpio = cpioProcess.getOutputStream();
new PipedStreamer(fromRpm2cpio, fromCpio);
new ProcessInputStreamer(cpioProcess.getErrorStream());
// System.out.println("pipe created");
while(cpioProcess!=null && fromRpm2cpio!=null) {
boolean doSleep = true;
// System.out.println("waking up");
if (cpioProcess!=null) {
try {
if (cpioProcess.exitValue()==0) {
cpioProcess = null;
doSleep = false;
}
} catch(IllegalThreadStateException e) {
}
}
if (rpm2cpioProcess!=null) {
try {
if (rpm2cpioProcess.exitValue()==0) {
rpm2cpioProcess = null;
doSleep = false;
}
} catch(IllegalThreadStateException e) {
}
}
if (doSleep) {
Thread.sleep(30);
}
// System.out.println("still running");
}
I'm trying to extract the content of an rpm archive. This code works fine after multiple modifications. My first attempt was to execute the next code through Java:
/bin/bash -c '/usr/bin/rpm2cpio <archive-file> | /bin/cpio -idmv'
Which worked fine the first time I ran it (you can see it in the code commented above). The second time I ran the code it got blocked since the extracted files already existed. So I thought maybe it has to do with the piping and thus split the call into two separate processes. This didn't help much either. So I then modified the arguments of the /bin/cpio from '-idmv' to '-idmu --quiet' and now it works. Unfortunately the -u option overwrites existing files 'unconditionally' which is not really needed. My question is why does it block with -idmv and why doesn't it block with -idmu ?
It could be waiting on standard input for some inputs. Redirect your standard input and/or output to /dev/null
I'd guess that your ProcessInputStreamer and/or PipedStreamer implement Runnable or extent Thread and you're not running them anywhere.

java error: Exception in thread "main" java.lang.NullPointerException

Here is code:
import java.awt.*;
import java.util.*;
import javax.media.*;
import javax.media.protocol.*;
import javax.media.control.*;
import javax.media.format.*;
public class jmfcam05v
{
DataSource dataSource;
PushBufferStream pbs;
Vector camImgSize = new Vector();
Vector camCapDevice = new Vector();
Vector camCapFormat = new Vector();
int camFPS;
int camImgSel;
Processor processor = null;
DataSink datasink = null;
public static void main(String[] args)
{
jmfcam05v jmfcam = new jmfcam05v();
}
public jmfcam05v()
{
fetchDeviceFormats();
camFPS = 30; // framerate
fetchDeviceDataSource();
createPBDSource();
createProcessor(dataSource);
startCapture();
try{Thread.sleep(20000);}catch(Exception e){} // 20 seconds
stopCapture();
}
boolean fetchDeviceFormats()
{
Vector deviceList = CaptureDeviceManager.getDeviceList(new VideoFormat(null));
CaptureDeviceInfo CapDevice = null;
Format CapFormat = null;
String type = "N/A";
CaptureDeviceInfo deviceInfo=null;boolean VideoFormatMatch=false;
for(int i=0;i<deviceList.size();i++)
{
// search for video device
deviceInfo = (CaptureDeviceInfo)deviceList.elementAt(i);
if(deviceInfo.getName().indexOf("vfw:")<0)continue;
Format deviceFormat[] = deviceInfo.getFormats();
for (int f=0;f<deviceFormat.length;f++)
{
if(deviceFormat[f] instanceof RGBFormat)type="RGB";
if(deviceFormat[f] instanceof YUVFormat)type="YUV";
if(deviceFormat[f] instanceof JPEGFormat)type="JPG";
Dimension size = ((VideoFormat)deviceFormat[f]).getSize();
camImgSize.addElement(type+" "+size.width+"x"+size.height);
CapDevice = deviceInfo;
camCapDevice.addElement(CapDevice);
//System.out.println("Video device = " + deviceInfo.getName());
CapFormat = (VideoFormat)deviceFormat[f];
camCapFormat.addElement(CapFormat);
//System.out.println("Video format = " + deviceFormat[f].toString());
VideoFormatMatch=true; // at least one
}
}
if(VideoFormatMatch==false)
{
if(deviceInfo!=null)System.out.println(deviceInfo);
System.out.println("Video Format not found");
return false;
}
return true;
}
void fetchDeviceDataSource()
{
CaptureDeviceInfo CapDevice =
(CaptureDeviceInfo)camCapDevice.elementAt(camImgSel);
System.out.println("Video device = " + CapDevice.getName());
Format CapFormat = (Format)camCapFormat.elementAt(camImgSel);
System.out.println("Video format = " + CapFormat.toString());
MediaLocator loc = CapDevice.getLocator();
try
{
dataSource = Manager.createDataSource(loc);
}
catch(Exception e){}
try
{
FormatControl formCont=((CaptureDevice)dataSource).getFormatControls()[0];
VideoFormat formatVideoNew = new
VideoFormat(null,null,-1,null,(float)camFPS);
formCont.setFormat(CapFormat.intersects(formatVideoNew));
}
catch(Exception e){}
}
void createPBDSource()
{
try
{
pbs=((PushBufferDataSource)dataSource).getStreams()[0];
}
catch(Exception e){}
}
public void createProcessor(DataSource datasource)
{
FileTypeDescriptor ftd = new FileTypeDescriptor(FileTypeDescriptor.MSVIDEO);
Format[] formats = new Format[] {new VideoFormat(VideoFormat.INDEO50)};
ProcessorModel pm = new ProcessorModel(datasource, formats, ftd);
try
{
processor = Manager.createRealizedProcessor(pm);
}
catch(Exception me)
{
System.out.println(me);
// Make sure the capture devices are released
datasource.disconnect();
return;
}
}
private void startCapture()
{
// Get the processor's output, create a DataSink and connect the two.
DataSource outputDS = processor.getDataOutput();
try
{
MediaLocator ml = new MediaLocator("file:capture.mpg");
datasink = Manager.createDataSink(outputDS, ml);
datasink.open();
datasink.start();
}catch (Exception e)
{
System.out.println(e);
}
processor.start();
System.out.println("Started saving...");
}
private void pauseCapture()
{
processor.stop();
}
private void resumeCapture()
{
processor.start();
}
private void stopCapture()
{
// Stop the capture and the file writer (DataSink)
processor.stop();
processor.close();
datasink.close();
processor = null;
System.out.println("Done saving.");
}
}
Error:
run:
Video device = vfw:Microsoft WDM Image Capture (Win32):0
Video format = YUV Video Format: Size = java.awt.Dimension[width=640,height=480] MaxDataLength = 614400 DataType = class [B yuvType = 32 StrideY = 1280 StrideUV = 1280 OffsetY = 0 OffsetU = 1 OffsetV = 3
javax.media.CannotRealizeException: Unable to provide all requested tracks
Exception in thread "main" java.lang.NullPointerException
at jmfcam05v.startCapture(jmfcam05v.java:202)
at jmfcam05v.(jmfcam05v.java:82)
at jmfcam05v.main(jmfcam05v.java:64)
please help me with this error.i am using windows vista OS.
can anyone suggest me how to store files in .3gp format?please help
Exception in thread "main" java.lang.NullPointerException
at jmfcam05v.startCapture(jmfcam05v.java:202)
Some object reference at line 202 of jmfcam05v.java, inside the startCapture() method, is null while the code is trying to access/invoke it using the dot . operator.
E.g.
SomeObject someObject = null;
someObject.doSomething(); // NullPointerException.
The solution is actually easy. Just make sure that it's not null by either instantiating it:
if (someObject == null) {
someObject = new SomeObject();
}
someObject.doSomething(); // No NPE more!
... or by simply doing a nullcheck before accessing/invoking:
if (someObject != null) {
someObject.doSomething(); // No NPE more!
}
The NPE is easy. One of the lines
MediaLocator ml = new MediaLocator("file:capture.mpg");
datasink = Manager.createDataSink(outputDS, ml);
in method startCapture throws a CannotRealizeException. So datasink is not initialized and if you try to close it later in stopCapture, it's still null and that causes the NPE.
To avoid the NPE: test, if datasink isn't null before calling a method on it.
EDIT
and could you PLEASE remove the application logic from the constructor and move it to the main method. A constructor is for constructing an object, mainly for initializing class members and nothing else. And Java classes should start with a capital letter, that helps people (and us) understanding the code.
Poor exception handling is to blame here.
Most likely, the processor member isn't getting initialized. If there isn't a processor, it looks like you can't do anything useful. So let the exception fly, terminating your doomed program at that point, instead of "swallowing" it and blithely continuing on.
Also, if you are going to eat exceptions and soldier on, at least print them properly: ex.printStackTrace(), instead of System.out.println(ex).
But it would be much better to add throws clauses to your methods, and not catch any exceptions, since you cannot recover from them.
Perhaps the Indeo codec was present on your Windows XP box, but isn't available on your Vista machine. (Update: In fact, Indeo is not supported and not compatible with Vista.) That prevents the processor from being created successfully, and your program is doomed from that point. Is there a way to test whether a particular FileTypeDescriptor or VideoFormat is valid at runtime?
It looks as though this line:
processor = Manager.createRealizedProcessor(pm);
Throws a CannotRealizeException, causing processor to be null and leading to the NPE later on. As for what that exception is thrown, that seems to have to do with your data and use of the JMF.
Generally, it's bad to use System.out.println() on exceptions because then you lose the stack trace, which is often the most important information for debugging. Instead. use exception.printStackTrace();
datasink is never being initialized.
When you try to call
datasink.close();
Its saying that datasink is null.
Make sure that your code is actually getting to and processing line #176
datasink = Manager.createDataSink(outputDS, ml);
By looking at the private void startCapture() method I guess the processor variable is NULL as this is the only stuff that is not in a try-catch block.
Remove this :
Processor processor = null;
DataSink datasink = null;
and replace with this :
Processor processor;
DataSink datasink;
This is because of createRealizedProcessor is not able to work on VedioCapture device.
Issue is with Microsoft WDM Image device.

Categories

Resources