@Grab('com.rabbitmq:amqp-client:2.7.0')
import com.rabbitmq.client.*
public class SendReceive {
private String QUEUE
private Channel channel
public SendReceive( String hostName = "localhost", String queue = "hello" ) {
QUEUE = queue
ConnectionFactory factory = new ConnectionFactory()
// factory.setUsername(userName)
// factory.setPassword(password)
// factory.setVirtualHost(virtualHost)
factory.setHost(hostName)
// factory.setPort(portNumber)
Connection connection = factory.newConnection()
channel = connection.createChannel()
channel.exchangeDeclare(QUEUE, "fanout")
}
public void send( String message )
throws java.io.IOException {
channel.basicPublish(QUEUE, "", null, message.getBytes())
println(" [x] Sent: $message")
//channel.close()
//connection.close()
}
public void receive()
throws java.io.IOException, java.lang.InterruptedException {
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, QUEUE, "");
QueueingConsumer consumer = new QueueingConsumer(channel)
channel.basicConsume(queueName, true, consumer)
println(" [*] Waiting for messages. To exit press CTRL+C")
while (true) { //loop forever!
QueueingConsumer.Delivery delivery = consumer.nextDelivery() // blocks for next message!
String message = new String(delivery.getBody())
println(" [x] Received: $message")
}
}
}
def input = System.console().&readLine // convenience method
def client = new SendReceive(
input('\nEnter rabbitMQ host location: '),
input('\nEnter rabbitMQ queue name: ')
)
String userType = input('\n[s]end or [r]eceive?: ')
if (userType && userType == 'r') {
client.receive()
}
else {
while(true) {
String msg = input('\nType a message to send -- To exit press CTRL+C: ')
client.send(msg)
}
}
Thursday, December 15, 2011
rabbitMQ - Publish/Subscribe
rabbitMQ - Queue
@Grab('com.rabbitmq:amqp-client:2.7.0')
import com.rabbitmq.client.*
public class SendReceive {
private String QUEUE
private Channel channel
public SendReceive( String hostName = "localhost", String queue = "hello" ) {
QUEUE = queue
ConnectionFactory factory = new ConnectionFactory()
// factory.setUsername(userName)
// factory.setPassword(password)
// factory.setVirtualHost(virtualHost)
factory.setHost(hostName)
// factory.setPort(portNumber)
Connection connection = factory.newConnection()
channel = connection.createChannel()
channel.queueDeclare(QUEUE, false, false, false, null)
}
public void send( String message )
throws java.io.IOException {
channel.basicPublish("", QUEUE, null, message.getBytes())
println(" [x] Sent: $message")
//channel.close()
//connection.close()
}
public void receive()
throws java.io.IOException, java.lang.InterruptedException {
QueueingConsumer consumer = new QueueingConsumer(channel)
channel.basicConsume(QUEUE, true, consumer)
println(" [*] Waiting for messages. To exit press CTRL+C")
while (true) { //loop forever!
QueueingConsumer.Delivery delivery = consumer.nextDelivery() // blocks for next message!
String message = new String(delivery.getBody())
println(" [x] Received: $message")
}
}
}
def input = System.console().&readLine // convenience method
def client = new SendReceive(
input('\nEnter rabbitMQ host location: '),
input('\nEnter rabbitMQ queue name: ')
)
String userType = input('\n[s]end or [r]eceive?: ')
if (userType && userType == 'r') {
client.receive()
}
else {
while(true) {
String msg = input('\nType a message to send -- To exit press CTRL+C: ')
client.send(msg)
}
}
Multi-Assign, Transform Map Keys
(a,b,c) = [1,2]
assert a == 1
assert c == null
(a,b,c) = {[1,2]}()
assert a == 1
assert c == null
Map o = [a:1,b:2,c:3,d:4,aa:5]
// the objective it to keep only the keys with 'a', and uppercase them //
Map f1 = [:]
o.findAll { i -> i.key.contains('a') }
.each { i -> f1[i.key.toUpperCase()] = i.value }
println f1 // [A:1, AA:5]
Map f2 = [:]
o.each { i ->
if (i.key.contains('a'))
f2[i.key.toUpperCase()] = i.value
}
println f2 // [A:1, AA:5]
Map g1 = o
.findAll { i -> i.key.contains('a') }
.inject([:]) { m, i ->
m[i.key.toUpperCase()] = i.value
return m
}
println g1 // [A:1, AA:5]
Map g2 = o
.inject([:]) { m, i ->
if (i.key.contains('a'))
m[i.key.toUpperCase()] = i.value
return m
}
println g2 // [A:1, AA:5]
Wednesday, December 14, 2011
Joda-Time
@Grab('joda-time:joda-time:2.0')
import org.joda.time.*
//see also http://groovycookbook.org/basic_types/dates_times_joda/
public boolean isAfterPayDay(DateTime datetime) {
if (datetime.getMonthOfYear() == 2) { // February is month 2!!
return datetime.getDayOfMonth() > 26;
}
return datetime.getDayOfMonth() > 28;
}
public Days daysToNewYear(LocalDate fromDate) {
LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1);
return Days.daysBetween(fromDate, newYear);
}
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = new Period().withDays(2).withHours(12);
return datetimeRented.plus(rentalPeriod).isBeforeNow();
}
public String getBirthMonthText(LocalDate dateOfBirth) {
return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH);
}
DateTime dt = new DateTime();
int month = dt.getMonthOfYear();
DateTime year2000 = dt.withYear(2000);
DateTime twoHoursLater = dt.plusHours(2);
String monthName = dt.monthOfYear().getAsText();
String frenchShortName = dt.monthOfYear().getAsShortText(Locale.FRENCH);
boolean isLeapYear = dt.year().isLeap();
DateTime rounded = dt.dayOfMonth().roundFloorCopy();
println (new DateTime().withDayOfMonth(4).withMonthOfYear(7).withYear(1899).toString('EEE, dd/MM/yyyy HH:mm:ss'))
println (new Date().parse("d/M/yyyy H:m:s","21/3/2008 17:30:20"))
println (Calendar.instance.time.format('MMM dd, yyyy'))
// standard groovy flavor, see also http://groovycookbook.org/basic_types/dates_times/
Various index techniques
enum Coin {
penny(1), nickel(5), dime(10), quarter(25)
private final int value
Coin(int value) { this.value = value }
public int value() { return value }
}
assert 'penny' == Coin.penny.toString()
assert 1 == Coin.penny.value
Map Coin2 = [penny:1, nickel:5, dime:10, quarter:25]
assert 1 == Coin2.penny
List Coin3 = ['penny', 'nickel']
assert 1 == Coin3.indexOf('nickel')
Monday, December 5, 2011
Gretty
@GrabResolver(name='gretty',
root='http://groovypp.artifactoryonline.com/groovypp/libs-releases-local')
@Grab('org.mbte.groovypp:gretty:0.4.302')
import org.mbte.gretty.httpserver.*
GrettyServer server = []
server.groovy = [
localAddress: new InetSocketAddress("localhost", 8080),
defaultHandler: {
response.redirect "/"
},
"/:name": {
get {
response.text = "Hello ${request.parameters['name']}"
}
}
]
server.start()
//see: https://github.com/groovypp/gretty/wiki/Getting-Started
see: Gretty, article
CSV file parser I/O
@Grab(group = 'net.sf.opencsv', module = 'opencsv', version = '2.3')
import au.com.bytecode.opencsv.CSVReader
import au.com.bytecode.opencsv.CSVParser
import au.com.bytecode.opencsv.CSVWriter
String TEST_FILE_NAME = 'C:\\test.csv'
String TEST_OUTPUT_FILE_NAME = 'C:\\testOut.csv'
List< String[] > rows = new CSVReader(
new FileReader(new File(TEST_FILE_NAME)),
CSVParser.DEFAULT_SEPARATOR,
CSVParser.DEFAULT_ESCAPE_CHARACTER,
CSVParser.DEFAULT_QUOTE_CHARACTER, 1
).readAll()
List< String[] > rowsOver100 = rows.findAll { it[1].toInteger() > 100 }
File output = new File(TEST_OUTPUT_FILE_NAME)
if (output.exists()) {
output.delete()
}
output.createNewFile()
output.withWriter { writer ->
new CSVWriter(writer).writeAll(rowsOver100)
}
// for streaming, see also: http://www.groovy-tutorial.org/basic-csv/
Subscribe to:
Posts (Atom)