Skip to content

Instantly share code, notes, and snippets.

@rbe
Created October 22, 2010 06:47
Show Gist options
  • Save rbe/640067 to your computer and use it in GitHub Desktop.
Save rbe/640067 to your computer and use it in GitHub Desktop.
class FileRouter extends org.apache.camel.language.groovy.GroovyRouteBuilder {
/**
* Define routes for Camel.
*/
protected void configure() {
//
// Route 1
//
// Watch directory for incoming file
from("file:///tmp/in")
// ...filter by its name
.filter {
// Ignore hidden dot-files and watch for PDFs
!it.in.headers.CamelFileName.startsWith(".") && it.in.headers.CamelFileName.endsWith(".pdf")
}
// ...and push file to bean; the method must take a File argument
.to("bean:camelProcessor?method=receive") // Should return text for XMPP
// ...send message to Google Talk
.to("xmpp://talk.google.com:5222/[email protected]?serviceName=gmail.com&[email protected]&password=senderpassword")
.to("bean:camelProcessor?method=afterXMPP")
// Watch file
.to("bean:camelProcessor?method=watchFile")
//
// Route 2
//
// Process outgoing file
from("file:///tmp/out")
// ...and push file to bean; the method must take a File argument
.to("bean:camelProcessor?method=send")
}
}
class Main {
/**
* Ride the Camel...
*/
def static setupCamel() {
// Create Camel context
camelCtx = new org.apache.camel.impl.DefaultCamelContext()
// Setup registry and register a bean
camelCtx.registry = new org.apache.camel.impl.SimpleRegistry()
camelCtx.registry.registry.put("camelProcessor", CamelProcessor.instance)
// Add routes and start Camel; this call doesn't block
camelCtx.addRoutes(new FileRouter())
camelCtx.start()
// Stop Camel when the JVM is shut down
Runtime.runtime.addShutdownHook({ ->
camelCtx.stop()
})
}
public static void main(String[] args) {
// Camel
setupCamel()
// Now start your application
// ...
}
}
/**
* Process files with Camel.
*/
@Singleton
class CamelProcessor {
def receive(File file) {
// Do something with the file
println "I cannot believe it, I received a file: ${file}"
// Return file name
"We received ${file}"
}
def afterXMPP(Object obj) {
println "afterXMPP: obj=${obj?.dump()}"
}
def send(File file) {
// Do something
println "Don't let me keep you: ${file}"
// Return file
file
}
def watchFile(File file) {
// Watch the file in a thread
def r = { ->
println "watchFileTime: start watching ${file}"
// Remember last modified
def lm = file.lastModified()
// As long as the file exists...
while (file.exists()) {
// Check file modification time and compare to saved value
if (file.lastModified() != lm) {
// Remember last modified
lm = file.lastModified()
// Do something...
println "${file} was changed"
}
// Hold on a second
try { Thread.sleep(1 * 1000) } catch (e) {}
}
println "watchFileTime: stop watching ${file}"
} as java.lang.Runnable
// Create and start thread
new java.lang.Thread(r).start()
// Return file
file
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment