org.springframework.tuple.Tuple Java Examples

The following examples show how to use org.springframework.tuple.Tuple. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JdbcSinkIntegrationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertion() {
	Tuple tupleA = TupleBuilder.tuple().of("a", "hello1", "b", 42);
	Tuple tupleB = TupleBuilder.tuple().of("a", "hello2", "b", null);
	Tuple tupleC = TupleBuilder.tuple().of("a", "hello3");
	channels.input().send(MessageBuilder.withPayload(tupleA).build());
	channels.input().send(MessageBuilder.withPayload(tupleB).build());
	channels.input().send(MessageBuilder.withPayload(tupleC).build());
	Assert.assertThat(jdbcOperations.queryForObject(
			"select count(*) from messages where a = ? and b = ?",
			Integer.class, tupleA.getString("a"), tupleA.getInt("b")), is(1));
	Assert.assertThat(jdbcOperations.queryForObject(
			"select count(*) from messages where a = ? and b IS NULL",
			Integer.class, tupleB.getString("a")), is(1));
	Assert.assertThat(jdbcOperations.queryForObject(
			"select count(*) from messages where a = ? and b IS NULL",
			Integer.class, tupleC.getString("a")), is(1));
}
 
Example #2
Source File: FieldValueCounterSinkConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@ServiceActivator(inputChannel=Sink.INPUT)
public void process(Message<?> message) {
	Object payload = message.getPayload();
	if (payload instanceof String) {
		try {
			payload = jsonToTupleTransformer.transformPayload(payload.toString());
		}
		catch (Exception e) {
			throw new MessageTransformationException(message, e.getMessage(), e);
		}
	}
	if (payload instanceof Tuple) {
		processTuple(computeMetricName(message), (Tuple) payload);
	}
	else {
		processPojo(computeMetricName(message), payload);
	}
}
 
Example #3
Source File: TupleToJsonStringConverter.java    From event-store-demo with GNU General Public License v3.0 6 votes vote down vote up
private BaseJsonNode toNode(Object value) {
    if (value != null) {
        if (value instanceof Tuple) {
            return toObjectNode((Tuple) value);
        }
        else if (value instanceof List<?>) {
            return toArrayNode((List<?>) value);
        }
        else if (!value.getClass().isPrimitive()) {
            return mapper.getNodeFactory().pojoNode(value);
        }
        else {
            return mapper.valueToTree(value);
        }
    }
    return null;
}
 
Example #4
Source File: EnrichProcessor.java    From FraudDetection-Microservices with Apache License 2.0 6 votes vote down vote up
private MutableMessage<?> convertToMutable(Message<?> input) throws Exception{
    Object payload = input.getPayload();
    if (payload instanceof Tuple && !(payload instanceof MutableTuple)) {
            payload = TupleBuilder.mutableTuple().putAll((Tuple) payload).build();
    }
    else if (payload instanceof String){
		String strPayload = input.getPayload().toString();
		Iterator<Entry<String, Object>> objects = new ObjectMapper().readValue(strPayload, Map.class).entrySet().iterator();
		TupleBuilder tuples = TupleBuilder.mutableTuple();
		while (objects.hasNext()){
			Entry<String,Object> entry = objects.next();
			tuples.put(entry.getKey(), entry.getValue());
		}        	
		payload = tuples.build();
    }
    return new MutableMessage<>(payload, input.getHeaders());
}
 
Example #5
Source File: DomainEventService.java    From event-store-demo with GNU General Public License v3.0 6 votes vote down vote up
@Transactional
public void processDomainEvent( final Tuple event ) {
    log.debug( "processDomainEvent : enter" );

    log.debug( "processDomainEvent : event[{}] ", event );

    String eventType = event.getString( "eventType" );
    switch ( eventType ) {

        case "BoardInitialized":
            processBoardInitialized( event );
            break;

        default:
            processBoardEvent( event );
            break;
    }

    log.debug( "processDomainEvent : calling publisher.sendNotification( event )" );
    this.publisher.sendNotification( event );

    log.debug( "processDomainEvent : exit" );
}
 
