List of usage examples for org.springframework.util ObjectUtils nullSafeToString
public static String nullSafeToString(@Nullable short[] array)
From source file:org.openspaces.events.adapter.AbstractReflectionEventListenerAdapter.java
/** * Delegates the event listener invocation to the appropriate method of the configured {@link * #setDelegate(Object)}. If a single event listener delegate method is found, uses the cached * reflection Method. If more than one event listener delegate method is configured uses * reflection to dynamically find the relevant event listener method. *//*w w w. j av a 2 s. c o m*/ @Override protected Object onEventWithResult(Object data, GigaSpace gigaSpace, TransactionStatus txStatus, Object source) { Method listenerMethod = listenerMethods[0]; /* Object newValue = null, oldValue = null; boolean doubleParameter = false; if (notifyPreviousValueOnUpdate && source instanceof EntryArrivedRemoteEvent) { EntryArrivedRemoteEvent event = (EntryArrivedRemoteEvent) source; try { newValue = event.getNewObject(); oldValue = event.getOldObject(); doubleParameter = true; } catch (Exception e) { newValue = null; oldValue = null; } } // set up the arguments passed to the method Object[] listenerArguments = null; if (numberOfParameters == 1) { listenerArguments = new Object[] { data }; } else if (numberOfParameters == 2) { if (doubleParameter) { listenerArguments = new Object[] { oldValue, newValue }; } else { listenerArguments = new Object[]{ data, gigaSpace}; } } else if (numberOfParameters == 3) { if (doubleParameter) { listenerArguments = new Object[] { oldValue, newValue, gigaSpace }; } else { listenerArguments = new Object[]{ data, gigaSpace, txStatus}; } } else if (numberOfParameters == 4) { if (doubleParameter) { listenerArguments = new Object[] { oldValue, newValue, gigaSpace, txStatus }; } else { listenerArguments = new Object[]{ data, gigaSpace, txStatus, source}; } } else if (numberOfParameters == 5 && doubleParameter) { listenerArguments = new Object[] { oldValue, newValue, gigaSpace, txStatus, source}; } */ // set up the arguments passed to the method Object[] listenerArguments = null; if (numberOfParameters == 1) { listenerArguments = new Object[] { data }; } else if (numberOfParameters == 2) { listenerArguments = new Object[] { data, gigaSpace }; } else if (numberOfParameters == 3) { listenerArguments = new Object[] { data, gigaSpace, txStatus }; } else if (numberOfParameters == 4) { listenerArguments = new Object[] { data, gigaSpace, txStatus, source }; } Object result = null; if (listenerMethods.length == 1) { // single method, use the already obtained Method to invoke the listener try { result = fastMethod.invoke(delegate, listenerArguments); } catch (IllegalAccessException ex) { throw new PermissionDeniedDataAccessException( "Failed to invoke event method [" + listenerMethod.getName() + "]", ex); } catch (InvocationTargetException ex) { throw new ListenerExecutionFailedException( "Listener event method [" + listenerMethod.getName() + "] of class [" + listenerMethod.getDeclaringClass().getName() + "] threw exception", ex.getTargetException()); } catch (Throwable ex) { throw new ListenerExecutionFailedException("Listener event method [" + listenerMethod.getName() + "] of class [" + listenerMethod.getDeclaringClass().getName() + "] threw exception", ex); } } else { // more than one method, we need to use reflection to find the matched method MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(getDelegate()); methodInvoker.setTargetMethod(listenerMethod.getName()); methodInvoker.setArguments(listenerArguments); try { methodInvoker.prepare(); result = methodInvoker.invoke(); } catch (InvocationTargetException ex) { throw new ListenerExecutionFailedException( "Listener method '" + listenerMethod.getName() + "' threw exception", ex.getTargetException()); } catch (Throwable ex) { throw new ListenerExecutionFailedException( "Failed to invoke target method '" + listenerMethod.getName() + "' with arguments " + ObjectUtils.nullSafeToString(listenerArguments), ex); } } return result; }
From source file:org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter.java
/** * Invoke the specified listener method. * @param methodName the name of the listener method * @param arguments the message arguments to be passed in * @return the result returned from the listener method * @throws Exception if thrown by Rabbit API methods * @see #getListenerMethodName// ww w. j a v a 2 s . co m * @see #buildListenerArguments */ protected Object invokeListenerMethod(String methodName, Object[] arguments) throws Exception { try { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(getDelegate()); methodInvoker.setTargetMethod(methodName); methodInvoker.setArguments(arguments); methodInvoker.prepare(); return methodInvoker.invoke(); } catch (InvocationTargetException ex) { Throwable targetEx = ex.getTargetException(); if (targetEx instanceof IOException) { throw new AmqpIOException((IOException) targetEx); } else { throw new ListenerExecutionFailedException("Listener method '" + methodName + "' threw exception", targetEx); } } catch (Throwable ex) { ArrayList<String> arrayClass = new ArrayList<String>(); if (arguments != null) { for (int i = 0; i < arguments.length; i++) { arrayClass.add(arguments[i].getClass().toString()); } } throw new ListenerExecutionFailedException("Failed to invoke target method '" + methodName + "' with argument type = [" + StringUtils.collectionToCommaDelimitedString(arrayClass) + "], value = [" + ObjectUtils.nullSafeToString(arguments) + "]", ex); } }
From source file:org.springframework.cloud.stream.binder.AbstractBinder.java
protected final MessageValues serializePayloadIfNecessary(Message<?> message) { Object originalPayload = message.getPayload(); Object originalContentType = message.getHeaders().get(MessageHeaders.CONTENT_TYPE); // Pass content type as String since some transport adapters will exclude // CONTENT_TYPE Header otherwise Object contentType = JavaClassMimeTypeConversion .mimeTypeFromObject(originalPayload, ObjectUtils.nullSafeToString(originalContentType)).toString(); Object payload = serializePayloadIfNecessary(originalPayload); MessageValues messageValues = new MessageValues(message); messageValues.setPayload(payload);//from www . j a v a 2 s. co m messageValues.put(MessageHeaders.CONTENT_TYPE, contentType); if (originalContentType != null && !originalContentType.toString().equals(contentType.toString())) { messageValues.put(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE, originalContentType.toString()); } return messageValues; }
From source file:org.springframework.cloud.stream.binder.DefaultBinding.java
@Override public String toString() { return " Binding [name=" + this.name + ", target=" + this.target + ", lifecycle=" + ((this.lifecycle instanceof NamedComponent) ? ((NamedComponent) this.lifecycle).getComponentName() : ObjectUtils.nullSafeToString(this.lifecycle)) + "]"; }
From source file:org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsDlqDispatch.java
@SuppressWarnings("unchecked") public void sendToDlq(byte[] key, byte[] value, int partittion) { ProducerRecord<byte[], byte[]> producerRecord = new ProducerRecord<>(this.dlqName, partittion, key, value, null);/* w ww . j a v a 2 s . c om*/ StringBuilder sb = new StringBuilder().append(" a message with key='") .append(toDisplayString(ObjectUtils.nullSafeToString(key))).append("'").append(" and payload='") .append(toDisplayString(ObjectUtils.nullSafeToString(value))).append("'").append(" received from ") .append(partittion); ListenableFuture<SendResult<byte[], byte[]>> sentDlq = null; try { sentDlq = this.kafkaTemplate.send(producerRecord); sentDlq.addCallback(new ListenableFutureCallback<SendResult<byte[], byte[]>>() { @Override public void onFailure(Throwable ex) { KafkaStreamsDlqDispatch.this.logger.error("Error sending to DLQ " + sb.toString(), ex); } @Override public void onSuccess(SendResult<byte[], byte[]> result) { if (KafkaStreamsDlqDispatch.this.logger.isDebugEnabled()) { KafkaStreamsDlqDispatch.this.logger.debug("Sent to DLQ " + sb.toString()); } } }); } catch (Exception ex) { if (sentDlq == null) { KafkaStreamsDlqDispatch.this.logger.error("Error sending to DLQ " + sb.toString(), ex); } } }
From source file:org.springframework.core.annotation.AnnotationUtils.java
/** * Post-process the supplied {@link AnnotationAttributes}. * <p>Specifically, this method enforces <em>attribute alias</em> semantics * for annotation attributes that are annotated with {@link AliasFor @AliasFor} * and replaces default value placeholders with their original default values. * @param annotatedElement the element that is annotated with an annotation or * annotation hierarchy from which the supplied attributes were created; * may be {@code null} if unknown//from w w w . j ava 2s. com * @param attributes the annotation attributes to post-process * @param classValuesAsString whether to convert Class references into Strings (for * compatibility with {@link org.springframework.core.type.AnnotationMetadata}) * or to preserve them as Class references * @param nestedAnnotationsAsMap whether to convert nested annotations into * {@link AnnotationAttributes} maps (for compatibility with * {@link org.springframework.core.type.AnnotationMetadata}) or to preserve them as * {@code Annotation} instances * @since 4.2 * @see #retrieveAnnotationAttributes(Object, Annotation, boolean, boolean) * @see #getDefaultValue(Class, String) */ static void postProcessAnnotationAttributes(@Nullable Object annotatedElement, @Nullable AnnotationAttributes attributes, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { if (attributes == null) { return; } Class<? extends Annotation> annotationType = attributes.annotationType(); // Track which attribute values have already been replaced so that we can short // circuit the search algorithms. Set<String> valuesAlreadyReplaced = new HashSet<>(); if (!attributes.validated) { // Validate @AliasFor configuration Map<String, List<String>> aliasMap = getAttributeAliasMap(annotationType); for (String attributeName : aliasMap.keySet()) { if (valuesAlreadyReplaced.contains(attributeName)) { continue; } Object value = attributes.get(attributeName); boolean valuePresent = (value != null && !(value instanceof DefaultValueHolder)); for (String aliasedAttributeName : aliasMap.get(attributeName)) { if (valuesAlreadyReplaced.contains(aliasedAttributeName)) { continue; } Object aliasedValue = attributes.get(aliasedAttributeName); boolean aliasPresent = (aliasedValue != null && !(aliasedValue instanceof DefaultValueHolder)); // Something to validate or replace with an alias? if (valuePresent || aliasPresent) { if (valuePresent && aliasPresent) { // Since annotation attributes can be arrays, we must use ObjectUtils.nullSafeEquals(). if (!ObjectUtils.nullSafeEquals(value, aliasedValue)) { String elementAsString = (annotatedElement != null ? annotatedElement.toString() : "unknown element"); throw new AnnotationConfigurationException(String.format( "In AnnotationAttributes for annotation [%s] declared on %s, " + "attribute '%s' and its alias '%s' are declared with values of [%s] and [%s], " + "but only one is permitted.", attributes.displayName, elementAsString, attributeName, aliasedAttributeName, ObjectUtils.nullSafeToString(value), ObjectUtils.nullSafeToString(aliasedValue))); } } else if (aliasPresent) { // Replace value with aliasedValue attributes.put(attributeName, adaptValue(annotatedElement, aliasedValue, classValuesAsString, nestedAnnotationsAsMap)); valuesAlreadyReplaced.add(attributeName); } else { // Replace aliasedValue with value attributes.put(aliasedAttributeName, adaptValue(annotatedElement, value, classValuesAsString, nestedAnnotationsAsMap)); valuesAlreadyReplaced.add(aliasedAttributeName); } } } } attributes.validated = true; } // Replace any remaining placeholders with actual default values for (String attributeName : attributes.keySet()) { if (valuesAlreadyReplaced.contains(attributeName)) { continue; } Object value = attributes.get(attributeName); if (value instanceof DefaultValueHolder) { value = ((DefaultValueHolder) value).defaultValue; attributes.put(attributeName, adaptValue(annotatedElement, value, classValuesAsString, nestedAnnotationsAsMap)); } } }
From source file:org.springframework.core.GenericTypeResolver.java
/** * Determine the target type for the generic return type of the given * <em>generic method</em>, where formal type variables are declared on * the given method itself.//from w w w . java 2 s . c om * * <p>For example, given a factory method with the following signature, * if {@code resolveReturnTypeForGenericMethod()} is invoked with the reflected * method for {@code creatProxy()} and an {@code Object[]} array containing * {@code MyService.class}, {@code resolveReturnTypeForGenericMethod()} will * infer that the target return type is {@code MyService}. * * <pre>{@code public static <T> T createProxy(Class<T> clazz)}</pre> * * <h4>Possible Return Values</h4> * <ul> * <li>the target return type, if it can be inferred</li> * <li>the {@linkplain Method#getReturnType() standard return type}, if * the given {@code method} does not declare any {@linkplain * Method#getTypeParameters() formal type variables}</li> * <li>the {@linkplain Method#getReturnType() standard return type}, if the * target return type cannot be inferred (e.g., due to type erasure)</li> * <li>{@code null}, if the length of the given arguments array is shorter * than the length of the {@linkplain * Method#getGenericParameterTypes() formal argument list} for the given * method</li> * </ul> * * @param method the method to introspect, never {@code null} * @param args the arguments that will be supplied to the method when it is * invoked, never {@code null} * @return the resolved target return type, the standard return type, or * {@code null} * @since 3.2 * @see #resolveReturnType */ public static Class<?> resolveReturnTypeForGenericMethod(Method method, Object[] args) { Assert.notNull(method, "method must not be null"); Assert.notNull(args, "args must not be null"); if (logger.isDebugEnabled()) { logger.debug(String.format("Resolving return type for [%s] with concrete method arguments [%s].", method.toGenericString(), ObjectUtils.nullSafeToString(args))); } final TypeVariable<Method>[] declaredTypeVariables = method.getTypeParameters(); final Type genericReturnType = method.getGenericReturnType(); final Type[] methodArgumentTypes = method.getGenericParameterTypes(); // No declared type variables to inspect, so just return the standard return type. if (declaredTypeVariables.length == 0) { return method.getReturnType(); } // The supplied argument list is too short for the method's signature, so // return null, since such a method invocation would fail. if (args.length < methodArgumentTypes.length) { return null; } // Ensure that the type variable (e.g., T) is declared directly on the method // itself (e.g., via <T>), not on the enclosing class or interface. boolean locallyDeclaredTypeVariableMatchesReturnType = false; for (TypeVariable<Method> currentTypeVariable : declaredTypeVariables) { if (currentTypeVariable.equals(genericReturnType)) { if (logger.isDebugEnabled()) { logger.debug(String.format( "Found declared type variable [%s] that matches the target return type [%s].", currentTypeVariable, genericReturnType)); } locallyDeclaredTypeVariableMatchesReturnType = true; break; } } if (locallyDeclaredTypeVariableMatchesReturnType) { for (int i = 0; i < methodArgumentTypes.length; i++) { final Type currentMethodArgumentType = methodArgumentTypes[i]; if (currentMethodArgumentType.equals(genericReturnType)) { if (logger.isDebugEnabled()) { logger.debug(String.format( "Found method argument type at index [%s] that matches the target return type.", i)); } return args[i].getClass(); } if (currentMethodArgumentType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) currentMethodArgumentType; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int j = 0; j < actualTypeArguments.length; j++) { final Type typeArg = actualTypeArguments[j]; if (typeArg.equals(genericReturnType)) { if (logger.isDebugEnabled()) { logger.debug(String.format( "Found method argument type at index [%s] that is parameterized with a type argument that matches the target return type.", i)); } if (args[i] instanceof Class) { return (Class<?>) args[i]; } else { // Consider adding logic to determine the class of the // J'th typeArg, if possible. logger.info(String.format( "Could not determine the target type for type argument [%s] for method [%s].", typeArg, method.toGenericString())); // For now, just fall back... return method.getReturnType(); } } } } } } // Fall back... return method.getReturnType(); }
From source file:org.springframework.data.keyvalue.redis.listener.adapter.MessageListenerAdapter.java
/** * Invoke the specified listener method. * @param methodName the name of the listener method * @param arguments the message arguments to be passed in * @return the result returned from the listener method * @see #getListenerMethodName//w w w.j a va2 s . c o m * @see #buildListenerArguments */ protected Object invokeListenerMethod(String methodName, Object[] arguments) { try { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(getDelegate()); methodInvoker.setTargetMethod(methodName); methodInvoker.setArguments(arguments); methodInvoker.prepare(); return methodInvoker.invoke(); } catch (InvocationTargetException ex) { Throwable targetEx = ex.getTargetException(); if (targetEx instanceof DataAccessException) { throw (DataAccessException) targetEx; } else { throw new RedisListenerExecutionFailedException( "Listener method '" + methodName + "' threw exception", targetEx); } } catch (Throwable ex) { throw new RedisListenerExecutionFailedException("Failed to invoke target method '" + methodName + "' with arguments " + ObjectUtils.nullSafeToString(arguments), ex); } }
From source file:org.springframework.data.redis.listener.adapter.MessageListenerAdapter.java
/** * Invoke the specified listener method. * // w ww . j a va 2s. c o m * @param methodName the name of the listener method * @param arguments the message arguments to be passed in * @see #getListenerMethodName */ protected void invokeListenerMethod(String methodName, Object[] arguments) { try { invoker.invoke(arguments); } catch (InvocationTargetException ex) { Throwable targetEx = ex.getTargetException(); if (targetEx instanceof DataAccessException) { throw (DataAccessException) targetEx; } else { throw new RedisListenerExecutionFailedException( "Listener method '" + methodName + "' threw exception", targetEx); } } catch (Throwable ex) { throw new RedisListenerExecutionFailedException("Failed to invoke target method '" + methodName + "' with arguments " + ObjectUtils.nullSafeToString(arguments), ex); } }
From source file:org.springframework.integration.kafka.listener.LoggingErrorHandler.java
@Override public void handle(Exception thrownException, KafkaMessage message) { log.error("Error while processing: " + ObjectUtils.nullSafeToString(message), thrownException); }