#!/usr/bin/perl
# ------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------
#
# sample listener
#

use strict;
use warnings;
use Net::STOMP::Client;
use Time::HiRes qw(time);

our(%Option, $Conn, $Count, $Start, $Run);

$Option{user} = $ENV{ACTIVEMQ_USER} || "admin";
$Option{password} = $ENV{ACTIVEMQ_PASSWORD} || "password";
$Option{host} = $ENV{ACTIVEMQ_HOST} || "localhost";
$Option{port} = $ENV{ACTIVEMQ_PORT} || 61613;
$Option{destination} = $ENV{STOMP_DESTINATION} || "/topic/event";

sub callback ($$) {
    my($self, $frame) = @_;

    $Start = time() unless $Count++;
    $Run = 0 if $frame->body() eq "SHUTDOWN";
}

$Conn = Net::STOMP::Client->new(
    host => $Option{host},
    port => $Option{port},
);
$Conn->connect(
    login    => $Option{user},
    passcode => $Option{password},
);
printf("connected to %s:%d\n", $Conn->peer()->addr(), $Conn->peer()->port());
$Conn->message_callback(\&callback);
$Conn->subscribe(
    destination => $Option{destination},
    id          => 0,
    ack         => "auto",
);
printf("Waiting for messages...\n");
$Count = 0;
$Run = 1;
$Conn->wait_for_frames() while $Run;
printf("received %d messages in %.3f seconds\n", $Count, time()-$Start);
$Conn->disconnect();