Task succeeds but the service onSucceed method is not triggered - java

When the Task includes 2 lines opening a stream and closing it, the Task returns correctly. Its succeed method runs. But the Service' setOnSucceeded method does not run. Why?
When the 2 lines about the streaming opening and closing are commented out in the Task, we do get the expected behavior: System.out.println("in the succeed method of the Service") does print.
The Main method:
package Test;
import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
MyService pluginUpdateService = new MyService();
pluginUpdateService.setOnFailed(e -> {
System.out.println("task failed");
});
pluginUpdateService.setOnSucceeded(e -> {
System.out.println("in the succeed method of the Service"); // this does not print, when MyTask opens the stream (see code of MyTask)
});
// launching the service
if (pluginUpdateService.getState() == Worker.State.READY) {
pluginUpdateService.start();
}
}
}
The service MyService
package Test;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
public class MyService extends Service {
public MyService() {
}
#Override
protected Task createTask() {
Task updater = new MyTask();
return updater;
}
}
The task MyTask:
package Test;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javafx.concurrent.Task;
public class MyTask extends Task {
public MyTask() {
}
#Override
protected Void call() throws MalformedURLException, IOException {
InputStream in;
URL url = new URL("https://clementlevallois.net");
in = url.openStream(); // when this line is commented out, the Service does trigger its setOnSucceeded method as expected
in.close(); // when this line is commented out, the Service does trigger its setOnSucceeded method as expected
System.out.println("about to return from the call method of the Task");
return null;
}
#Override
protected void succeeded() {
super.succeeded();
System.out.println("succeeded - sent from the succeeded method of the Task");
}
#Override
protected void cancelled() {
super.cancelled();
System.out.println("cancelled");
updateMessage("Cancelled!");
}
#Override
protected void failed() {
super.failed();
System.out.println("failed");
updateMessage("Failed!");
}
}

Related

Why does Amazon SWF Workflow not cancel immediately after calling TryCatch.cancel()?

I am using the below code sample where I am calling the cancelWF method to cancel the execution of workflow. The onCatch method is successfully invoked with the RuntimeException("Simply cancel"), but on the Amazon SWF console the WF does not end immediately, it waits will timeout and ends with a WorkflowExecutionTerminated event.
The whole project is available here if you want more info.
package aws.swf;
import aws.swf.common.Constants;
import aws.swf.common.DelayRequest;
import aws.swf.common.MyActivityClient;
import aws.swf.common.MyActivityClientImpl;
import aws.swf.common.MyWorkflow;
import aws.swf.common.SWFClient;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker;
import com.amazonaws.services.simpleworkflow.flow.annotations.Asynchronous;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.flow.core.TryCatch;
import java.util.concurrent.CancellationException;
public class D_CancelWorkflow implements MyWorkflow {
private TryCatch tryCatch;
private final MyActivityClient activityClient = new MyActivityClientImpl();
#Override
public void sum() {
tryCatch = new TryCatch() {
#Override
protected void doTry() throws Throwable {
System.out.printf("[WF %s] Started exec\n", D_CancelWorkflow.this);
Promise<Integer> result = activityClient.getNumWithDelay(new DelayRequest("req1", 1));
cancelWF(result);
newDelayRequest(result);
}
#Override
protected void doCatch(Throwable e) throws Throwable {
if (e instanceof CancellationException) {
System.out.printf("[WF %s] Cancelled With message [%s]\n",
D_CancelWorkflow.this, e.getCause().getMessage());
} else {
e.printStackTrace();
}
rethrow(e);
}
};
}
#Asynchronous
private void newDelayRequest(Promise<Integer> num) {
activityClient.getNumWithDelay(new DelayRequest("req2", 1));
}
#Asynchronous
private void cancelWF(Promise<Integer> ignore) {
System.out.printf("[WF %s] Cancelling WF\n", D_CancelWorkflow.this);
this.tryCatch.cancel(new RuntimeException("Simply cancel"));
}
public static void main(String[] args) throws Exception {
AmazonSimpleWorkflow awsSwfClient = new SWFClient().getClient();
WorkflowWorker workflowWorker =
new WorkflowWorker(awsSwfClient, Constants.DOMAIN, Constants.TASK_LIST);
workflowWorker.addWorkflowImplementationType(D_CancelWorkflow.class);
workflowWorker.start();
}
}
This is the event history for one of my execution,

io.grpc.StatusRuntimeException: UNIMPLEMENTED: Method not found

