RED5 AXIS camera capturing & streaming - java

I want to capture an AXIS camera & stream it. I am quite new to RED5. I get the following error:
Exception in thread "main" java.lang.NullPointerException at
org.vikulin.rtmp.publisher.Publisher2.packetReceived(Publisher2.java:23)
at
org.red5.server.presentation.output.flv.FLVStream.dispatchEvent(FLVStream.java:243)
at
org.red5.server.presentation.output.flv.FLVStream.sendAVCDecoderConfig(FLVStream.java:162)
at
org.red5.server.presentation.output.flv.FLVStream.addEvent(FLVStream.java:76) at
org.red5.server.presentation.MediaPresentation.onMediaEvent(MediaPresentation.java:43)
at
org.red5.server.presentation.input.avp.codecs.H264.addPacket(H264.java:206)
at
org.red5.server.presentation.RTSPStream.onRTSPEvent(RTSPStream.java:100)
at
org.red5.server.net.rtsp.proxy.RtspTcp.setupAndPlay(RtspTcp.java:287)
at org.red5.server.presentation.RTSPStream.onSDP(RTSPStream.java:138)
at
org.red5.server.net.rtsp.proxy.RtspTcp.parseDescription(RtspTcp.java:128)
at org.red5.server.net.rtsp.proxy.RtspTcp.describe(RtspTcp.java:64)
at
org.red5.server.presentation.RTSPStream.startInput(RTSPStream.java:77)
at org.red5.server.presentation.RTSPStream.start(RTSPStream.java:82)
at org.vikulin.rtmp.publisher.Publisher2.main(Publisher2.java:49)
Here is the code:
import java.io.IOException;
import org.red5.server.api.stream.IBroadcastStream;
import org.red5.server.api.stream.IStreamListener;
import org.red5.server.api.stream.IStreamPacket;
import org.red5.server.net.rtmp.event.VideoData;
import org.red5.server.presentation.RTSPStream;
import org.red5.server.stream.message.RTMPMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Publisher2 implements IStreamListener {
PublishClient client;
#Override
public void packetReceived(IBroadcastStream arg0, IStreamPacket arg1) {
System.out.println("" + arg1);
VideoData data = new VideoData(arg1.getData());
RTMPMessage message = RTMPMessage.build(data);
try {
client.pushMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
Logger log = LoggerFactory.getLogger(Publisher2.class);
String publishName = "testb";
String host = "127.0.0.1";
int port = 1935;
String app = "live";
PublishClient client = new PublishClient();
client.setHost(host);
client.setPort(port);
client.setApp(app);
client.start(publishName, "live", null);
while (client.getState() != PublishClient.PUBLISHED) {
Thread.sleep(500);
}
Publisher2 test = new Publisher2();
final RTSPStream camera = new RTSPStream("192.168.254.115", 554,
"rtsp://192.168.254.115/axis-media/media.amp?videocodec=h264&videokeyframeinterval=30&fps=30");
camera.addStreamListener(test);
new Thread(new Runnable() {
#Override
public void run() {
camera.start();
}
}).start();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
camera.stop();
try {//wait for write out.
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.stop();
}
}
If you have any idea please help me!

You declared a client variable in your main method, but in your packetReceived method, you reference the class variable. The class variable is still null at that point. So, possibly change this line:
PublishClient client = new PublishClient();
to this:
client = new PublishClient();
or pass the client in to your method, and remove variable declaration from your class.

Related

How to send a String via Telnet?

I want to send a String to a Telnet Connection using TelnetConnection from Apache
import java.io.IOException;
import org.apache.commons.net.telnet.TelnetClient;
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
String telnetServer = "123.456.789.123";
int telnetPort = 32106;
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(telnetServer, telnetPort);
String start = "start";
telnet.getOutputStream().write(start.getBytes());
telnet.getOutputStream().flush();
System.out.println(telnet.getInputStream());
} catch (Exception e) {
System.out.println(e);
}finally {
telnet.disconnect();
}
}
}
However, I don't get a result. How do I use Input and Output Stream in this case?
The command ("start") should start the recording of METUS INGEST 5.6.
Thanks to Some programmer dude(https://stackoverflow.com/users/440558/some-programmer-dude). This totally did the job.
Here is the complete code:
import java.io.IOException;
import org.apache.commons.net.telnet.TelnetClient;
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
String telnetServer = "123.456.789.123";
int telnetPort = 32106;
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(telnetServer, telnetPort);
String start = "start\r\n";
telnet.getOutputStream().write(start.getBytes());
telnet.getOutputStream().flush();
System.out.println(telnet.getInputStream());
} catch (Exception e) {
System.out.println(e);
}finally {
telnet.disconnect();
}
}
}
You can stop the recording of all sources with:
String stop = "stop\r\n";
telnet.getOutputStream().write(stop.getBytes());
telnet.getOutputStream().flush();

