spring ws MessageEndpoint vs PayloadEndpoint - spring-ws

What is the difference here? Can you give an example. Thanks in advance
From the source for PayLoadEndpoint I see
Source invoke(Source request) throws Exception;
In MessageEndpoint I see
void invoke(MessageContext messageContext) throws Exception;
What is the use of both options

As far as I can make up from the javadoc, the PayloadEndpoint is used when you just want the message payload (the content of the incoming message) and MessageEndpoint is used when you need the complete MessageContext (including request/response, and so on).
Check out:
- PayloadEndpoint
- MessageEndpoint

Related

Q: Using Circuit Breaker in SAP Cloud SDK resilience

When I tried to use ResilienceDecorator.executeCallable() to enable circuit breaker, I have to throw out ResilienceRuntimeException in my callable to make the circuit break work. Sample code as below. Without it, circuit breaker is always closed. is this the right way to do it?
response = ResilienceDecorator.executeCallable(() -> {
HttpResponse response1 = tryHttpClient.get().execute(request);
if (response1.getStatusLine().getStatusCode() == 404){
throw new ResilienceRuntimeException("404 error is raised when calling SB api");
}
return response1;
},
ResilienceConfiguration.of(SubscriptionBillingAdapter.class).isolationMode(ResilienceIsolationMode.TENANT_OPTIONAL).timeLimiterConfiguration(ResilienceConfiguration.TimeLimiterConfiguration.of().timeoutDuration(Duration.ofSeconds(6L))).circuitBreakerConfiguration(ResilienceConfiguration.CircuitBreakerConfiguration.of().waitDuration(Duration.ofSeconds(600000L)).failureRateThreshold(1).closedBufferSize(1).halfOpenBufferSize(1)),
e -> {LOG.warn("resiliience fallback call: " + e); return response1;});
I am asking since I don't see any document of it. Also when I check how destination configuration in SCP is retrieved, I saw the following code in com.sap.cloud.sdk.cloudplatform.connectivity.DestinationService . It doesn't throw out ResilienceRuntimeException, when using ResilienceDecorator.executeCallable(). so my question is do I need to throw out ResilienceRuntimeException or not to make circuit breaker work? if I don't need, anything wrong in my code?
return (String)ResilienceDecorator.executeCallable(() -> {
XsuaaCredentials xsuaaCredentials = (new ServiceCredentialsRetriever()).getClientCredentials("destination");
AccessToken accessToken;
if (propagateUser) {
accessToken = xsuaaService.retrieveAccessTokenViaUserTokenExchange(xsuaaCredentials.getXsuaaUri(), xsuaaCredentials.getCredentials(), useProviderTenant);
} else {
accessToken = xsuaaService.retrieveAccessTokenViaClientCredentialsGrant(xsuaaCredentials.getXsuaaUri(), xsuaaCredentials.getCredentials(), useProviderTenant);
}
return this.fetchDestinationsJson(servicePath, accessToken);
}, ResilienceConfiguration.of(DestinationService.class).isolationMode(ResilienceIsolationMode.TENANT_OPTIONAL).timeLimiterConfiguration(TimeLimiterConfiguration.of().timeoutDuration(Duration.ofSeconds(6L))).circuitBreakerConfiguration(CircuitBreakerConfiguration.of().waitDuration(Duration.ofSeconds(6L))));
Steven
I'm not the most experienced in this specific part, but looking at your code it seems fine to me. When a server returns 404 Not found it's not an indication of a service failure or error, but that resource is simply not found. If in your case 404 means that an error took place and the request has to be retried with a resilient approach, you have to throw that exception to inform Resilience4J that smth went wrong.
While we're working on improving our documentation, I recommend you take a look at the existing tutorial explaining resilience within the SAP Cloud SDK context. There we also throw ResilienceRuntimeException for clarity:
public List<BusinessPartner> execute() {
return ResilienceDecorator.executeSupplier(this::run, myResilienceConfig, e -> {
logger.warn("Fallback called because of exception.", e);
return Collections.emptyList();
});
}
private List<BusinessPartner> run() {
try {
return businessPartnerService
.getAllBusinessPartner()
.select(BusinessPartner.BUSINESS_PARTNER,
BusinessPartner.LAST_NAME,
BusinessPartner.FIRST_NAME,
BusinessPartner.IS_MALE,
BusinessPartner.IS_FEMALE,
BusinessPartner.CREATION_DATE,
BusinessPartner.TO_BUSINESS_PARTNER_ADDRESS
.select(BusinessPartnerAddress.CITY_NAME,
BusinessPartnerAddress.COUNTRY,
BusinessPartnerAddress.TO_EMAIL_ADDRESS
.select(AddressEmailAddress.EMAIL_ADDRESS)
)
)
.filter(BusinessPartner.BUSINESS_PARTNER_CATEGORY.eq(CATEGORY_PERSON))
.orderBy(BusinessPartner.LAST_NAME, Order.ASC)
.top(200)
.execute(destination);
} catch (ODataException e) {
throw new ResilienceRuntimeException(e);
}
}
Regarding the code snippet from the DestinationService, I believe that fetchDestinationsJson() method throws an implicit exception thus letting Resilience4J know that smth went wrong. While in your case HttpClient won't throw anything when receiving 404 as it's a correct response code as any other.
I also think that checking CircuitsBreaker examples from Resilience4J library might be helpful.
I hope it helps:)
No you do not have to throw a ResilienceRuntimeException. In fact the SDK only uses that to wrap checked and unchecked exceptions into an unchecked exception which wraps all kinds of failures that occur within a resilient call.
Please expand your question with more details, I'll then expand this answer:
Which version of the SDK are you using?
How (and how often) do you invoke the decorated callable? Please expand the code block.
Please specify the exact behaviour you observe. What exception is thrown when you invoke the decorated callable? If the circuit breaker opens this should be a CallNotPermittedException wrapped inside a ResilienceRuntimeException
Reduce the callable to simply throw an exception in order to simplify the code
Reduce the resilience configuration to only use a circuit breaker (leverage ResilienceConfiguration.empty()). If that works add stuff back in again until it doesn't.
For reference also please find the documentation of resilience4j which the SDK uses under the hood to perform resilient operations.