Example #6
Source File: TensorTupleConverterTest.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Test
public void longArray() {
	long[][] inLongArray = new long[2][2];
	inLongArray[0][0] = 0;
	inLongArray[0][1] = 1;
	inLongArray[1][0] = 2;
	inLongArray[1][1] = 3;

	Tensor inTensor = Tensor.create(inLongArray);

	Tuple tuple = TensorTupleConverter.toTuple(inTensor);
	Tensor outTensor = TensorTupleConverter.toTensor(tuple);

	long[][] outLongArray = new long[2][2];
	outLongArray = outTensor.copyTo(outLongArray);

	compareTensors(inTensor, outTensor);
	assertArrayEquals(inLongArray, outLongArray);
}
 
Example #7
Source File: TensorTupleConverter.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
public static Tuple toTuple(Tensor tensor) {
	ByteBuffer buffer = ByteBuffer.allocate(tensor.numBytes());
	tensor.writeTo(buffer);

	// Retrieve all bytes in the buffer
	buffer.clear();
	byte[] bytes = new byte[buffer.capacity()];

       buffer.get(bytes, 0, bytes.length);

	return TupleBuilder.tuple()
			.put(TF_DATA_TYPE, tensor.dataType().name())
			.put(TF_SHAPE, tensor.shape())
			.put(TF_VALUE, bytes)
			.build();
}
 
Example #8
Source File: BoardEventNotificationSink.java    From event-store-demo with GNU General Public License v3.0 6 votes vote down vote up
@StreamListener( Sink.INPUT )
public void processNotification( final String json ) {
    log.debug( "processNotification : enter" );

    Tuple event = TupleBuilder.fromString( json );

    Assert.hasText( event.getString( "eventType" ), "eventType not set" );
    Assert.hasText( event.getString( "boardUuid" ), "boardUuid not set" );
    Assert.hasText( event.getString( "occurredOn" ), "occurredOn not set" );

    String eventType = event.getString( "eventType" );
    if( eventType.equals( "BoardInitialized" ) ) {
        log.debug( "processNotification : exit, no board should exist in cache if 'BoardInitialized' event is received" );

        return;
    }

    this.service.uncacheTarget( UUID.fromString( event.getString( "boardUuid" ) ) );

    log.debug( "processNotification : exit" );
}
 
Example #9
Source File: GatewayConfig.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public GatewayFilter apply(Tuple args) {
	return (exchange, chain) -> exchange.getSession()
		.map(webSession -> {
			log.debug("Session id: " + webSession.getId());
			webSession.getAttributes().entrySet()
				.forEach(entry ->
				log.debug(entry.getKey() + " => " +
									entry.getValue()));
			return webSession;
		})
		.map(WebSession::save)
		.then(chain.filter(exchange));
}
 
Example #10
Source File: PmmlProcessorConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
private MutableMessage<?> convertToMutable(Message<?> input) {
	Object payload = input.getPayload();
	if (payload instanceof Tuple && !(payload instanceof MutableTuple)) {
		payload = TupleBuilder.mutableTuple().putAll((Tuple) payload).build();
	}
	return new MutableMessage<>(payload, input.getHeaders());
}
 
Example #11
Source File: FieldValueCounterSinkConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
private void processValueForCounter(String counterName, Object value, String[] path) {
	String key = path[0];
	Object result = null;
	if (value instanceof List) {
		for (Object item : (List<?>) value) {
			processValueForCounter(counterName, item, path);
		}
	}
	else if (value instanceof Tuple) {
		Tuple t = (Tuple) value;
		if (t.hasFieldName(key)) {
			result = t.getValue(key);
		}
	}
	else if (value instanceof Map) {
		result = ((Map<?, ?>) value).get(key);
	}
	if (result != null) {
		if (path.length == 1) {
			processValue(counterName, result);
		}
		else {
			path = Arrays.copyOfRange(path, 1, path.length);
			processValueForCounter(counterName, result, path);
		}
	}
}
 
Example #12
Source File: LinearRegressionTensorflowProcessorIntegrationTests.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test(expected = MessageHandlingException.class)
public void testEvaluationIncorrectTupleInput() {
	Tuple incompleteInputTuple = TupleBuilder.tuple()
			//	missing data type
			.put(TF_SHAPE, new long[0])
			.put(TF_VALUE, new byte[0])
			.build();
	testEvaluation(incompleteInputTuple);
}
 
