Example usage for org.springframework.amqp.core MessageProperties setContentType

List of usage examples for org.springframework.amqp.core MessageProperties setContentType

Introduction

In this page you can find the example usage for org.springframework.amqp.core MessageProperties setContentType.

Prototype

public void setContentType(String contentType) 

Source Link

Usage

From source file:com.jbrisbin.vpc.jobsched.mapred.ReplyClosure.java

@Override
public Object call(final Object obj) {
    log.debug("obj: " + obj);
    String replyTo = (String) getProperty("replyTo");
    if (null != replyTo) {
        rabbitTemplate.send("", replyTo, new MessageCreator() {
            public Message createMessage() {
                MessageProperties props = new RabbitMessageProperties();
                props.setContentType("application/json");
                props.setCorrelationId(getProperty("id").toString().getBytes());
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                try {
                    mapper.writeValue(out, obj);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }/*from   ww w .  j a va 2  s.c  o  m*/
                Message msg = new Message(out.toByteArray(), props);
                if (log.isDebugEnabled()) {
                    log.debug("Sending reply: " + msg);
                }
                return msg;
            }
        });
    } else {
        log.warn("Reply requested, but replyTo was null!");
    }
    return null;
}

From source file:amqp.spring.converter.ContentTypeConverterFactoryTest.java

@Test
public void testStringConversion() throws Exception {
    TestObject testObject = new TestObject();
    testObject.setValue("TESTING");

    StringConverter stringConverter = new StringConverter();
    stringConverter.setContentType("application/xml");

    ContentTypeConverterFactory converter = new ContentTypeConverterFactory();
    converter.getConverters().put("application/json", new XStreamConverter());
    converter.getConverters().put("application/xml", new StringConverter());
    converter.setDefaultContentType("application/json");
    converter.setFallbackConverter(new StringConverter());

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("application/xml");

    Message amqpMessage = converter.toMessage(testObject, messageProperties);
    Assert.assertEquals("TESTING", new String(amqpMessage.getBody()));

    Object newObject = converter.fromMessage(amqpMessage);
    Assert.assertEquals("TESTING", newObject);
}

From source file:amqp.spring.converter.ContentTypeConverterFactoryTest.java

@Test
public void testJSONConversion() throws Exception {
    TestObject testObject = new TestObject();
    testObject.setValue("TESTING");

    StringConverter stringConverter = new StringConverter();
    stringConverter.setContentType("application/xml");

    ContentTypeConverterFactory converter = new ContentTypeConverterFactory();
    converter.getConverters().put("application/json", new XStreamConverter());
    converter.getConverters().put("application/xml", new StringConverter());
    converter.setDefaultContentType("application/json");
    converter.setFallbackConverter(new StringConverter());

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("application/json");

    Message amqpMessage = converter.toMessage(testObject, messageProperties);
    Assert.assertEquals(/*ww  w . j a  v a2 s  .co  m*/
            "{\"amqp.spring.converter.ContentTypeConverterFactoryTest_-TestObject\":{\"value\":\"TESTING\"}}",
            new String(amqpMessage.getBody()));

    Object newObject = converter.fromMessage(amqpMessage);
    Assert.assertEquals(testObject, newObject);
}

From source file:com.jbrisbin.vpc.jobsched.SubmitClosure.java

