Simple Apache Camel SNMP trap - java

I am new to Apache Camel and trying to receive a simple SNMP trap.
I have the Maven project set up with camel-core and org.apache.servicemix.bundles.snmp4j.
I have not been able to find any SNMP examples, but based on other examples I have come up with this Main class:
public class Main {
public static Processor myProcessor = new Processor() {
public void process(Exchange arg0) throws Exception {
// save to database
}
};
public static void main(String[] args) {
CamelContext context = new DefaultCamelContext();
context.addComponent("snmp", new SnmpComponent());
RouteBuilder builder = new RouteBuilder() {
public void configure() {
from("snmp:127.0.0.1:162?protocol=udp&type=TRAP").process(myProcessor);
}
};
try {
context.addRoutes(builder);
context.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
However when I run it in Eclipse as Java application it just exits after running for half a second. I was expecting it to keep running and listening to 127.0.0.1:162 ...
Any help is greatly appreciated

One way to at least pick up a trap and print to System.out is like so:
public class SNMPTrap {
private Main main;
public static void main(String[] args) throws Exception {
SNMPTrap snmpTrap = new SNMPTrap();
snmpTrap.boot();
}
#SuppressWarnings("deprecation")
public void boot() throws Exception {
main = new Main();
main.bind("snmp", new SnmpComponent());
main.addRouteBuilder(new MyRouteBuilder());
main.addMainListener(new Events());
System.out.println("Starting SNMPTrap. Use ctrl + c to terminate the JVM.\n");
main.run();
}
private static class MyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
from("snmp:127.0.0.1:162?protocol=udp&type=TRAP").process(myProcessor)
.bean("snmp");
}
}
public static Processor myProcessor = new Processor() {
public void process(Exchange trap) throws Exception {
System.out.println(trap.getIn().getBody(String.class));
// Save to DB or do other good stuff
}
};
public static class Events extends MainListenerSupport {
#Override
public void afterStart(MainSupport main) {
System.out.println("SNMPTrap is now started!");
}
#Override
public void beforeStop(MainSupport main) {
System.out.println("SNMPTrap is now being stopped!");
}
}
}
However, I get warning that Main which is part of Camel core is deprecated now.

Related

Thread at Springboot start, unable to read Property file

I am trying to execute a method in a separate thread, when the server starts. Please find my main class below:
#SpringBootApplication
#EnableSwagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor();
}
#Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
return new CommandLineRunner() {
public void run(String... args) throws Exception {
executor.execute(new CsvReader());
}
};
}
}
#Component
public class CsvReader implements Runnable{
#Value("${file-url}")
private String appUrl;
#Override
public void run() {
System.out.println("run after Object created: "+ appUrl); // this is coming as null. Not able to read it from application.properties
}
}
You can use #PropertySource annotation.
Something like this
#SpringBootApplication
#PropertySource("application.properties")
#EnableSwagger2
public class Application {
// Your code
}
You can Autowire the value like this
#Component
public class CsvReader implements Runnable{
#Value("${property.name.from.application.properties.file}")
private String appUrl;
#Override
public void run() {
System.out.println("run after Object created: "+ appUrl); // this is coming as null. Not able to read it from application.properties
}
}
Got the issue,
As I am executing CsvReader in a separate thread, container is not taking care of the bean initialisation, and thus dependency injections are not working.
Fixed the issue by
#Configuration
public class CsvReader {
#Value("${file-url}")
private String appUrl;
#PostConstruct
private void runAfterObjectCreated() {
Thread thread = new Thread() {
public void run() {
System.out.println("run after Object created: "+ appUrl);
}
};
thread.start();
}
}
With the above code, I am delegating the bean instantiation to the container.
#PostConstruct, ensures execution, once the class is loaded, and because I have a Thread class instantiated, by method is running in a new thread.
Option 2
#SpringBootApplication
#EnableSwagger2
public class Application {
#Autowired
private CsvReader csvReader;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
return new CommandLineRunner() {
public void run(String... args) throws Exception {
executor.execute(csvReader);
}
};
}
}

TestNg Console App with Exit

I am trying to write a TestNgtest case for a console app for when the user inputs ESC. At which point the application should print a message and then exit. I want the TestNg to test if the message gets printed. Here's the app code:
public class Application {
public static void doSomething(Scanner scanner) {
String inputString = scanner.nextLine();
if("ESC".equals(inputString.toUpperCase())) {
System.out.println("Bye");
System.exit(0);
}
}
}
Here's the junit code:
public class ApplicationTest {
private Application app;
private ByteArrayInputStream in;
private ByteArrayOutputStream out;
#BeforeMethod
public void setUp() throws Exception {
app = new Application();
out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
}
#AfterMethod
public void tearDown() throws Exception {
System.setIn(System.in);
}
#Test
public void testESCInput() throws Exception {
in = new ByteArrayInputStream("ESC".getBytes());
System.setIn(in);
app.processInput(new Scanner(System.in));
assertTrue(out.toString().contains("Bye"));
}
}
But since the application exits with System.exit I don't even get to the assertTrue line, the TestNg just ends before that. Is there a right way to test this?
You can use a SecurityManager to reject exit attempts, then build tests around the expected exception, e.g. this works with JUnit, should be easily adapted to TestNG
public class ExitTest {
public static class RejectedExitAttempt extends SecurityException {
private int exitStatus;
public RejectedExitAttempt(int status) {
exitStatus=status;
}
public int getExitStatus() {
return exitStatus;
}
#Override
public String getMessage() {
return "attempted to exit with status "+exitStatus;
}
}
#Before
public void setUp() throws Exception {
System.setSecurityManager(new SecurityManager() {
#Override
public void checkPermission(Permission perm) {
if(perm instanceof RuntimePermission && perm.getName().startsWith("exitVM."))
throw new RejectedExitAttempt(
Integer.parseInt(perm.getName().substring("exitVM.".length())));
}
});
}
#After
public void tearDown() throws Exception {
System.setSecurityManager(null);
}
#Test(expected=RejectedExitAttempt.class)
public void test() {
System.exit(0);
}
}
This is a simple test, that is satisfied with any exit attempt. If a particular exit status is required, you have to catch the exception and verify the status.
Since this custom SecurityManager allows any other action, resetting the security manager to null is possible.