Using Springboot starter app. Everything working. Then I moved the client and server to new packages. Everything compiles, but at runtime when I run the client I get an error: UNIMPLEMENTED Method not found.
I checked that the method is in fact implemented. When I start the Springboot app where do I confirm that the bean itself was loaded? I just see confirmation that the application is up and running but no list of loaded beans in log.
Here is my Springboot application. All I did was move the client and server bean into a new package called example.client and example.server. before they were in same package as spring boot com.test.MyApplication
io.grpc.StatusRuntimeException: UNIMPLEMENTED: Method not found: example.GreetingService/greetingWithResponseStream
at io.grpc.Status.asRuntimeException(Status.java:526)
at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:434)
at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
GreetingService.proto:
syntax = "proto3";
package example;
message HelloRequest {
string name = 1;
}
message HelloResponse {
string greeting = 1;
}
service GreetingService {
rpc greeting (HelloRequest) returns (HelloResponse);
rpc greetingWithResponseStream (HelloRequest) returns (stream HelloResponse);
rpc greetingWithRequestStream (stream HelloRequest) returns (HelloResponse);
rpc greetingWithRequestResponseStream (stream HelloRequest) returns (stream HelloResponse);
}
import example.GreetingServiceOuterClass;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.List;
#GrpcService
public class GreetingServiceImpl extends GreetingServiceGrpc.GreetingServiceImplBase{
#Override
public void greeting(GreetingServiceOuterClass.HelloRequest request, StreamObserver<GreetingServiceOuterClass.HelloResponse> responseObserver) {
GreetingServiceOuterClass.HelloResponse response = GreetingServiceOuterClass.HelloResponse.newBuilder()
.setGreeting("HELLO, THERE, " + request.getName())
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
#Override
public void greetingWithResponseStream(GreetingServiceOuterClass.HelloRequest request, StreamObserver<GreetingServiceOuterClass.HelloResponse> responseObserver) {
GreetingServiceOuterClass.HelloResponse response = GreetingServiceOuterClass.HelloResponse.newBuilder()
.setGreeting("(Stream Response) Hello there, " + request.getName())
.build();
responseObserver.onNext(response);
responseObserver.onNext(response);
responseObserver.onNext(response);
responseObserver.onCompleted();
}
#Override
public StreamObserver<GreetingServiceOuterClass.HelloRequest> greetingWithRequestStream(StreamObserver<GreetingServiceOuterClass.HelloResponse> responseObserver) {
return new StreamObserver<GreetingServiceOuterClass.HelloRequest>() {
private List<String> nameList = new ArrayList<>();
#Override
public void onNext(GreetingServiceOuterClass.HelloRequest request) {
nameList.add(request.getName());
}
#Override
public void onError(Throwable t) {
t.printStackTrace();
}
#Override
public void onCompleted() {
GreetingServiceOuterClass.HelloResponse response = GreetingServiceOuterClass.HelloResponse.newBuilder()
.setGreeting("(Stream Request) Hello there, " + String.join(" ", nameList))
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
};
}
#Override
public StreamObserver<GreetingServiceOuterClass.HelloRequest> greetingWithRequestResponseStream(StreamObserver<GreetingServiceOuterClass.HelloResponse> responseObserver) {
return new StreamObserver<GreetingServiceOuterClass.HelloRequest>() {
private List<String> nameList = new ArrayList<>();
#Override
public void onNext(GreetingServiceOuterClass.HelloRequest request) {
nameList.add(request.getName());
}
#Override
public void onError(Throwable t) {
t.printStackTrace();
}
#Override
public void onCompleted() {
nameList.stream()
.map(name -> GreetingServiceOuterClass.HelloResponse.newBuilder().setGreeting("(Stream Request/Response) Hello there, " + name).build())
.forEach(responseObserver::onNext);
responseObserver.onCompleted();
}
};
}
}
package example.client;
import example.GreetingServiceGrpc;
import example.GreetingServiceOuterClass;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import java.util.stream.Stream;
public class Client {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:8081")
.usePlaintext()
.build();
GreetingServiceGrpc.GreetingServiceBlockingStub stub = GreetingServiceGrpc.newBlockingStub(channel);
GreetingServiceOuterClass.HelloRequest request = GreetingServiceOuterClass.HelloRequest.newBuilder().setName("Steve").build();
GreetingServiceOuterClass.HelloResponse response = stub.greeting(request);
System.out.println(response);
}
public static class RequestStreamClient {
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:8081")
.usePlaintext()
.build();
GreetingServiceGrpc.GreetingServiceStub stub = GreetingServiceGrpc.newStub(channel);
StreamObserver<GreetingServiceOuterClass.HelloRequest> requestStream =
stub.greetingWithRequestStream(new StreamObserver<GreetingServiceOuterClass.HelloResponse>() {
#Override
public void onNext(GreetingServiceOuterClass.HelloResponse response) {
System.out.println(response);
}
#Override
public void onError(Throwable t) {
t.printStackTrace();
}
#Override
public void onCompleted() {
}
});
Stream.of("Steve1", "Steve2", "Steve3")
.map(name -> GreetingServiceOuterClass.HelloRequest.newBuilder().setName(name).build())
.forEach(requestStream::onNext);
requestStream.onCompleted();
}).start();
Thread.sleep(10000);
}
}
}
#SpringBootApplication javadoc states:
This is a convenience annotation that is equivalent to declaring
#Configuration, #EnableAutoConfiguration and #ComponentScan.
And #ComponentScan javadoc states:
If specific packages are not defined, scanning will occur from the
package of the class that declares this annotation.
This means that by default the #SpringBootApplication annotation scans all classes in the same package or below (see the best practices on structuring your code in Spring Boot application).
But if you do not want to move your classes, you can import them explicitly, using the #ComponentScan or #Import annotations on the main class:
#SpringBootApplication
#ComponentScan({"example.client","example.server"})
#Import(GreetingServiceImpl.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