@Override
public Object call(Object[] args) {
    log.debug("args: " + args);
    String exch = args[0].toString();
    String route = args[1].toString();
    final Object body = args[2];
    Map headers = null;// w  w w .  j a  v a 2s.co m

    final BlockingQueue<Object> resultsQueue = new LinkedBlockingQueue<Object>();
    Queue replyQueue = rabbitAdmin.declareQueue();
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer();
    listener.setQueues(replyQueue);
    if (args.length > 3) {
        for (int i = 3; i <= args.length; i++) {
            if (args[i] instanceof MessageListener) {
                MessageListener callback = (MessageListener) args[3];
                listener.setMessageListener(callback);
            } else if (args[i] instanceof Map) {
                headers = (Map) args[i];
            }
        }
    } else {
        listener.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                byte[] body = message.getBody();
                try {
                    resultsQueue.add(mapper.readValue(body, 0, body.length, Map.class));
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }

    final Map msgHdrs = headers;
    rabbitTemplate.send(exch, route, new MessageCreator() {
        public Message createMessage() {
            MessageProperties props = new RabbitMessageProperties();
            props.setContentType("application/json");
            if (null != msgHdrs) {
                props.getHeaders().putAll(msgHdrs);
            }
            String uuid = UUID.randomUUID().toString();
            props.setCorrelationId(uuid.getBytes());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                mapper.writeValue(out, body);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            Message msg = new Message(out.toByteArray(), props);
            return msg;
        }
    });

    Object results = null;
    try {
        results = resultsQueue.poll(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    }
    listener.stop();

    return results;
}

From source file:org.resthub.rpc.AMQPHessianProxy.java

/**
 * Send request message/*from   w w w  .j  a  v  a  2 s . c  om*/
 * 
 * @param connectionFactory Spring connection factory
 * @param method Method to call
 * @param args Method arguments
 * @return Response to the sent request
 * @throws IOException
 */
private Message sendRequest(ConnectionFactory connectionFactory, Method method, Object[] args)
        throws IOException {
    RabbitTemplate template = this._factory.getTemplate();

    byte[] payload = createRequestBody(method, args);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("x-application/hessian");
    if (_factory.isCompressed()) {
        messageProperties.setContentEncoding("deflate");
    }

    Message message = new Message(payload, messageProperties);
    Message response = template.sendAndReceive(_factory.getRequestExchangeName(_factory.getServiceInterface()),
            _factory.getRequestQueueName(_factory.getServiceInterface()), message);

    return response;
}

From source file:org.springframework.amqp.support.converter.Jackson2JsonMessageConverterTests.java

@Test
public void testDefaultTypeConfig() {
    byte[] bytes = "{\"name\" : \"foo\" }".getBytes();
    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("application/json");
    Message message = new Message(bytes, messageProperties);
    Object foo = jsonConverterWithDefaultType.fromMessage(message);
    assertTrue(foo instanceof Foo);
}

From source file:org.springframework.amqp.support.converter.Jackson2JsonMessageConverterTests.java

@Test
public void testDefaultType() {
    byte[] bytes = "{\"name\" : \"foo\" }".getBytes();
    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("application/json");
    Message message = new Message(bytes, messageProperties);
    JsonMessageConverter converter = new JsonMessageConverter();
    DefaultClassMapper classMapper = new DefaultClassMapper();
    classMapper.setDefaultType(Foo.class);
    converter.setClassMapper(classMapper);
    Object foo = converter.fromMessage(message);
    assertTrue(foo instanceof Foo);
}

From source file:com.jbrisbin.vpc.jobsched.batch.BatchMessageConverter.java

public Message toMessage(Object object, MessageProperties props) throws MessageConversionException {
    if (object instanceof BatchMessage) {
        BatchMessage batch = (BatchMessage) object;
        props.setCorrelationId(batch.getId().getBytes());
        props.setContentType("application/zip");

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream zout = new ZipOutputStream(bout);
        for (Map.Entry<String, String> msg : batch.getMessages().entrySet()) {
            ZipEntry zentry = new ZipEntry(msg.getKey());
            try {
                zout.putNextEntry(zentry);
                zout.write(msg.getValue().getBytes());
                zout.closeEntry();/*from w ww. j a  va2 s .c  o  m*/
            } catch (IOException e) {
                throw new MessageConversionException(e.getMessage(), e);
            }
        }

        try {
            zout.flush();
            zout.close();
        } catch (IOException e) {
            throw new MessageConversionException(e.getMessage(), e);
        }

        return new Message(bout.toByteArray(), props);
    } else {
        throw new MessageConversionException(
                "Cannot convert object " + String.valueOf(object) + " using " + getClass().toString());
    }
}

From source file:amqp.spring.converter.StringConverter.java

@Override
protected Message createMessage(Object object, MessageProperties messageProperties) {
    try {//from w  w w.j ava 2 s. c o  m
        byte[] body = null;
        if (object != null) {
            body = object.toString().getBytes(this.encoding);
        }

        String msgContentType = this.contentType == null ? DEFAULT_CONTENT_TYPE : this.contentType;
        messageProperties.setContentType(msgContentType);
        messageProperties.setContentEncoding(this.encoding);
        messageProperties.setContentLength(body != null ? body.length : 0);
        return new Message(body, messageProperties);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Cannot encode strings as {}", this.encoding, ex);
        throw new MessageConversionException("Cannot encode strings as " + this.encoding, ex);
    }
}

From source file:com.jbrisbin.vpc.jobsched.mapred.MapReduceMessageHandler.java

private void onKeyChange(final String id, final String key) {
    final String token = id + key;
    Closure cl = contextCache.remove(token);
    Closure onKeyChange = (Closure) cl.getProperty("onKeyChange");
    onKeyChange.setProperty("key", key);
    final Object o = onKeyChange.call();
    if (null != o) {
        // Send to rereduce
        rabbitTemplate.send("", DigestUtils.md5Hex(id), new MessageCreator() {
            public Message createMessage() {
                MessageProperties props = new RabbitMessageProperties();
                props.setContentType("application/json");
                props.setCorrelationId(id.getBytes());
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                try {
                    mapper.writeValue(out, o);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }/*  w w  w.  ja va  2 s . c  om*/
                Message msg = new Message(out.toByteArray(), props);
                return msg;
            }
        });
    }
}