Java Code Examples for org.springframework.messaging.MessageHeaders#get()
The following examples show how to use
org.springframework.messaging.MessageHeaders#get() .
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: NegotiatingMessageConverterWrapper.java From spring-cloud-function with Apache License 2.0 | 6 votes |
@Override public Message<?> toMessage(Object payload, MessageHeaders headers, Object conversionHint) { MimeType accepted = headers.get(ACCEPT, MimeType.class); MessageHeaderAccessor accessor = new MessageHeaderAccessor(); accessor.copyHeaders(headers); accessor.removeHeader(ACCEPT); // Fall back to (concrete) 'contentType' header if 'accept' is not present. // MimeType.includes() below should then amount to equality. if (accepted == null) { accepted = headers.get(MessageHeaders.CONTENT_TYPE, MimeType.class); } if (accepted != null) { for (MimeType supportedConcreteType : delegate.getSupportedMimeTypes()) { if (accepted.includes(supportedConcreteType)) { // Note the use of setHeader() which will set the value even if already present. accessor.setHeader(MessageHeaders.CONTENT_TYPE, supportedConcreteType); Message<?> result = delegate.toMessage(payload, accessor.toMessageHeaders(), conversionHint); if (result != null) { return result; } } } } return null; }
Example 2
Source File: LocalTransactionRocketMQListener.java From fw-spring-cloud with Apache License 2.0 | 6 votes |
/** * 执行本地事务 * @param message 消息 * @param o 额外参数 * @return RocketMQ事务状态 */ @Override public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) { MessageHeaders headers = message.getHeaders(); String transicationId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID); try { FwTradeLog tradeLog = (FwTradeLog) o; orderService.payOrder(tradeLog,transicationId); // 对应图中第3步,执行本地事务 log.info("本地事务=>{} 执行成功,往RocketMQ发送COMMIT",transicationId); return RocketMQLocalTransactionState.COMMIT; // 对应图中第4步,COMMIT,半消息经过COMMIT后,消息消费端就可以消费这条消息了 } catch (Exception e){ log.info("本地事务=>{} 回滚,往RocketMQ发送ROLLBACK",transicationId ,e); return RocketMQLocalTransactionState.ROLLBACK; // 对应途中第4步,ROLLBACK } }
Example 3
Source File: DefaultSubscriptionRegistry.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException { MessageHeaders headers = (MessageHeaders) target; SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class); Object value; if ("destination".equalsIgnoreCase(name)) { value = accessor.getDestination(); } else { value = accessor.getFirstNativeHeader(name); if (value == null) { value = headers.get(name); } } return new TypedValue(value); }
Example 4
Source File: DefaultContentTypeResolver.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public MimeType resolve(MessageHeaders headers) { if (headers == null || headers.get(MessageHeaders.CONTENT_TYPE) == null) { return this.defaultMimeType; } Object value = headers.get(MessageHeaders.CONTENT_TYPE); if (value instanceof MimeType) { return (MimeType) value; } else if (value instanceof String) { return MimeType.valueOf((String) value); } else { throw new IllegalArgumentException( "Unknown type for contentType header value: " + value.getClass()); } }
Example 5
Source File: WebAuth.java From flow-platform-x with Apache License 2.0 | 6 votes |
/** * Get user object from ws message header * @param headers * @return User object * @exception AuthenticationException if Token header is missing or invalid token */ public User validate(MessageHeaders headers) { MultiValueMap<String, String> map = headers.get(StompHeaderAccessor.NATIVE_HEADERS, MultiValueMap.class); if (Objects.isNull(map)) { throw new AuthenticationException("Invalid token"); } String token = map.getFirst(HeaderToken); if (!StringHelper.hasValue(token)) { throw new AuthenticationException("Invalid token"); } Optional<User> user = authService.get(token); if (!user.isPresent()) { throw new AuthenticationException("Invalid token"); } return user.get(); }
Example 6
Source File: DefaultContentTypeResolver.java From spring-analysis-note with MIT License | 6 votes |
@Override @Nullable public MimeType resolve(@Nullable MessageHeaders headers) { if (headers == null || headers.get(MessageHeaders.CONTENT_TYPE) == null) { return this.defaultMimeType; } Object value = headers.get(MessageHeaders.CONTENT_TYPE); if (value == null) { return null; } else if (value instanceof MimeType) { return (MimeType) value; } else if (value instanceof String) { return MimeType.valueOf((String) value); } else { throw new IllegalArgumentException( "Unknown type for contentType header value: " + value.getClass()); } }
Example 7
Source File: DefaultRocketMQListenerContainer.java From rocketmq-spring with Apache License 2.0 | 5 votes |
private Message<?> doConvert(Object payload, MessageHeaders headers) { Message<?> message = this.messageConverter instanceof SmartMessageConverter ? ((SmartMessageConverter) this.messageConverter).toMessage(payload, headers, null) : this.messageConverter.toMessage(payload, headers); if (message == null) { String payloadType = payload.getClass().getName(); Object contentType = headers != null ? headers.get(MessageHeaders.CONTENT_TYPE) : null; throw new MessageConversionException("Unable to convert payload with type='" + payloadType + "', contentType='" + contentType + "', converter=[" + this.messageConverter + "]"); } MessageBuilder<?> builder = MessageBuilder.fromMessage(message); builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN); return builder.build(); }
Example 8
Source File: FunctionInvoker.java From spring-cloud-function with Apache License 2.0 | 5 votes |
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { Message requestMessage = this.generateMessage(input, context); Message<byte[]> responseMessage = (Message<byte[]>) this.function.apply(requestMessage); byte[] responseBytes = responseMessage.getPayload(); if (requestMessage.getHeaders().containsKey("httpMethod") || requestMessage.getPayload() instanceof APIGatewayProxyRequestEvent) { // API Gateway Map<String, Object> response = new HashMap<String, Object>(); response.put("isBase64Encoded", false); MessageHeaders headers = responseMessage.getHeaders(); int statusCode = headers.containsKey("statusCode") ? (int) headers.get("statusCode") : 200; response.put("statusCode", statusCode); if (isKinesis(requestMessage)) { HttpStatus httpStatus = HttpStatus.valueOf(statusCode); response.put("statusDescription", httpStatus.toString()); } String body = new String(responseMessage.getPayload(), StandardCharsets.UTF_8).replaceAll("\"", ""); response.put("body", body); Map<String, String> responseHeaders = new HashMap<>(); headers.keySet().forEach(key -> responseHeaders.put(key, headers.get(key).toString())); response.put("headers", responseHeaders); responseBytes = mapper.writeValueAsBytes(response); } StreamUtils.copy(responseBytes, output); }
Example 9
Source File: ApplicationJsonMessageMarshallingConverter.java From spring-cloud-function with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override @Nullable protected MimeType getMimeType(@Nullable MessageHeaders headers) { Object contentType = headers.get(MessageHeaders.CONTENT_TYPE); if (contentType instanceof byte[]) { contentType = new String((byte[]) contentType, StandardCharsets.UTF_8); contentType = ((String) contentType).replace("\"", ""); Map<String, Object> headersMap = (Map<String, Object>) ReflectionUtils.getField(this.headersField, headers); headersMap.put(MessageHeaders.CONTENT_TYPE, contentType); } return super.getMimeType(headers); }
Example 10
Source File: HeaderUtils.java From spring-cloud-function with Apache License 2.0 | 5 votes |
public static HttpHeaders fromMessage(MessageHeaders headers) { HttpHeaders result = new HttpHeaders(); for (String name : headers.keySet()) { Object value = headers.get(name); name = name.toLowerCase(); if (!IGNORED.containsKey(name)) { Collection<?> values = multi(value); for (Object object : values) { result.set(name, object.toString()); } } } return result; }
Example 11
Source File: MessagingMessageConverter.java From java-technology-stack with MIT License | 5 votes |
@Override public javax.jms.Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { if (!(object instanceof Message)) { throw new IllegalArgumentException("Could not convert [" + object + "] - only [" + Message.class.getName() + "] is handled by this converter"); } Message<?> input = (Message<?>) object; MessageHeaders headers = input.getHeaders(); Object conversionHint = headers.get(AbstractMessagingTemplate.CONVERSION_HINT_HEADER); javax.jms.Message reply = createMessageForPayload(input.getPayload(), session, conversionHint); this.headerMapper.fromHeaders(headers, reply); return reply; }
Example 12
Source File: DefaultSubscriptionRegistry.java From java-technology-stack with MIT License | 5 votes |
@Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) { Object value; if (target instanceof Message) { value = name.equals("headers") ? ((Message) target).getHeaders() : null; } else if (target instanceof MessageHeaders) { MessageHeaders headers = (MessageHeaders) target; SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class); Assert.state(accessor != null, "No SimpMessageHeaderAccessor"); if ("destination".equalsIgnoreCase(name)) { value = accessor.getDestination(); } else { value = accessor.getFirstNativeHeader(name); if (value == null) { value = headers.get(name); } } } else { // Should never happen... throw new IllegalStateException("Expected Message or MessageHeaders."); } return new TypedValue(value); }
Example 13
Source File: CompositeMessageConverterFactory.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
/** * @param customConverters a list of {@link AbstractMessageConverter} * @param objectMapper object mapper for for serialization / deserialization */ public CompositeMessageConverterFactory( List<? extends MessageConverter> customConverters, ObjectMapper objectMapper) { this.objectMapper = objectMapper; if (!CollectionUtils.isEmpty(customConverters)) { this.converters = new ArrayList<>(customConverters); } else { this.converters = new ArrayList<>(); } initDefaultConverters(); Field headersField = ReflectionUtils.findField(MessageHeaders.class, "headers"); headersField.setAccessible(true); DefaultContentTypeResolver resolver = new DefaultContentTypeResolver() { @Override @SuppressWarnings("unchecked") public MimeType resolve(@Nullable MessageHeaders headers) { Object contentType = headers.get(MessageHeaders.CONTENT_TYPE); if (contentType instanceof byte[]) { contentType = new String((byte[]) contentType, StandardCharsets.UTF_8); contentType = ((String) contentType).replace("\"", ""); Map<String, Object> headersMap = (Map<String, Object>) ReflectionUtils.getField(headersField, headers); headersMap.put(MessageHeaders.CONTENT_TYPE, contentType); } return super.resolve(headers); } }; resolver.setDefaultMimeType(BindingProperties.DEFAULT_CONTENT_TYPE); this.converters.stream().filter(mc -> mc instanceof AbstractMessageConverter) .forEach(mc -> ((AbstractMessageConverter) mc) .setContentTypeResolver(resolver)); }
Example 14
Source File: LocalTransactionRocketMQListener.java From fw-spring-cloud with Apache License 2.0 | 5 votes |
/** * RocketMQ回查本地事务状态 * @param message 消息 * @return RocketMQ事务状态 */ @Override public RocketMQLocalTransactionState checkLocalTransaction(Message message) { MessageHeaders headers = message.getHeaders(); String transicationId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID); log.info("RocketMQ事务状态回查=>{}",transicationId); // 从数据库中根据事务Id查询对应的事务日志,对应图中第6步 FwTransactionLog transactionLog = fwTransactionLogService.getOne( new LambdaQueryWrapper<FwTransactionLog>().eq(FwTransactionLog::getTransactionId, transicationId) ); // 对应图中的第7步骤 return transactionLog != null ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK; }
Example 15
Source File: MessagingMessageConverter.java From spring-analysis-note with MIT License | 5 votes |
@Override public javax.jms.Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { if (!(object instanceof Message)) { throw new IllegalArgumentException("Could not convert [" + object + "] - only [" + Message.class.getName() + "] is handled by this converter"); } Message<?> input = (Message<?>) object; MessageHeaders headers = input.getHeaders(); Object conversionHint = headers.get(AbstractMessagingTemplate.CONVERSION_HINT_HEADER); javax.jms.Message reply = createMessageForPayload(input.getPayload(), session, conversionHint); this.headerMapper.fromHeaders(headers, reply); return reply; }
Example 16
Source File: DestinationVariableMethodArgumentResolver.java From spring-analysis-note with MIT License | 5 votes |
@Override @Nullable @SuppressWarnings("unchecked") protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, String name) { MessageHeaders headers = message.getHeaders(); Map<String, String> vars = (Map<String, String>) headers.get(DESTINATION_TEMPLATE_VARIABLES_HEADER); return vars != null ? vars.get(name) : null; }
Example 17
Source File: DestinationVariableMethodArgumentResolver.java From spring-analysis-note with MIT License | 5 votes |
@Override @Nullable @SuppressWarnings("unchecked") protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, String name) { MessageHeaders headers = message.getHeaders(); Map<String, String> vars = (Map<String, String>) headers.get(DESTINATION_TEMPLATE_VARIABLES_HEADER); return vars != null ? vars.get(name) : null; }
Example 18
Source File: DefaultSubscriptionRegistry.java From spring-analysis-note with MIT License | 5 votes |
@Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) { Object value; if (target instanceof Message) { value = name.equals("headers") ? ((Message) target).getHeaders() : null; } else if (target instanceof MessageHeaders) { MessageHeaders headers = (MessageHeaders) target; SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class); Assert.state(accessor != null, "No SimpMessageHeaderAccessor"); if ("destination".equalsIgnoreCase(name)) { value = accessor.getDestination(); } else { value = accessor.getFirstNativeHeader(name); if (value == null) { value = headers.get(name); } } } else { // Should never happen... throw new IllegalStateException("Expected Message or MessageHeaders."); } return new TypedValue(value); }
Example 19
Source File: RocketMQUtil.java From rocketmq-spring with Apache License 2.0 | 4 votes |
private static Message getAndWrapMessage(String destination, MessageHeaders headers, byte[] payloads) { if (destination == null || destination.length() < 1) { return null; } if (payloads == null || payloads.length < 1) { return null; } String[] tempArr = destination.split(":", 2); String topic = tempArr[0]; String tags = ""; if (tempArr.length > 1) { tags = tempArr[1]; } Message rocketMsg = new Message(topic, tags, payloads); if (Objects.nonNull(headers) && !headers.isEmpty()) { Object keys = headers.get(RocketMQHeaders.KEYS); if (!StringUtils.isEmpty(keys)) { // if headers has 'KEYS', set rocketMQ message key rocketMsg.setKeys(keys.toString()); } Object flagObj = headers.getOrDefault("FLAG", "0"); int flag = 0; try { flag = Integer.parseInt(flagObj.toString()); } catch (NumberFormatException e) { // Ignore it if (log.isInfoEnabled()) { log.info("flag must be integer, flagObj:{}", flagObj); } } rocketMsg.setFlag(flag); Object waitStoreMsgOkObj = headers.getOrDefault("WAIT_STORE_MSG_OK", "true"); rocketMsg.setWaitStoreMsgOK(Boolean.TRUE.equals(waitStoreMsgOkObj)); headers.entrySet().stream() .filter(entry -> !Objects.equals(entry.getKey(), "FLAG") && !Objects.equals(entry.getKey(), "WAIT_STORE_MSG_OK")) // exclude "FLAG", "WAIT_STORE_MSG_OK" .forEach(entry -> { if (!MessageConst.STRING_HASH_SET.contains(entry.getKey())) { rocketMsg.putUserProperty(entry.getKey(), String.valueOf(entry.getValue())); } }); } return rocketMsg; }
Example 20
Source File: SendToMethodReturnValueHandler.java From spring4-understanding with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") private PlaceholderResolver initVarResolver(MessageHeaders headers) { String name = DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER; Map<String, String> vars = (Map<String, String>) headers.get(name); return new DestinationVariablePlaceholderResolver(vars); }