spring batch restart job starts from initial stage instead of where it left off?

I want to implement the functionality of restart job to start it from initial sage. I am facing two issues.
First Problem: When I restart the job very first time it will create a new job instance id and behave like a fresh job. In the second time, it will restart and run with same job instance id. (I sent the execution id from rest controller)
Second Problem: It will start from the initial stage when I will restart it.
Custom Reader:
package com.orange.alc.dabekdataload.reader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.AfterStep;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
import com.orange.alc.dabekdataload.constants.PostalHeader;
import com.orange.alc.dabekdataload.dto.PostalDto;
#Component("itemReader")
#Scope(value = "step", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class PostalReader implements ItemReader<PostalDto>, ItemStream{
private static final Logger LOGGER = LoggerFactory.getLogger(PostalReader.class);
#Value("#{jobParameters[fullPathFileName]}")
public String fileName;
private int currentIndex = 0;
private static final String CURRENT_INDEX = "current.index";
private FlatFileItemReader<PostalDto> reader;
#BeforeStep
public void beforeStep(StepExecution stepExecution) {
LOGGER.info("Executing batch reader...");
reader = new FlatFileItemReader<>();
reader.setResource(new FileSystemResource(fileName));
reader.setLinesToSkip(1);
reader.setLineMapper(new DefaultLineMapper<PostalDto>() {{
setLineTokenizer(new DelimitedLineTokenizer() {{
setNames(PostalHeader.getPostalColumnNames());
}});
setFieldSetMapper(new PostalFieldSetMapper());
}});
reader.setSaveState(true);
reader.open(stepExecution.getExecutionContext());
}
#Override
public PostalDto read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
reader.setCurrentItemCount(currentIndex++);
return reader.read();
}
#AfterStep
public void afterStep(StepExecution stepExecution) {
LOGGER.info("Closing the reader...");
reader.close();
}
#Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
if(executionContext.containsKey(CURRENT_INDEX)){
currentIndex = new Long(executionContext.getLong(CURRENT_INDEX)).intValue();
} else{
currentIndex = 0;
}
}
#Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
executionContext.putLong(CURRENT_INDEX, new Long(currentIndex).longValue());
}
#Override
public void close() throws ItemStreamException {
}
}
Job Restart Code:
#Override
public void restartJob(Long jobId) throws JobInstanceAlreadyCompleteException, NoSuchJobExecutionException, NoSuchJobException, JobRestartException, JobParametersInvalidException {
LOGGER.info("Restarting job with JobId: {}", jobId);
jobOperator.restart(jobId);
}
Please let me know in case you need any code from my side.
The delegate reader (FlatFileItemReader) used in your custom reader (PostalReader) is not honouring the ItemStream contract. You need to call open/update/close on the delegate reader in the corresponding open/update/close methods of your item reader. Something like:
public class PostalReader implements ItemReader<PostalDto>, ItemStream{
private FlatFileItemReader<PostalDto> reader;
#Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
reader.open(executionContext);
}
#Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
reader.update(executionContext);
}
#Override
public void close() throws ItemStreamException {
reader.close();
}
}
The update method from itemStream will put the exeuctionContext in current Step's execution context. But when you restart the job, the step re run as a new step and it cannot get the execution context of previous step. In order to start processing the data from where it left for restart, you need to save the state in job execution context.

