_route parameter from Request is null with a custom operation - api-platform.com

In my Event plugged on KernelEvents::RESPONSE => EventPriorities::PRE_READ when I check the _route attribute in a custom operation I received null as _route
I'm running a SF 4.2.7 and api-platform/core 2.3.4 and api-platform/api-pack 1.1.0
There is my entity annotation for this operation
subresourceOperations={
* "validate_user"={
* "path"="/legal_documents/{id}/validate",
* "method"="PUT",
* "controller"=LegalDocumentValidate::class
* }
* }
And there's the Controller annotation
#Route(
* name="api_legal_documents_validate_user",
* path="/legal_documents/{id}/validate",
* methods={"PUT"},
* defaults={
* "_api_resource_class"=LegalDocument::class,
* "_api_item_operation_name"="validate_user"
* }
* )
In my EventSubscriber when I dump the _route parameter I have null and a second dump with the good value, it's only with the custom operations, if I try on a operation handle by api-platform I have only 1 dump which shows the good value

It was caused by an exception triggered before the event who was dumping the _route attribute
When you're in a Exception Event the route appears to be null

Related

SeekToCurrentErrorHandler with RetryableException handling (and not NotRetryableException)

Actual SeekToCurrentErrorHandler has the ability to add not retryable exception, meaning all exception are retryable, except the initial one, and added X, Y, Z exceptions.
Stupid question : Is there a simple way to do the opposite : all exception are not retryable, except X', Y', Z'...
Yes, it is possible see this configuration method of that class:
/**
* Set an exception classifications to determine whether the exception should cause a retry
* (until exhaustion) or not. If not, we go straight to the recoverer. By default,
* the following exceptions will not be retried:
* <ul>
* <li>{#link DeserializationException}</li>
* <li>{#link MessageConversionException}</li>
* <li>{#link MethodArgumentResolutionException}</li>
* <li>{#link NoSuchMethodException}</li>
* <li>{#link ClassCastException}</li>
* </ul>
* All others will be retried.
* When calling this method, the defaults will not be applied.
* #param classifications the classifications.
* #param defaultValue whether or not to retry non-matching exceptions.
* #see BinaryExceptionClassifier#BinaryExceptionClassifier(Map, boolean)
* #see #addNotRetryableExceptions(Class...)
*/
public void setClassifications(Map<Class<? extends Throwable>, Boolean> classifications, boolean defaultValue) {
So, to make everything not-retryable you need to provide a default value as false.
The map should then container those exception you'd like to have retryable with the value for keys as true.

Which AmqpEvent or AmqpException to handle when an exclusive consumer fails

I have two instances of the same application, running in different virtual machines. I want to grant exclusive access to a queue for the consumer of one of them, while invalidating the local cache that is used by the consumer on the other.
Now, I have figured out that I need to handle ListenerContainerConsumerFailedEvent but I am guessing that implementing an ApplicationListener for this event is not going to ensure that I am receiving this event because of an exclusive consumer exception. I might want to check the Throwable of the event, or event further checks.
Which subclass of AmqpException or what further checks should I perform to ensure that the exception is received due to exclusive consumer access?
The logic in the listener container implementations is like this:
if (e.getCause() instanceof ShutdownSignalException
&& e.getCause().getMessage().contains("in exclusive use")) {
getExclusiveConsumerExceptionLogger().log(logger,
"Exclusive consumer failure", e.getCause());
publishConsumerFailedEvent("Consumer raised exception, attempting restart", false, e);
}
So, we indeed raise a ListenerContainerConsumerFailedEvent event and you can trace the cause message like we do in the framework, but on the other hand you can just inject your own ConditionalExceptionLogger:
/**
* Set a {#link ConditionalExceptionLogger} for logging exclusive consumer failures. The
* default is to log such failures at WARN level.
* #param exclusiveConsumerExceptionLogger the conditional exception logger.
* #since 1.5
*/
public void setExclusiveConsumerExceptionLogger(ConditionalExceptionLogger exclusiveConsumerExceptionLogger) {
and catch such an exclusive situation over there.
Also you can consider to use RabbitUtils.isExclusiveUseChannelClose(cause) in your code:
/**
* Return true if the {#link ShutdownSignalException} reason is AMQP.Channel.Close
* and the operation that failed was basicConsumer and the failure text contains
* "exclusive".
* #param sig the exception.
* #return true if the declaration failed because of an exclusive queue.
*/
public static boolean isExclusiveUseChannelClose(ShutdownSignalException sig) {

JmsMessageDrivenChannelAdapter start phase finishing observation [duplicate]

I have an integration test for my Spring Integration config, which consumes messages from a JMS topic with durable subscription. For testing, I am using ActiveMQ instead of Tibco EMS.
The issue I have is that I have to delay sending the first message to the endpoint using a sleep call at the beginning of our test method. Otherwise the message is dropped.
If I remove the setting for durable subscription and selector, then the first message can be sent right away without delay.
I'd like to get rid of the sleep, which is unreliable. Is there a way to check if the endpoint is completely setup before I send the message?
Below is the configuration.
Thanks for your help!
<int-jms:message-driven-channel-adapter
id="myConsumer" connection-factory="myCachedConnectionFactory"
destination="myTopic" channel="myChannel" error-channel="errorChannel"
pub-sub-domain="true" subscription-durable="true"
durable-subscription-name="testDurable"
selector="..."
transaction-manager="emsTransactionManager" auto-startup="false"/>
If you are using a clean embedded activemq for the test, the durability of the subscription is irrelevant until the subscription is established. So you have no choice but to wait until that happens.
You could avoid the sleep by sending a series of startup messages and only start the real test when the last one is received.
EDIT
I forgot that there is a methodisRegisteredWithDestination() on the DefaultMessageListenerContainer.
Javadocs...
/**
* Return whether at least one consumer has entered a fixed registration with the
* target destination. This is particularly interesting for the pub-sub case where
* it might be important to have an actual consumer registered that is guaranteed
* not to miss any messages that are just about to be published.
* <p>This method may be polled after a {#link #start()} call, until asynchronous
* registration of consumers has happened which is when the method will start returning
* {#code true} – provided that the listener container ever actually establishes
* a fixed registration. It will then keep returning {#code true} until shutdown,
* since the container will hold on to at least one consumer registration thereafter.
* <p>Note that a listener container is not bound to having a fixed registration in
* the first place. It may also keep recreating consumers for every invoker execution.
* This particularly depends on the {#link #setCacheLevel cache level} setting:
* only {#link #CACHE_CONSUMER} will lead to a fixed registration.
*/
We use it in some channel tests, where we get the container using reflection and then poll the method until we are subscribed to the topic.
/**
* Blocks until the listener container has subscribed; if the container does not support
* this test, or the caching mode is incompatible, true is returned. Otherwise blocks
* until timeout milliseconds have passed, or the consumer has registered.
* #see DefaultMessageListenerContainer#isRegisteredWithDestination()
* #param timeout Timeout in milliseconds.
* #return True if a subscriber has connected or the container/attributes does not support
* the test. False if a valid container does not have a registered consumer within
* timeout milliseconds.
*/
private static boolean waitUntilRegisteredWithDestination(SubscribableJmsChannel channel, long timeout) {
AbstractMessageListenerContainer container =
(AbstractMessageListenerContainer) new DirectFieldAccessor(channel).getPropertyValue("container");
if (container instanceof DefaultMessageListenerContainer) {
DefaultMessageListenerContainer listenerContainer =
(DefaultMessageListenerContainer) container;
if (listenerContainer.getCacheLevel() != DefaultMessageListenerContainer.CACHE_CONSUMER) {
return true;
}
while (timeout > 0) {
if (listenerContainer.isRegisteredWithDestination()) {
return true;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
timeout -= 100;
}
return false;
}
return true;
}

What is the difference between Rx.Observable subscribe and forEach

After creating an Observable like so
var source = Rx.Observable.create(function(observer) {...});
What is the difference between subscribe
source.subscribe(function(x) {});
and forEach
source.forEach(function(x) {});
In the ES7 spec, which RxJS 5.0 follows (but RxJS 4.0 does not), the two are NOT the same.
subscribe
public subscribe(observerOrNext: Observer | Function, error: Function, complete: Function): Subscription
Observable.subscribe is where you will do most of your true Observable handling. It returns a subscription token, which you can use to cancel your subscription. This is important when you do not know the duration of the events/sequence you have subscribed to, or if you may need to stop listening before a known duration.
forEach
public forEach(next: Function, PromiseCtor?: PromiseConstructor): Promise
Observable.forEach returns a promise that will either resolve or reject when the Observable completes or errors. It is intended to clarify situations where you are processing an observable sequence of bounded/finite duration in a more 'synchronous' manner, such as collating all the incoming values and then presenting once, by handling the promise.
Effectively, you can act on each value, as well as error and completion events either way. So the most significant functional difference is the inability to cancel a promise.
I just review the latest code available, technically the code of foreach is actually calling subscribe in RxScala, RxJS, and RxJava. It doesn't seems a big different. They now have a return type allowing user to have an way for stopping a subscription or similar.
When I work on the RxJava earlier version, the subscribe has a subscription return, and forEach is just a void. Which you may see some different answer due to the changes.
/**
* Subscribes to the [[Observable]] and receives notifications for each element.
*
* Alias to `subscribe(T => Unit)`.
*
* $noDefaultScheduler
*
* #param onNext function to execute for each item.
* #throws java.lang.IllegalArgumentException if `onNext` is null
* #throws rx.exceptions.OnErrorNotImplementedException if the [[Observable]] tries to call `onError`
* #since 0.19
* #see ReactiveX operators documentation: Subscribe
*/
def foreach(onNext: T => Unit): Unit = {
asJavaObservable.subscribe(onNext)
}
def subscribe(onNext: T => Unit): Subscription = {
asJavaObservable.subscribe(scalaFunction1ProducingUnitToAction1(onNext))
}
/**
* Subscribes an o to the observable sequence.
* #param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* #param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* #param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* #returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {
return this._subscribe(typeof oOrOnNext === 'object' ?
oOrOnNext :
observerCreate(oOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the {#link Observable} and receives notifications for each element.
* <p>
* Alias to {#link #subscribe(Action1)}
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{#code forEach} does not operate by default on a particular {#link Scheduler}.</dd>
* </dl>
*
* #param onNext
* {#link Action1} to execute for each item.
* #throws IllegalArgumentException
* if {#code onNext} is null
* #throws OnErrorNotImplementedException
* if the Observable calls {#code onError}
* #see ReactiveX operators documentation: Subscribe
*/
public final void forEach(final Action1<? super T> onNext) {
subscribe(onNext);
}
public final Disposable forEach(Consumer<? super T> onNext) {
return subscribe(onNext);
}

How to call an EventType on a goog.ui.tree.Basenode?

I am constructing a tree using the Google Closure Library. Now I want the nodes to expand on a single mouseclick, but I seem not to get it working.
I've tried calling goog.ui.component.EventType.SELECT, but it won't work.
At my tree-component class I've added the following event:
goog.events.listen(item, [goog.ui.Component.EventType.SELECT, goog.ui.tree.BaseNode.EventType.EXPAND], this.dispatchEvent, false, this);
And at my class calling the function i've added:
goog.events.listen(this._tree, [goog.ui.Component.EventType.SELECT, goog.ui.tree.BaseNode.EventType.EXPAND], this.treeClick, false, this)
Any suggestions on how I could expand my node with a single click?
I see that BaseNode is screwing up any click events:
/**
* Handles a click event.
* #param {!goog.events.BrowserEvent} e The browser event.
* #protected
* #suppress {underscore}
*/
goog.ui.tree.BaseNode.prototype.onClick_ = goog.events.Event.preventDefault;
When adding this code to the goog/demos/tree/demo.html:
goog.ui.tree.BaseNode.prototype.onClick_ = function (e) {
var qq = this.expanded_?this.collapse():this.expand();
};
The tree control expands and collapses on one click.
Tried to extend goog.ui.tree.TreeControl and override createNode to return a custom goog.ui.tree.TreeNode that overrides onClick but could not do it without getting errors. In theory you could create your custom TreeControl that expands and collapses on one click.
If you want to support non collapsable content and other features I guess you have to trigger some sort of event instead of just extend or callapse the TreeNode.
[update]
After some fiddling I got it working by subclassing TreeControl and TreeNode added the following code to goog/demos/tree/demo.html
/**
* This creates a myTreeControl object. A tree control provides a way to
* view a hierarchical set of data.
* #param {string} html The HTML content of the node label.
* #param {Object=} opt_config The configuration for the tree. See
* goog.ui.tree.TreeControl.defaultConfig. If not specified, a default config
* will be used.
* #param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* #constructor
* #extends {goog.ui.tree.BaseNode}
*/
var myTreeControl = function (html, opt_config, opt_domHelper) {
goog.ui.tree.TreeControl.call(this, html, opt_config, opt_domHelper);
};
goog.inherits(myTreeControl, goog.ui.tree.TreeControl);
/**
* Creates a new myTreeNode using the same config as the root.
* myTreeNode responds on single clicks
* #param {string} html The html content of the node label.
* #return {goog.ui.tree.TreeNode} The new item.
* #override
*/
myTreeControl.prototype.createNode = function (html) {
return new myTreeNode(html || '', this.getConfig(),
this.getDomHelper());
};
/**
* A single node in the myTreeControl.
* #param {string} html The html content of the node label.
* #param {Object=} opt_config The configuration for the tree. See
* goog.ui.tree.TreeControl.defaultConfig. If not specified, a default config
* will be used.
* #param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* #constructor
* #extends {goog.ui.tree.BaseNode}
*/
var myTreeNode = function (html, opt_config, opt_domHelper) {
goog.ui.tree.TreeNode.call(this,html, opt_config, opt_domHelper)
}
goog.inherits(myTreeNode, goog.ui.tree.TreeNode);
/**
* Handles a click event.
* #param {!goog.events.BrowserEvent} e The browser event.
* #override
*/
myTreeNode.prototype.onClick_ = function (e) {
goog.base(this, "onClick_", e);
this.onDoubleClick_(e);
};
Changed the creation of the tree variable:
tree = new myTreeControl('root', treeConfig);
Works on single clicks and have not noticed any other things breaking. I've added the annotations so it'll compile easier. You might put the declarations in a separate file with a goog.provide.
Too bad the handleMouseEvent_ of TreeControl is private or you'll just override that one but you can't without changing either TreeControl source or getting compile errors/warnings. Ach wel, jammer.

Resources