catch any error in angular dart (like angular's ErrorHandler)

I need to catch any front end (angulardart) error and send it back to the server.
I saw there is something like his in regular Angular ErrorHandler, but I can't find any equivalent in angular dart (or dart it self).
Maybe I should hack the Exception object's constructor, but I don't find it a good approach (assuming it's possible)
any hints please?
In Dart it's quite similar:
#Injectable()
class ErrorHandler implements ExceptionHandler {
ApplicationRef _appRef;
ErrorHandler(Injector injector) {
// prevent DI circular dependency
new Future<Null>.delayed(Duration.ZERO, () {
_appRef = injector.get(ApplicationRef) as ApplicationRef;
});
}
#override
void call(dynamic exception, [dynamic stackTrace, String reason]) {
final stackTraceParam = stackTrace is StackTrace
? stackTrace
: (stackTrace is String
? new StackTrace.fromString(stackTrace)
: (stackTrace is List
? new StackTrace.fromString(stackTrace.join('\n'))
: null));
_log.shout(reason ?? exception, exception, stackTraceParam);
// We can try to get an error shown, but don't assume the app is
// in a healthy state after this error handler was reached.
// You can for example still instruct the user to reload the
// page with danger to cause hare because of inconsistent
// application state..
// To get changes shown, we need to explicitly invoke change detection.
_appRef?.tick();
}
}
Provide the error handler
return bootstrap(AppComponent, [const Provide(ExceptionHandler, useClass: ErrorHandler)]);
For errors that might be caused outside Angular, see also How to catch all uncaught errors in a dart polymer app?

NotSupportedException during the execution of Membership.GetUserNameByEmail(string email)

Why I cannot execute the following code? (It throws the exception: NotSupportedException)
Membership.FindUsersByEmail(model.Email);
I probably missed some configurations, could you please indicate what should I have to do?
(I am working with a SimpleMembershipProvider)
The simple providers do not support many of the old APIs, and will return NotSupportedException if called.
Unsupported MembershipProvider functions are:
CreateUser
GetUser (by providerUserKey)
GetUserNameByEmail
FindUserByUserName
FindUserByEmail
GetAllUsers
FindUsersByName
FindUsersByEmail
UnlockUser
ChangePasswordQuestionAndAnswer
GetNumberOfUsersOnline
GetPassword
ResetPassword
You can find more details here: http://www.codeproject.com/Articles/637428/SimpleMembershipProvider-vs-MembershipProvider

Vaadin "A connector with id xy is already registered"

Somewhere in my Vaadin application, I'm getting this exception as soon as I connect using a second browser
Caused by: java.lang.RuntimeException: A connector with id 22 is already registered!
at com.vaadin.ui.ConnectorTracker.registerConnector(ConnectorTracker.java:133)
It happens always in the same place but I don't know why exactly as the reason for this must be somewhere else.
I think I might be stealing UI components from the other session - which is not my intention.
Currently, I don't see any static instances of UI components I might be using in multiple sessions.
How can I debug this? It's become quite a large project.
Any hints to look for?
Yes, this usually happens because you are attaching a component already attached in other session.
Try logging the failed connector with a temporal ConnectorTracker, So the next time that it happens, you can catch it.
For example:
public class SomeUI extends UI {
private ConnectorTracker tracker;
#Override
public ConnectorTracker getConnectorTracker() {
if (this.tracker == null) {
this.tracker = new ConnectorTracker(this) {
#Override
public void registerConnector(ClientConnector connector) {
try {
super.registerConnector(connector);
} catch (RuntimeException e) {
getLogger().log(Level.SEVERE, "Failed connector: {0}", connector.getClass().getSimpleName());
throw e;
}
}
};
}
return tracker;
}
}
I think I might be stealing UI components from the other session - which is not my intention. Currently, I don't see any static instances of UI components I might be using in multiple sessions.
That was it. I was actually stealing UI components without prior knowledge.
It was very well hidden in a part which seems to be same for all instances. Which is true: the algorithm is the same.
Doesn't mean I should've reused the same UI components as well...
Thanks to those who took a closer look.
Here is how I fixed it -
1) look for components you have shared across sessions. For example if you have declared a component as static it will be created once and will be shared.
2) if you are not able to find it and want a work around until you figure out the real problem, put your all addComponent calls in try and in catch add following code -
getUI().getConnectorTracker().markAllConnectorsDirty();
getUI().getConnectorTracker().markAllClientSidesUnititialized();
getPage().reload():
This will clear old connectors and will reload the page properly only when it fails. For me it was failing when I was logged out and logged in back.
Once you find the real problem you can fix it till then inform your customers about the reload.
**** note - only solution is to remove shared components this is just a work around.
By running your application in debug mode (add ?debug at the end of URL in browser) you will be able to browse to the component, e.g:
-UIConnector(0)
--VerticalLayoutConnector(1)
---...
---LabelConnector(22)
where 22 is id from your stack trace. Find this component in your code and make sure that it is not static (yes, I saw such examples).

Grails Services / Transactions / RuntimeException / Testing

I'm testing come code in a service with transactional set to true , which talks
to a customer supplied web service the main part of which looks like
class BarcodeService {
..
/// some stuff ...
try{
cancelBarCodeResponse = cancelBarCode(cancelBarcodeRequest)
} catch(myCommsException e) {
throw new RuntimeException(e)
}
...
where myCommsException extends Exception ..
I have a test which looks like
// As no connection from my machine, it should fail ..
shouldFailWithCause(RuntimeException){
barcodeServices.cancelBarcodeDetails()
}
The test fails cause it's catching a myCommsException rather than the
RuntimeException i thought i'd converted it to .. Anyone care to point out what
i'm doing wrong ? Also will the fact that it's not a RuntimeException mean any
transaction related info done before my try/catch actually be written out rather
than thrown away ??
Thanks
From what I see, it looks ok. The problem might be in the ///some stuff and the ... parts of the code. Use a debugger to find out exactly where the exception is being thrown.

Resources