Spring-batch : How to catch exception message with skip method in spring batch?

I am a novice of spring batch.
My question is how to catch exceptions with the skip method in spring-batch?
As I know, we can use a skip method to skip them when some exceptions happened in spring batch.
But how can I get the exception message with skip method?
somebody suggested me use SkipListener ,this class has three call back method like onSkipInProcess(),but it is no use for me.
And ItemProcessListener did not work either.
The code like below:(I use skip method to ignore the exception and two listeners to receive the exception info)
Step mainStep = stepBuilder.get("run")
.<ItemProcessing, ItemProcessing>chunk(5)
.faultTolerant()
.skip(IOException.class).skip(SocketTimeoutException.class)//skip IOException here
.skipLimit(2000)
.reader(reader)
.processor(processor)
.writer(writer)
.listener(stepExecListener)
.listener(new ItemProcessorListener()) //add process listener
.listener(new SkipExceptionListener()) //add skip exception listner
.build();
ItemProcessorListener like below:
//(this class implements ItemProcessListener )
{
#Override
public void beforeProcess(Object item) {
// TODO Auto-generated method stub
}
#Override
public void afterProcess(Object item, Object result) {
logger.info("invoke remote finished, item={},result={}",item,result);
}
#Override
public void onProcessError(Object item, Exception e) {
logger.error("invoke remote error, item={},exception={},{}",item,e.getMessage(),e);
}
}
SkipExceptionListener like below:
//(implements SkipListener<Object, Object>)
{
#Override
public void onSkipInRead(Throwable t) {
// TODO Auto-generated method stub
}
#Override
public void onSkipInWrite(Object item, Throwable t) {
// TODO Auto-generated method stub
}
#Override
public void onSkipInProcess(Object item, Throwable t) {
logger.info("invoke remote finished,item={},itemJsonStr={},errMsg={},e={}",
item,
JSONObject.toJSONString(item),
t.getMessage(),
t);
}
}
The issue is that all logger did not work. Actually the skip method does work well, I can get the skip count in table batch_step_execution. I am not sure these two listeners whether be callback. Who can tell me how can I do? Or is there anything else? Thanks a lot.
How to catch exception message with skip method in spring batch?
You can do that by implementing the SkipListener interface or extending the SkipListenerSupport class. All methods in the SkipListener interface have a Throwable parameter which is the exception thrown and that caused the item to be skipped. This is where you can get the exception message. Here is an example:
import java.util.Arrays;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.SkipListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableBatchProcessing
public class MyJob {
#Autowired
private JobBuilderFactory jobs;
#Autowired
private StepBuilderFactory steps;
#Bean
public ItemReader<Integer> itemReader() {
return new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
#Bean
public ItemWriter<Integer> itemWriter() {
return items -> {
for (Integer item : items) {
System.out.println("item = " + item);
}
};
}
#Bean
public ItemProcessor<Integer, Integer> itemProcessor() {
return item -> {
if (item.equals(7)) {
throw new IllegalArgumentException("Sevens are not accepted!!");
}
return item;
};
}
#Bean
public Step step() {
return steps.get("step")
.<Integer, Integer>chunk(5)
.reader(itemReader())
.processor(itemProcessor())
.writer(itemWriter())
.faultTolerant()
.skip(IllegalArgumentException.class)
.skipLimit(3)
.listener(new MySkipListener())
.build();
}
#Bean
public Job job() {
return jobs.get("job")
.start(step())
.build();
}
public static class MySkipListener implements SkipListener<Integer, Integer> {
#Override
public void onSkipInRead(Throwable t) {
}
#Override
public void onSkipInWrite(Integer item, Throwable t) {
}
#Override
public void onSkipInProcess(Integer item, Throwable t) {
System.out.println("Item " + item + " was skipped due to: " + t.getMessage());
}
}
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(MyJob.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job job = context.getBean(Job.class);
jobLauncher.run(job, new JobParameters());
}
}
In this example, MySkipListener implements SkipListener and gets the message from the exception as you are trying to do. The example reads numbers from 1 to 10 and skips number 7. You can run the main method and should see the following output:
item = 1
item = 2
item = 3
item = 4
item = 5
item = 6
item = 8
item = 9
item = 10
Item 7 was skipped due to: Sevens are not accepted!!
I hope this helps.
I couldn't get it to work either with implementing SkipListener (would be nice to know why) but in the end I went with the annotation way which is only briefly mentioned in the docs. Also somebody had a similar issue here using the implementation method (question) and the guy in the answer uses this annotation method instead of implementing the interface.
Example bean:
#Component
public class CustomSkippedListener {
#OnSkipInRead
public void onSkipInRead(Throwable throwable) {
}
#OnSkipInWrite
public void onSkipInWrite(FooWritingDTO fooWritingDTO, Throwable throwable) {
LOGGER.info("balabla" + throwable.getMessage());
}
#OnSkipInProcess
public void onSkipInProcess(FooLoaderDTO fooLoaderDTO, Throwable throwable) {
LOGGER.info("blabla" + throwable.getMessage());
}
private static final Logger LOGGER = LoggerFactory.getLogger(CustomSkippedListener.class);
}
then autowire and include in the step chain as you did.

Asterisk + asterisk-java listen new channels

Asterisk 11.4.0
Asterisk-java: 1.0.0.CI-SNAPSHOT
I've try to run this code:
import org.asteriskjava.live.AsteriskChannel;
import org.asteriskjava.live.AsteriskQueue;
import org.asteriskjava.live.AsteriskQueueEntry;
import org.asteriskjava.live.internal.AsteriskAgentImpl;
import org.asteriskjava.live.AsteriskServer;
import org.asteriskjava.live.AsteriskServerListener;
import org.asteriskjava.live.DefaultAsteriskServer;
import org.asteriskjava.live.ManagerCommunicationException;
import org.asteriskjava.live.MeetMeRoom;
import org.asteriskjava.live.MeetMeUser;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
public class HelloLiveEverything implements AsteriskServerListener, PropertyChangeListener
{
private AsteriskServer asteriskServer;
public HelloLiveEverything()
{
asteriskServer = new DefaultAsteriskServer("localhost", "manager", "password");
}
public void run() throws ManagerCommunicationException
{
// listen for new events
asteriskServer.addAsteriskServerListener(this);
// add property change listeners to existing objects
for (AsteriskChannel asteriskChannel : asteriskServer.getChannels())
{
System.out.println(asteriskChannel);
asteriskChannel.addPropertyChangeListener(this);
}
}
public void onNewAsteriskChannel(AsteriskChannel channel)
{
System.out.println(channel);
channel.addPropertyChangeListener(this);
}
public void onNewMeetMeUser(MeetMeUser user)
{
System.out.println(user);
user.addPropertyChangeListener(this);
}
public void onNewQueueEntry(AsteriskQueueEntry user)
{
System.out.println(user);
user.addPropertyChangeListener(this);
}
public void onNewAgent(AsteriskAgentImpl user)
{
System.out.println(user);
user.addPropertyChangeListener(this);
}
public void propertyChange(PropertyChangeEvent propertyChangeEvent)
{
System.out.println(propertyChangeEvent);
}
public static void main(String[] args) throws Exception
{
HelloLiveEverything helloLiveEverything = new HelloLiveEverything();
helloLiveEverything.run();
while (true) {
}
}
}
When executed, connectios is OK. This code show me current channels but never show me new channels when callers make a calls.
I need to catch the events when new asterisk channels are opening.
What I made wrong?
Thank you
Try This:
Your Class HelloLiveEverything should implement ManagerEventListener
then override the onManagerEvent method
#Override
public void onManagerEvent(ManagerEvent event) {
String event_name = event.getClass().getSimpleName();
if (event_name.equals("DialEvent")) {
DialEvent e = (DialEvent) event;
System.out.println(e.getCallerIdNum());//caller number
System.out.println(e.getDestination());//Called number
//do something here
}
}
edit asterisk manager.conf :
[manager]
secret = password
deny=0.0.0.0/0.0.0.0
permit=209.16.236.73/255.255.255.0; change this ip with one your java app is using permit=127.0.0.1/255.255.255.0
read = system,call,log,verbose,command,agent,user,originate; add full permission
write = system,call,log,verbose,command,agent,user,originate; add full permission

Categories

Resources