Example #13
Source File: TensorTupleConverter.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
public static Tensor toTensor(Tuple tuple) {
	DataType dataType = DataType.valueOf(tuple.getString(TF_DATA_TYPE));
	long[] shape = (long[]) tuple.getValue(TF_SHAPE);
	byte[] bytes = (byte[]) tuple.getValue(TF_VALUE);

	return Tensor.create(dataType, shape, ByteBuffer.wrap(bytes));
}
 
Example #14
Source File: TensorFlowService.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
private Tensor toFeedTensor(Object value) {
	if (value instanceof Tensor) {
		return (Tensor) value;
	}
	else if (value instanceof Tuple) {
		return TensorTupleConverter.toTensor((Tuple) value);
	}

	return Tensor.create(value);
}
 
Example #15
Source File: TensorflowProcessorConfiguration.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "tensorflowOutputConverter")
public TensorflowOutputConverter tensorflowOutputConverter() {
	// Default implementations serializes the Tensor into Tuple
	return new TensorflowOutputConverter<Tuple>() {
		@Override
		public Tuple convert(Tensor tensor, Map<String, Object> processorContext) {
			return TensorTupleConverter.toTuple(tensor);
		}
	};
}
 
Example #16
Source File: NotificationPublisherImpl.java    From event-store-demo with GNU General Public License v3.0 5 votes vote down vote up
@Publisher( channel = Source.OUTPUT )
public Message<String> sendNotification( Tuple event ) {

    String payload = converter.convert( event );

    return MessageBuilder
            .withPayload( payload )
            .setHeader( "x-delay", 1000 )
            .build();
}
 
Example #17
Source File: TupleToJsonStringConverter.java    From event-store-demo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String convert( Tuple source ) {
    ObjectNode root = toObjectNode(source);
    String json = null;
    try {
        json = mapper.writeValueAsString(root);
    }
    catch (Exception e) {
        throw new IllegalArgumentException("Tuple to string conversion failed", e);
    }
    return json;
}
 
Example #18
Source File: EventStoreController.java    From event-store-demo with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping( "/" )
public ResponseEntity saveEvent( @RequestBody String json ) {

    Tuple event = TupleBuilder.fromString( json );

    Assert.isTrue( event.hasFieldName( "eventType" ), "eventType is required" );
    Assert.isTrue( event.hasFieldName( "boardUuid" ), "boardUuid is required" );
    Assert.isTrue( event.hasFieldName( "occurredOn" ), "occurredOn is required" );

    this.service.processDomainEvent( event );

    return ResponseEntity
            .accepted()
            .build();
}
 
Example #19
Source File: GatewayConfig.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public GatewayFilter apply(Tuple args) {
	return (exchange, chain) -> exchange.getSession()
		.map(webSession -> {
			log.debug("Session id: " + webSession.getId());
			webSession.getAttributes().entrySet()
				.forEach(entry ->
				log.debug(entry.getKey() + " => " +
									entry.getValue()));
			return webSession;
		})
		.map(WebSession::save)
		.then(chain.filter(exchange));
}
 
Example #20
Source File: JsonStringToTupleConverter.java    From event-store-demo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Tuple convert(byte[] source) {
    if (source == null) {
        return null;
    }
    try {
        return jsonNodeToTupleConverter.convert( mapper.readTree( source ) );
    }
    catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}
 
Example #21
Source File: TupleToJsonStringConverter.java    From event-store-demo with GNU General Public License v3.0 5 votes vote down vote up
private ObjectNode toObjectNode(Tuple source) {
    ObjectNode root = mapper.createObjectNode();
    for (int i = 0; i < source.size(); i++) {
        Object value = source.getValues().get(i);
        String name = source.getFieldNames().get(i);
        if (value == null) {
            root.putNull(name);
        } else {
            root.putPOJO(name, toNode(value));
        }
    }
    return root;
}
 
Example #22
Source File: FieldValueCounterSinkTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
public void setTest(Tuple test) {
	this.test = test;
}
 
Example #23
Source File: FieldValueCounterSinkTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
public Tuple getTest() {
	return this.test;
}
 