Spring Camel application for one run

I am trying to create an application which will be used only in particular cases, from time to time.
scenario is as follows
user run an application
aplication start with spring-context.xml camel-context.xml
Routes from AppRoute.java are created
method which use created routes are executed
end
However I have a problem because whenever I use main.run() I can see that route is created however method is not executed. Without main.run() method is executed but no route is built.
my main:
import org.apache.camel.spring.Main;
import org.springframework.stereotype.Component;
public class EgzekutorManual extends Main{
#Produce(uri="direct:tester")
static ProducerTemplate pt;
public static void main(String[] args) throws Exception {
Main main = new Main();
main.showOptions();
main.run();
main.addRouteBuilder(new AppRoute());
manualTester();
}
public void manualTester(){
System.out.println("Manual tester executed");
pt.sendBody("X");
}
}
AppRoute.java:
private static class AppRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("direct:tester")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("Tester received message");
}
});
}
}
Can anyone give me a hint what I am doing wrong?

nextTuple() is called infinite times using BaseRichSpout on Storm

I implemented simple Storm topology having single spout and a bolt running on local cluster mode.
for some reason nextTuple() of the spout is called more than once.
Any idea why?
code:
spout:
public class CommitFeedListener extends BaseRichSpout {
private SpoutOutputCollector outputCollector;
private List<String> commits;
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("commit"));
}
#Override
public void open(Map configMap,
TopologyContext context,
SpoutOutputCollector outputCollector) {
this.outputCollector = outputCollector;
}
**//that method is invoked more than once**
#Override
public void nextTuple() {
outputCollector.emit(new Values("testValue"));
}
}
bolt:
public class EmailExtractor extends BaseBasicBolt {
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("email"));
}
#Override
public void execute(Tuple tuple,
BasicOutputCollector outputCollector) {
String commit = tuple.getStringByField("commit");
System.out.println(commit);
}
}
running configuration:
public class LocalTopologyRunner {
private static final int TEN_MINUTES = 600000;
public static void main(String[] args) {
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("commit-feed-listener", new CommitFeedListener());
builder
.setBolt("email-extractor", new EmailExtractor())
.shuffleGrouping("commit-feed-listener");
Config config = new Config();
config.setDebug(true);
StormTopology topology = builder.createTopology();
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("github-commit-count-topology",
config,
topology);
Utils.sleep(TEN_MINUTES);
cluster.killTopology("github-commit-count");
cluster.shutdown();
}
}
thanks all,
ray.
nextTuple() is called in an infinite loop by design. It is made like this to use for instance dirty checks against an external resource (database, stream, IO, etc).
You should sleep a while to prevent CPU spamming with backtype.storm.utils.Utils if you have nothing to do in nextTuple()
Utils.sleep(pollIntervalInMilliseconds);
Storm is a real-time processing architecture, so it is indeed the correct behaviour. Check some samples to see how to implement a spout according to your needs.
How about create some flag and set it when necessary?
if (completed) {
try {
Utils.sleep(pollIntervalInMilliseconds);
} catch (InterruptedException e) {
// Do nothing
}
return;
}

Implementation of addShutdownHook

Where and how to implement addShutdownHook in a class, which have no main method? Can this used to kill all the active sockets initialized by that class?
This Might work for you,
public class AddShutdownHookSample {
public void attachShutDownHook(){
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Inside Add Shutdown Hook");
}
});
System.out.println("Shut Down Hook Attached.");
}
}
And in main Method:
public static void main(String[] args) {
AddShutdownHookSample sample = new AddShutdownHookSample();
sample.attachShutDownHook();
System.out.println("Last instruction of Program....");
System.exit(0);
}
Describe whole thing that you are trying to do and show the very exact point where you are having trouble this would be easier for other to help you.
The following is an example, this may help you
public class RuntimeDemo {
// a class that extends thread that is to be called when program is exiting
static class Message extends Thread {
public void run() {
System.out.println("Bye.");
}
}
public static void main(String[] args) {
try {
// register Message as shutdown hook
Runtime.getRuntime().addShutdownHook(new Message());
// print the state of the program
System.out.println("Program is starting...");
// cause thread to sleep for 3 seconds
System.out.println("Waiting for 3 seconds...");
Thread.sleep(3000);
// print that the program is closing
System.out.println("Program is closing...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Done like this...
static {
Runtime.getRuntime().addShutdownHook ( new Thread() {
public void run() {
server.shutdown();
}
} );
}

Categories