Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a standalone Camel application that can automatically shutdown?

I have a simple file transfer application that is run as a standalone Java application. It takes files from an SFTP endpoint and moves them to another endpoint.

Files are deleted from the SFTP endpoint after they are transferred. When there are no more files left, it would be ideal to have the program end. However, I haven't been able to find a solution where I can start Camel and get it to end conditionally (like when there are no more files in the SFTP endpoint). My workaround is currently to start Camel and then have the main thread sleep for a very long time. The user then has to kill the application manually (via CTRL+C or otherwise).

Is there a better way to have the application terminate such that it does so automatically?

Below is my current code:

In CamelContext (Spring App Context):

<route>
    <from uri="sftp:(url)" />
    <process ref="(processor)" />
    <to uri="(endpoint)" />
</route>

main() method:

public static void main(String[] args)
{
  ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  CamelContext camelContext = appContext.getBean(CamelContext.class);

  try
  {
    camelContext.start();
    Thread.sleep(1000000000); // Runs the program for a long time -- is there a better way?
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }

  UploadContentLogger.info("Exiting");
}
like image 716
jeffmaher Avatar asked Oct 16 '12 16:10

jeffmaher


2 Answers

You could change you route something like this:

<route>
    <from uri="sftp:(url)?sendEmptyMessageWhenIdle=true" />
    <choose>
        <when>
            <simple>${body} != null</simple>
            <process ref="(processor)" />
            <to uri="(endpoint)" />
        </when>
        <otherwise>
            <process ref="(shutdownProcessor)" />
        </otherwise>
    </choose>
</route>

Notice using sendEmptyMessageWhenIdle=true

And here is shutdownProcessor

public class ShutdownProcessor {
    public void stop(final Exchange exchange) {
        new Thread() {
            @Override
            public void run() {
                try {
                    exchange.getContext().stop();
                } catch (Exception e) {
                    // log error
                }
            }
        }.start();
    }
}

Actually I didn't run this code, but it should work as desired.

like image 178
szhem Avatar answered Oct 18 '22 06:10

szhem


I just wanted to point you to this FAQ also http://camel.apache.org/how-can-i-stop-a-route-from-a-route.html

like image 1
Claus Ibsen Avatar answered Oct 18 '22 06:10

Claus Ibsen