Example #24
Source File: DomainEventService.java    From event-store-demo with GNU General Public License v3.0 4 votes vote down vote up
private void processBoardEvent( final Tuple event ) {
    log.debug( "processBoardEvent : enter " );

    String boardUuid = event.getString( "boardUuid" );

    this.domainEventsRepository.findById( boardUuid )
            .ifPresent( found -> {
                log.debug( "processBoardEvent : a DomainEventsEntity[{}] was found for boardUuid[{}]. ", found, boardUuid );

                DomainEventEntity domainEventEntity = new DomainEventEntity();
                domainEventEntity.setId( UUID.randomUUID().toString() );

                Instant occurredOn = Instant.parse( event.getString( "occurredOn" ) );
                domainEventEntity.setOccurredOn( LocalDateTime.ofInstant( occurredOn, ZoneOffset.UTC ) );

                domainEventEntity.setData( toJsonStringConverter.convert( event ) );

                found.getDomainEvents().add( domainEventEntity );
                this.domainEventsRepository.save( found );

            });

}
 
Example #25
Source File: DomainEventService.java    From event-store-demo with GNU General Public License v3.0 4 votes vote down vote up
private void processBoardInitialized( final Tuple event ) {
    log.debug( "processBoardInitialized : enter " );

    String boardUuid = event.getString( "boardUuid" );

    DomainEventsEntity domainEventsEntity = new DomainEventsEntity( boardUuid );

    DomainEventEntity domainEventEntity = new DomainEventEntity();
    domainEventEntity.setId( UUID.randomUUID().toString() );

    Instant occurredOn = Instant.parse( event.getString( "occurredOn" ) );
    domainEventEntity.setOccurredOn( LocalDateTime.ofInstant( occurredOn, ZoneOffset.UTC ) );

    domainEventEntity.setData( this.toJsonStringConverter.convert( event ) );

    domainEventsEntity.getDomainEvents().add( domainEventEntity );

    this.domainEventsRepository.save( domainEventsEntity );

}
 
Example #26
Source File: FieldValueCounterSinkConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
private void processTuple(String counterName, Tuple tuple) {
	String[] path = StringUtils.tokenizeToStringArray(fvcSinkProperties.getFieldName(), ".");
	processValueForCounter(counterName, tuple, path);
}
 
Example #27
Source File: TensorTupleConverterTest.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 3 votes vote down vote up
@Test
public void longScalar() {
	long inLong = 666;

	Tensor inTensor = Tensor.create(inLong);

	Tuple tuple = TensorTupleConverter.toTuple(inTensor);

	Tensor outTensor = TensorTupleConverter.toTensor(tuple);

	compareTensors(inTensor, outTensor);
	assertEquals(inLong, outTensor.longValue());
}
 
Example #28
Source File: DomainEventServiceTests.java    From event-store-demo with GNU General Public License v3.0 3 votes vote down vote up
@Test
public void testProcessBoardInitializedEvent() throws Exception {

    this.service.processDomainEvent( TupleBuilder.fromString( BOARD_INITIALIZED_EVENT ) );

    verify( this.repository, times( 1 ) ).save( any( DomainEventsEntity.class ) );
    verify( this.notificationPublisher, times( 1 ) ).sendNotification( any( Tuple.class ) );

}
 
Example #29
Source File: DomainEventServiceTests.java    From event-store-demo with GNU General Public License v3.0 3 votes vote down vote up
@Test
public void testProcessBoardRenamedEvent() throws Exception {

    DomainEventsEntity domainEventsEntity = createDomainEventsEntity();
    when( this.repository.findById( anyString() ) ).thenReturn( Optional.of( domainEventsEntity ) );

    this.service.processDomainEvent( TupleBuilder.fromString( BOARD_RENAMED_EVENT ) );

    verify( this.repository, times( 1 ) ).findById( anyString() );
    verify( this.repository, times( 1 ) ).save( any( DomainEventsEntity.class ) );
    verify( this.notificationPublisher, times( 1 ) ).sendNotification( any( Tuple.class ) );

}
 
Example #30
Source File: NotificationPublisherTests.java    From event-store-demo with GNU General Public License v3.0 3 votes vote down vote up
@Test
public void testSendNotification() throws Exception {

    BlockingQueue<Message<?>> messages = collector.forChannel( source.output() );

    Tuple event = TupleBuilder.fromString( BOARD_INITIALIZED_EVENT );
    this.notificationPublisher.sendNotification( event );

    assertThat( messages, receivesPayloadThat( is( BOARD_INITIALIZED_EVENT ) ) );

}