/*
 * This is the main handler which is called when a request for state is
 * received from Diffusion.
 *
 * Choose a random fortune and write it to the response parameter.
 */
static int
fortune_state_handler(SESSION_T *session, const SVC_STATE_REQUEST_T *request, SVC_STATE_RESPONSE_T *response, void *context)
{
        long r = random() % fortune_count;
        char *fortune = fortunes[r];

        printf("fortune_state_handler(): %s\n", fortune);

        buf_write_bytes(response->payload, fortune, strlen(fortune));

        return HANDLER_SUCCESS;
}
Esempio n. 2
0
int
main(int argc, char **argv)
{
        // Standard command line parsing.
        HASH_T *options = parse_cmdline(argc, argv, arg_opts);
        if(options == NULL || hash_get(options, "help") != NULL) {
                show_usage(argc, argv, arg_opts);
                return 1;
        }

        char *url = hash_get(options, "url");
        const char *principal = hash_get(options, "principal");
        CREDENTIALS_T *credentials = NULL;
        const char *password = hash_get(options, "credentials");
        if(password != NULL) {
                credentials = credentials_create_password(password);
        }
        char *topic = hash_get(options, "topic");

        // Setup for condition variable.
        apr_initialize();
        apr_pool_create(&pool, NULL);
        apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_UNNESTED, pool);
        apr_thread_cond_create(&cond, pool);

        // Create a session with Diffusion.
        SESSION_T *session = NULL;
        DIFFUSION_ERROR_T error;
        session = session_create(url, principal, credentials, NULL, NULL, &error);
        if(session == NULL) {
                fprintf(stderr, "TEST: Failed to create session\n");
                fprintf(stderr, "ERR : %s\n", error.message);
                return 1;
        }

        // Create a payload.
        char *data = hash_get(options, "data");
        BUF_T *payload = buf_create();
        buf_write_bytes(payload, data, strlen(data));

        // Build up some headers to send with the message.
        LIST_T *headers = list_create();
        list_append_last(headers, "apple");
        list_append_last(headers, "train");

        // Parameters for send_msg() call.
        SEND_MSG_PARAMS_T params = {
                .topic_path = topic,
                .payload = *payload,
                .headers = headers,
                .priority = CLIENT_SEND_PRIORITY_NORMAL,
                .on_send = on_send,
                .context = "FOO"
        };

        // Send the message and wait for the callback to acknowledge delivery.
        apr_thread_mutex_lock(mutex);
        send_msg(session, params);
        apr_thread_cond_wait(cond, mutex);
        apr_thread_mutex_unlock(mutex);

        // Politely close the client connection.
        session_close(session, &error);

        return 0;
}