Sending a String through socket. Server not receiving it

I've been struggling lately to find a way to deliver strings through a socket file. I'm planning to create a remote tool(client) to execute things based on the received message(server).
I've searched answers for my problem on google and i found some things and managed to understand things but I also got some problems (i'm new to programming, not yet in college).
I would appreciate any help in this matter
SocketService.java ---- class file = serverside
package socket;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
public class ServiceSocket {
static ServerSocket myService;
static Socket thesocket;
static Thread socketThread;
public static boolean socketRunning;
public static DataInputStream socketMessage;
public static void initialise(String localhost, int portNumber ){
// make a server socket//////
try {
myService = new ServerSocket(portNumber);
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
//////////////////////////////
}
public static void deploySocket(){
socketThread = new Thread() {
public void run(){
// making connection
System.out.println("VVaiting for connection...");
try {
thesocket = myService.accept();
System.out.println("Connection made");
socketRunning = true;
} catch (IOException e) {
e.printStackTrace();
}
////////////////////////////////////
try {
StartBrain();
} catch (IOException e1) {
e1.printStackTrace();
}
if(socketRunning = false) {
try {
thesocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
socketThread.start();
}
public static String getSocketMessage() throws IOException {
try {
socketMessage = new DataInputStream(thesocket.getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
boolean looprunning = true;
String message = null;
System.out.println("entering loop");
do {
try {
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
} catch (EOFException e) {
}
}while(looprunning);
System.out.println("Message received from UTF: " + message);
System.out.println("loop exited vvith message");
if(message == null) {
message = "no message";
}
return message;
}
public static void StartBrain() throws IOException {
System.out.println("socket brain started");
String BrainMessage = getSocketMessage();
if(BrainMessage == "command") {
System.out.println("Command EXECUTED HAHA");
} else if(BrainMessage == "taskschedule") {
System.out.println("task scheduled");
} else {
System.out.println("no command received");
}
}
Main.java ----- class file = serverside
package main;
import socket.ServiceSocket;
public class Main {
public static void main(String[] args) {
ServiceSocket.initialise("localhost", 3535);
ServiceSocket.deploySocket();
}
}
}
Main.java = CLIENT
package mainPackage;
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
public class Main {
private static Socket clientSocket;
public static void sendMessage(String message) throws IOException, InterruptedException {
DataOutputStream dOut = new DataOutputStream(Main.clientSocket.getOutputStream());
dOut.writeUTF(message);
dOut.flush();
dOut.close();
}
public static void main(String[] args) throws Exception {
// String modifiedSentence;
clientSocket = new Socket("localhost", 3535);
System.out.println("Initializing");
sendMessage("command");
boolean running = true;
while(running) {
TimeUnit.SECONDS.sleep(3);
sendMessage("taskschedule");
}
clientSocket.close();
}
}
main problem
do {
try {
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
} catch (EOFException e) {
}
}while(looprunning);
it doesn't read the string/UTF
It does read it, here:
while (socketMessage.readUTF() != null) {
and then throws it away as you're not assigning the return-value to a variable, and then tries to read another one, here:
message = socketMessage.readUTF();
but the one (first) message you send is already gone.
You have problem in
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
First call to method readUTF() will block thread and read UTF string from socket, but you discard this value and try read string second time.
If you replace socketMessage.readUTF() != null with looprunning server will log this messages:
VVaiting for connection...
Connection made
socket brain started
entering loop
Message received from UTF: command
loop exited vvith message
no command received
P.S.
Command is not recognized because use compare objects (string is object) with ==, but you must use equals.
public static void StartBrain() throws IOException {
System.out.println("socket brain started");
String BrainMessage = getSocketMessage();
if (BrainMessage.equals("command")) {
System.out.println("Command EXECUTED HAHA");
} else if (BrainMessage.equals("taskschedule")) {
System.out.println("task scheduled");
} else {
System.out.println("no command received");
}
}
Server log:
VVaiting for connection...
Connection made
socket brain started
entering loop
Message received from UTF: command
loop exited vvith message
Command EXECUTED HAHA

Java RMI causes "NoSuchObjectException" [duplicate]

This question already has answers here:
java.rmi.NoSuchObjectException: no such object in table
(7 answers)
Closed 7 years ago.
I have a problem with JAVA RMI.
I have a java ee application running, which uses rmi to call specific methods, which have to be implemented specificly for each customer.
The vendor gave me an example RMI interface implementation to show how to get a specific hostinterface running.
The original codefragment looked like posted example1.
The Interface is running but every 2 to 3 days it stops working, without any known reason. The interfaces' log looks like it would be still running.
The glassfish server, which calls the interface, shows log entries like this:
[#|2015-10-01T16:27:53.446+0200|SEVERE|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=106;_ThreadName=Thread-2;|egatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
...
The application error log shows entries like this:
2015-10-05 08:44:07,819 [http-thread-pool-8080(4)] ERROR medexter.arden.server.engine.DelegatingHostInterface - The method evaluateRead on remote interface does not work correctly.
java.rmi.NoSuchObjectException: no such object in table
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
...
I found several threads like this one:
java.rmi.NoSuchObjectException: no such object in table
which tells me the garbage-collection could be responsible and the registry has to be kept statically to prevent the GC from destroying the object.
Meanwhile I tried out diffrent ways. My last one (which somehow shows my desparation - restarting the interface every 24h should not be the golden solution) is posted in example2.
At the moment I generate an executable jar file and start it as an application. I wanted to get it running as a service later on, but first it should work without any mistakes.
Does anybody hava an idea, what the reason for the described behaviour could be?
Any imporovement of the given code apprechiated. I just want to get this stuff working, without loosing connection every few days.
Thank you very much,
Martin
Example 1:
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class SampleRMIProvider {
private static RmiRegistryThread thr;
public static void main(String[] args) {
SampleRMIProvider prv = new SampleRMIProvider();
prv.init();
}
public void init(){
SampleRMIProvider.thr = new RmiRegistryThread();
thr.start();
}
public class RmiRegistryThread extends Thread {
public boolean run = true;
#Override
public void run() {
System.err.println("thread start");
String name = "RMIHostInterface";
int servicePorti = Integer.parseInt("18989");
try {
RmiHostInterface engine = new RmiHostInterfaceImpl();
RmiHostInterface stub = (RmiHostInterface) UnicastRemoteObject.exportObject(engine, 0);
Registry registry;
try {
registry = LocateRegistry.createRegistry(servicePorti);
} catch (RemoteException e) {
registry = LocateRegistry.getRegistry(servicePorti);
}
registry.bind(name, stub);
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
try {
while (this.run) {
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Example 2:
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class SampleRMIProvider extends Thread{
private static Registry r = null;
#Override
public void run() {
String name = "RMIHostInterface";
int servicePorti = Integer.parseInt("20002"); //18989
try {
RmiHostInterface engine = new SampleInterfaceImpl();
RmiHostInterface stub = (RmiHostInterface) UnicastRemoteObject.exportObject(engine, 0);
try {
SampleRMIProvider.r = LocateRegistry.createRegistry(servicePorti);
} catch (RemoteException e) {
SampleRMIProvider.r = LocateRegistry.getRegistry(servicePorti);
}
SampleRMIProvider.r.bind(name, stub);
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
System.err.println("RMI Interface created...");
try{
while(true){
Thread.sleep(10000);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
while (true) {
//RMI Interface instanzieren
SampleRMIProvider provider = new SampleRMIProvider();
provider.start();
//Ein Tag pause
Thread.sleep(86400000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
14.10.2015
Finally - this minimal example shows a solution that worked for me. Thanks for the useful advices.
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class SampleRMIProvider{
private static Registry r = null;
private static SampleHostInterfaceImpl hif = null;
private static RmiHostInterface stub = null;
SampleRMIProvider(){
try{
SampleRMIProvider.r.bind("RMIHostInterface", SampleRMIProvider.stub);
}
catch(RemoteException | AlreadyBoundException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
//setup static references to prevent from beeing collected by GC
try {
SampleRMIProvider.hif = new SampleHostInterfaceImpl();
SampleRMIProvider.stub = (RmiHostInterface) UnicastRemoteObject.exportObject(SampleRMIProvider.hif, 0);
try {
SampleRMIProvider.r = LocateRegistry.createRegistry(20002);
} catch (RemoteException e) {
SampleRMIProvider.r = LocateRegistry.getRegistry(20002);
}
} catch (RemoteException e) {
e.printStackTrace();
}
new SampleRMIProvider();
}
}
I don't know what you mean by 'no known cause', when the cause is documented in the Javadoc of the exception.
You say that you've read that the Registry reference must be static, yet you don't have a static Registry reference anywhere.
Try implementing that.

Awaitility.await().atMost(...) causes program to exit if time out interval expires?

This question regards com.jayway.awaitility.Awaitility.
I just tried Awaitility.await() and it seems to have some odd behavior.
In the test method below if I comment out testWithFuture() and enable
testWithAwaitility(), I never see the message "end " printed out.
I see 'start ', then the program just exits, and the second
print statement never seems to be reached.
So as a work around I decided to use Settable{Future}.. If anyone else has the same issue then maybe the work-around I provide will be useful.. Even better would be to get a nice answer ;^) ! thanks in advance / chris
THE CODE:
import com.google.common.util.concurrent.SettableFuture;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.SECONDS;
public class AwaitTest {
static volatile boolean done = false;
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
testWithFuture();
//testWithAwaitility();
}
private static void testWithAwaitility() {
System.out.println("start " + new Date());
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
done = true;
}
}).start();
await().atMost(2, SECONDS).until(new Callable() {
#Override
public Boolean call() throws Exception {
return done;
}
});
System.out.println("end " + new Date()); // NEVER Reached. i wonder why?
}
// This does what I want.
//
private static void testWithFuture() throws InterruptedException, ExecutionException, TimeoutException {
System.out.println("start testWithFuture");
final SettableFuture future = SettableFuture. create();
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
future.set("Hello");
}
}).start();
String result = future.get(4, TimeUnit.SECONDS);
if (! result.equals("Hello")) {
throw new RuntimeException("not equal");
} else {
System.out.println("got Hello");
}
}
}
CORRECTED CODE ->
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.SECONDS;
public class Sample {
static volatile boolean done = false;
public static void main(String[] args) {
testWithAwaitility();
}
private static void testWithAwaitility() {
System.out.println("start " + new Date());
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
done = true;
}
}).start();
try {
await().atMost(2, SECONDS).until(new Callable() {
#Override
public Boolean call() throws Exception {
return done;
}
});
} catch (Exception e) {
System.out.println("FAILED");
e.printStackTrace();
}
System.out.println("end " + new Date()); // REACHED this statement after correction
}
}
According to the documentation, await() throws a TimeoutException if the timeout is reached and the condition is not true, so your method ends at this point because the exception is propagated up through the stack. This explains the behavior. You should see a stacktrace, however.
If you want to continue executing code afterwards, it seems you would need to catch this exception.

Running xjc from java code

I am using xjc to generate classes from xsd. The generation has to happen inside the java code. Right now I have done it like this:
Process child = Runtime.getRuntime().exec(command);
try {
System.out.println("waiting...");
child.waitFor();
System.out.println("waiting ended..");
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
The output for the above program is:
waiting...
I have to use the classes after they are generated. The problem here is that the subprocess never exits and the control is never back to the java program!
Is there a way to do this without getRuntime().exec() ?
You can actually use the driver class (com.sun.tools.xjc.Driver) behind the command line tool. This worked for me:
import com.sun.tools.xjc.BadCommandLineException;
import com.sun.tools.xjc.Driver;
import com.sun.tools.xjc.XJCListener;
import org.xml.sax.SAXParseException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Generator {
public static void main(String[] args) throws BadCommandLineException, IOException {
final String targetDir = "jaxb-files";
Path path = Paths.get(targetDir);
if(!Files.exists(path)) {
Files.createDirectories(path);
}
Driver.run(new String[]{"-d", targetDir,
"D:\\dev\\onepoint\\tui\\java\\xsdjsonschema\\src\\main\\xsd\\test.xsd"}, new XJCListener() {
#Override
public void error(SAXParseException e) {
printError(e, "ERROR");
}
#Override
public void fatalError(SAXParseException e) {
printError(e, "FATAL");
}
#Override
public void warning(SAXParseException e) {
printError(e, "WARN");
}
#Override
public void info(SAXParseException e) {
printError(e, "INFO");
}
private void printError(SAXParseException e, String level) {
System.err.printf("%s: SAX Parse exception", level);
e.printStackTrace();
}
});
}
}
try this
Process child = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(
new InputStreamReader(child.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}

Categories

Resources