Java Examples for org.springframework.amqp.support.converter.Jackson2JsonMessageConverter

The following java examples will help you to understand the usage of org.springframework.amqp.support.converter.Jackson2JsonMessageConverter. These source code samples are taken from different open source projects.

Example 1
Project: MineKnowContainer-master  File: RabbitMQConfig.java View source code
@Bean(name = "studentMessageConverter_receive")
public MessageConverter StudentMessageConverter_receive() {
    DefaultClassMapper classMapper = new DefaultClassMapper();
    classMapper.setDefaultType(StudentInReceive.class);
    Map<String, Class<?>> map = new HashMap<String, Class<?>>();
    map.put("Student", StudentInReceive.class);
    map.put("Teacher", Teacher.class);
    classMapper.setIdClassMapping(map);
    Jackson2JsonMessageConverter messageConverter = new Jackson2JsonMessageConverter();
    messageConverter.setClassMapper(classMapper);
    return messageConverter;
}
Example 2
Project: spring-amqp-master  File: EnableRabbitIntegrationTests.java View source code
@Test
public void testConverted() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(EnableRabbitConfigWithCustomConversion.class);
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    Foo1 foo1 = new Foo1();
    foo1.setBar("bar");
    Jackson2JsonMessageConverter converter = ctx.getBean(Jackson2JsonMessageConverter.class);
    converter.setTypePrecedence(TypePrecedence.TYPE_ID);
    Object returned = template.convertSendAndReceive("test.converted", foo1);
    assertThat(returned, instanceOf(Foo2.class));
    assertEquals("bar", ((Foo2) returned).getBar());
    assertTrue(TestUtils.getPropertyValue(ctx.getBean("foo1To2Converter"), "converted", Boolean.class));
    converter.setTypePrecedence(TypePrecedence.INFERRED);
    // No type info in message
    template.setMessageConverter(new SimpleMessageConverter());
    @SuppressWarnings("resource") MessagePostProcessor messagePostProcessor =  message -> {
        message.getMessageProperties().setContentType("application/json");
        message.getMessageProperties().setUserId("guest");
        return message;
    };
    returned = template.convertSendAndReceive("", "test.converted", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("{\"bar\":\"baz\"}", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.converted.list", "[ { \"bar\" : \"baz\" } ]", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("{\"bar\":\"BAZZZZ\"}", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.converted.array", "[ { \"bar\" : \"baz\" } ]", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("{\"bar\":\"BAZZxx\"}", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.converted.args1", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"bar=baztest.converted.args1\"", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.converted.args2", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"bar=baztest.converted.args2\"", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.converted.message", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"bar=bazfoo2MessageFoo2Service\"", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.notconverted.message", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"fooMessage\"", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.notconverted.channel", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"barAndChannel\"", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.notconverted.messagechannel", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"bar=bazMessageAndChannel\"", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.notconverted.messagingmessage", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"GenericMessageLinkedHashMap\"", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.converted.foomessage", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"GenericMessageFoo2guest\"", new String((byte[]) returned));
    returned = template.convertSendAndReceive("", "test.notconverted.messagingmessagenotgeneric", "{ \"bar\" : \"baz\" }", messagePostProcessor);
    assertThat(returned, instanceOf(byte[].class));
    assertEquals("\"GenericMessageLinkedHashMap\"", new String((byte[]) returned));
    Jackson2JsonMessageConverter jsonConverter = ctx.getBean(Jackson2JsonMessageConverter.class);
    DefaultJackson2JavaTypeMapper mapper = TestUtils.getPropertyValue(jsonConverter, "javaTypeMapper", DefaultJackson2JavaTypeMapper.class);
    Mockito.verify(mapper).setBeanClassLoader(ctx.getClassLoader());
    ctx.close();
}
Example 3
Project: spring-integration-master  File: DefaultAmqpHeaderMapperTests.java View source code
// INT-2090
@Test
public void jsonTypeIdNotOverwritten() {
    DefaultAmqpHeaderMapper headerMapper = DefaultAmqpHeaderMapper.inboundMapper();
    MessageConverter converter = new Jackson2JsonMessageConverter();
    MessageProperties amqpProperties = new MessageProperties();
    converter.toMessage("123", amqpProperties);
    Map<String, Object> headerMap = new HashMap<String, Object>();
    headerMap.put("__TypeId__", "java.lang.Integer");
    MessageHeaders integrationHeaders = new MessageHeaders(headerMap);
    headerMapper.fromHeadersToRequest(integrationHeaders, amqpProperties);
    assertEquals("java.lang.String", amqpProperties.getHeaders().get("__TypeId__"));
    Object result = converter.fromMessage(new Message("123".getBytes(), amqpProperties));
    assertEquals(String.class, result.getClass());
}
Example 4
Project: SIA-master  File: FlowHandler.java View source code
@Bean
IntegrationFlow flow(ConnectionFactory connectionFactory, Queue input, Jackson2JsonMessageConverter messageConverter, Environment environment) {
    IntegrationFlowBuilder flow = IntegrationFlows.from(Amqp.inboundAdapter(connectionFactory, input).concurrentConsumers(// but not the number of requests
    annotatorConfig.getConcurrentConsumer()).messageConverter(messageConverter).headerMapper(DefaultAmqpHeaderMapper.inboundMapper()).defaultRequeueRejected(// if this fails ... forward to the error queue
    false).adviceChain(retryOperationsInterceptor()).errorChannel("errorSendingResults.input")).enrichHeaders( headerEnricherSpec -> headerEnricherSpec.headerExpression("communication_id", "payload.parameters.communication_id")).enrichHeaders( headerEnricherSpec -> headerEnricherSpec.headerExpression("types", "payload.parameters.types")).split(ServerRequest.class,  serverRequest -> {
        ImmutableListMultimap<String, ServerRequest.Document> index = Multimaps.index(serverRequest.getParameters().getDocuments(), ServerRequest.Document::getSource);
        List<IdList> idLists = new ArrayList<>();
        for (Map.Entry<String, Collection<ServerRequest.Document>> entry : index.asMap().entrySet()) {
            for (List<ServerRequest.Document> documentList : Iterables.partition(entry.getValue(), annotatorConfig.getRequestBulkSize())) {
                idLists.add(new IdList(entry.getKey(), documentList.stream().map(ServerRequest.Document::getDocument_id).collect(Collectors.toList())));
            }
        }
        return idLists;
    }).transform(//   .channel(c -> c.executor("Downloader", Executors.newFixedThreadPool(annotatorConfig.getConcurrentHandler())))
    IdList.class, documentFetcher::load).split().channel("annotate").routeToRecipients( r -> r.applySequence(true).defaultOutputToParentFlow().recipient("mirner", "headers['types'].contains(T(de.dfki.nlp.domain.PredictionType).MIRNA)").recipient("seth", "headers['types'].contains(T(de.dfki.nlp.domain.PredictionType).MUTATION)").recipient("diseases", "headers['types'].contains(T(de.dfki.nlp.domain.PredictionType).DISEASE)")).channel("parsed").aggregate().<// this aggregates annotations per document (from router)
    List<Set<PredictionResult>>, Set<PredictionResult>>transform( s -> s.stream().flatMap(Collection::stream).collect(Collectors.toSet())).channel("aggregate").aggregate().aggregate().channel(// now merge the results by flattening
    "jointogether").<List<List<Set<PredictionResult>>>, Set<PredictionResult>>transform( source -> source.stream().flatMap(Collection::stream).flatMap(Collection::stream).collect(Collectors.toSet()));
    if (environment.acceptsProfiles("cloud")) {
        // when cloud profile is active, send results via http
        flow.enrichHeaders( headerEnricherSpec -> headerEnricherSpec.headerExpression("Content-Type", "'application/json'")).log(LoggingHandler.Level.INFO,  objectMessage -> String.format("Sending Results [%s] after %d ms %s", objectMessage.getHeaders().get("communication_id"), (System.currentTimeMillis() - (long) objectMessage.getHeaders().get(ProcessingGateway.HEADER_REQUEST_TIME)), objectMessage.getHeaders().toString())).handleWithAdapter(// use retry advice - which tries to resend in case of failure
        sendToBecalmServer(),  e -> e.advice(retryAdvice()));
    } else {
        // for local deployment, just log
        flow.<Set<PredictionResult>>handle(( parsed,  headers) -> {
            log.info(headers.toString());
            log.info("Annotation request took [{}] {} ms", headers.get("communication_id"), System.currentTimeMillis() - (long) headers.get(ProcessingGateway.HEADER_REQUEST_TIME));
            parsed.stream().sorted(( o1,  o2) -> ComparisonChain.start().compare(o1.getDocumentId(), o2.getDocumentId()).compare(o1.getSection().name(), o2.getSection().name()).compare(o1.getInit(), o2.getInit()).result()).forEach( r -> log.info(r.toString()));
            return null;
        });
    }
    return flow.get();
}
Example 5
Project: cloudfoundry-ftp-service-broker-master  File: Application.java View source code
// TODO: Rewrite this in Spring Cloud Stream as a module
// https://github.com/spring-cloud/spring-cloud-dataflow/blob/master/spring-cloud-dataflow-module-deployers/spring-cloud-dataflow-module-deployer-lattice/src/main/java/org/springframework/cloud/dataflow/module/deployer/lattice/TaskModuleDeployer.java
// Write a planner that preemptive-ly schedules new instances at 80%?
@Bean
IntegrationFlow amqpReplyFlow(ConnectionFactory rabbitConnectionFactory, UserManager ftpUserManager) {
    return IntegrationFlows.from(Amqp.inboundGateway(rabbitConnectionFactory, this.ftpRequests).messageConverter(new Jackson2JsonMessageConverter())).transform(String.class, new GenericTransformer<String, String>() {

        @Override
        public String transform(String source) {
            try {
                Map<String, String> map = toMap(source);
                String ws = map.get("workspace");
                String usr = map.get("user");
                String password = UUID.randomUUID().toString();
                FtpUser user = new FtpUser(ws, usr, password, true);
                ftpUserManager.save(user);
                String ftpUri = buildFtpConnectionString(host, port, user);
                log.info("registering: workspace: " + ws + ", " + "user: " + usr + ", ftp URI: " + ftpUri);
                return ftpUri;
            } catch (FtpException e) {
                throw new RuntimeException(e);
            }
        }
    }).get();
}
Example 6
Project: spring-amqp-samples-master  File: Application.java View source code
@Bean
public SimpleMessageListenerContainer legacyPojoListener(ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setQueueNames(MAPPED_QUEUE);
    MessageListenerAdapter messageListener = new MessageListenerAdapter(new Object() {

        @SuppressWarnings("unused")
        public void handleMessage(Object object) {
            System.out.println("Got a " + object);
            Application.this.latch.countDown();
        }
    });
    Jackson2JsonMessageConverter jsonConverter = new Jackson2JsonMessageConverter();
    jsonConverter.setClassMapper(classMapper());
    messageListener.setMessageConverter(jsonConverter);
    container.setMessageListener(messageListener);
    return container;
}
Example 7
Project: scraping-microservice-java-python-rabbitmq-master  File: RabbitMqConfiguration.java View source code
@Bean
public MessageConverter jsonMessageConverter() {
    final Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
    converter.setClassMapper(classMapper());
    return converter;
}
Example 8
Project: spring-rabbitmq-example-master  File: MessagingConfiguration.java View source code
@Bean
protected MessageConverter messageConverter() {
    return new Jackson2JsonMessageConverter();
}
Example 9
Project: sfdc-cloudfoundry-master  File: RabbitConfiguration.java View source code
@Bean
Jackson2JsonMessageConverter jsonMessageConverter() {
    return new Jackson2JsonMessageConverter();
}
Example 10
Project: rabbit-master  File: RabbitSinkConfiguration.java View source code
@Bean
@ConditionalOnProperty(name = "rabbit.converterBeanName", havingValue = RabbitSinkProperties.JSON_CONVERTER)
public Jackson2JsonMessageConverter jsonConverter() {
    return new Jackson2JsonMessageConverter();
}
Example 11
Project: spring-cloud-stream-modules-master  File: RabbitSink.java View source code
@Bean
@ConditionalOnProperty(name = "converterBeanName", havingValue = RabbitSinkProperties.JSON_CONVERTER)
public Jackson2JsonMessageConverter jsonConverter() {
    return new Jackson2JsonMessageConverter();
}