MSAL4j - How to handle MsalThrottlingException? - azure-active-directory

I use MSAL4j and there is an exception type named MsalThrottlingException. How can I handle it when I catch it? I need an example implementation.
try{
Future<IAuthenticationResult> future =
confidentialClientApplication.acquireToken(authorizationCodeParameters);
IAuthenticationResult authenticationResult = future.get(1, TimeUnit.MINUTES);
}
catch(ExecutionException e){
if(e.getCause() instanceof MsalThrottlingException){
//how to handle it
}
}
https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-error-handling-java
There was a document about it also(you can see the screen shot in above link), but it doesn't give a example handling implementation. Could you give an example?

This worked for me:
private static String PREFIX_RETRY_STR = "com.microsoft.aad.msal4j.MsalThrottlingException: Request was throttled according to instructions from STS. Retry in ";
private static String SUFFIX_RETRY_STR = " ms.";
(...)
if (e.getCause() instanceof MsalThrottlingException) {
int waitTime = Integer.parseInt(e.getMessage().replace(PREFIX_RETRY_STR, "").replace(SUFFIX_RETRY_STR, ""));
try {
TimeUnit.MILLISECONDS.sleep(waitTime);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
result = pca.acquireToken(parameters).join();
} else
throw e;

Related

BaseX parrallel Client

I have client like this :
import org.basex.api.client.ClientSession;
#Slf4j
#Component(value = "baseXAircrewClient")
#DependsOn(value = "baseXAircrewServer")
public class BaseXAircrewClient {
#Value("${basex.server.host}")
private String basexServerHost;
#Value("${basex.server.port}")
private int basexServerPort;
#Value("${basex.admin.password}")
private String basexAdminPassword;
#Getter
private ClientSession session;
#PostConstruct
private void createClient() throws IOException {
log.info("##### Creating BaseX client session {}", basexServerPort);
this.session = new ClientSession(basexServerHost, basexServerPort, UserText.ADMIN, basexAdminPassword);
}
}
It is a singleton injected in a service which run mulitple queries like this :
Query query = client.getSession().query(finalQuery);
return query.execute();
All threads query and share the same session.
With a single thread all is fine but with multiple thread I get some random (and weird) error, like the result of a query to as a result of another.
I feel that I should put a synchronized(){} arround query.execute() or open and close session for each query, or create a pool of session.
But I don't find any documentation how the use the session in parrallel.
Is this implementation fine for multithreading (and my issue is comming from something else) or should I do it differently ?
I ended creating a simple pool by adding removing the client from a ArrayBlockingQueue and it is working nicely :
#PostConstruct
private void createClient() throws IOException {
log.info("##### Creating BaseX client session {}", basexServerPort);
final int poolSize = 5;
this.resources = new ArrayBlockingQueue < ClientSession > (poolSize) {
{
for (int i = 0; i < poolSize; i++) {
add(initClient());
}
}
};
}
private ClientSession initClient() throws IOException {
ClientSession clientSession = new ClientSession(basexServerHost, basexServerPort, UserText.ADMIN, basexAdminPassword);
return clientSession;
}
public Query query(String finalQuery) throws IOException {
ClientSession clientSession = null;
try {
clientSession = resources.take();
Query result = clientSession.query(finalQuery);
return result;
} catch (InterruptedException e) {
log.error("Error during query execution: " + e.getMessage(), e);
} finally {
if (clientSession != null) {
try {
resources.put(clientSession);
} catch (InterruptedException e) {
log.error("Error adding to pool : " + e.getMessage(), e);
}
}
}
return null;
}

How to set a Camel exchangeProperty from a unit test

I have a bunch of unit tests that run camel routes with code like
// setup code here...
String route = "direct:someroute";
try (CamelContext context = new DefaultCamelContext()) {
Object response = runCamelRoute(context, route, ci);
checkResponse(route, response);
}
but this route expects an exchange property to be set before it gets here - how can I set it? CamelContext has a whole lot of methods but I can't seem to find something like:
CamelRoute cr = context.getRoute(route);
cr.getExchange().setProperty("propertyName", "propetyValue");
Here is my camel run method for unit testing, with a bit of extra code for setting up an Oracle connection, etc.
protected Object runCamelRoute(CamelContext context, String route, Object message) throws Exception {
context.addRoutes(new MyRouteBuilder() {
});
setupRegistry(context);
context.start();
FluentProducerTemplate template = context.createFluentProducerTemplate();
template.withBody(message)
.withHeader("hello", "goodbye")
.withProcessor(e -> e.setProperty("propertyName", "propertyValue")) // fail use header instead
.to(route);
try {
Future<Object> future = template.asyncRequest();
return future.get();
}
catch(Exception ex) {
System.out.println(route + " " + ex.getClass().getCanonicleName() + " " + ex.getMessage());
throw ex;
}
finally {
template.stop();
context.stop();
}
}
private void setupRegistry(CamelContext context) {
DataSource ds = DataSourceHelper.createConnectionPoolDev();
context.getRegistry().bind("dataSource", ds);
context.getRegistry().bind("Transformer", new Transformer());
}
public static OracleDataSource createConnectionPoolDev() {
try {
OracleDataSource ds = new OracleDataSource();
ds.setConnectionCacheName("oraCache");
ds.setURL("jdbc:oracle:thin:#//cluster:1521/server.domain.ca");
ds.setUser("user");
ds.setPassword("pass");
return ds;
}
catch (Exception ex) {
logger.error("Failed to create connection to the database " + ex.getMessage());
}
return null;
}
Something like this may be ?
context.createFluentProducerTemplate()
.withBody(...)
.withHeader(..., ...)
.withProcessor( e -> e.setProperty(propertyName, propertyValue) )
.to("direct:someroute")
.send();

hotchocolate 11 : how to replace ExceptionMiddleware by my own middleware?

Is it possible to replace the "official" ExceptionMiddleware HotChocolate classe by my own middleware classe?
I plan to "complete" the catch by including AgregationException .Net exception and create IError[] array by looping AgregationException.InnerExceptions property (see below the original ExceptionMiddleware).
I would like to replace it by my own implementation.
Is it possible ? How can I do this ?
Thanks.
Kind Regards
internal sealed class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly IErrorHandler _errorHandler;
public ExceptionMiddleware(RequestDelegate next, IErrorHandler errorHandler)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_errorHandler = errorHandler ?? throw new ArgumentNullException(nameof(errorHandler));
}
public async ValueTask InvokeAsync(IRequestContext context)
{
try
{
await _next(context).ConfigureAwait(false);
}
catch (GraphQLException ex)
{
context.Exception = ex;
context.Result = QueryResultBuilder.CreateError(_errorHandler.Handle(ex.Errors));
}
catch (Exception ex)
{
context.Exception = ex;
IError error = _errorHandler.CreateUnexpectedError(ex).Build();
context.Result = QueryResultBuilder.CreateError(_errorHandler.Handle(error));
}
}
}

CXF WS, Interceptor: stop processing, respond with fault

I'm scratching my head over this:
Using an Interceptor to check a few SOAP headers, how can I abort the interceptor chain but still respond with an error to the user?
Throwing a Fault works regarding the output, but the request is still being processed and I'd rather not have all services check for some flag in the message context.
Aborting with "message.getInterceptorChain().abort();" really aborts all processing, but then there's also nothing returned to the client.
What's the right way to go?
public class HeadersInterceptor extends AbstractSoapInterceptor {
public HeadersInterceptor() {
super(Phase.PRE_LOGICAL);
}
#Override
public void handleMessage(SoapMessage message) throws Fault {
Exchange exchange = message.getExchange();
BindingOperationInfo bop = exchange.getBindingOperationInfo();
Method action = ((MethodDispatcher) exchange.get(Service.class)
.get(MethodDispatcher.class.getName())).getMethod(bop);
if (action.isAnnotationPresent(NeedsHeaders.class)
&& !headersPresent(message)) {
Fault fault = new Fault(new Exception("No headers Exception"));
fault.setFaultCode(new QName("Client"));
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
Element detail = doc.createElementNS(Soap12.SOAP_NAMESPACE, "mynamespace");
detail.setTextContent("Missing some headers...blah");
fault.setDetail(detail);
} catch (ParserConfigurationException e) {
}
// bad: message.getInterceptorChain().abort();
throw fault;
}
}
}
Following the suggestion by Donal Fellows I'm adding an answer to my question.
CXF heavily relies on Spring's AOP which can cause problems of all sorts, at least here it did. I'm providing the complete code for you. Using open source projects I think it's just fair to provide my own few lines of code for anyone who might decide not to use WS-Security (I'm expecting my services to run on SSL only). I wrote most of it by browsing the CXF sources.
Please, comment if you think there's a better approach.
/**
* Checks the requested action for AuthenticationRequired annotation and tries
* to login using SOAP headers username/password.
*
* #author Alexander Hofbauer
*/
public class AuthInterceptor extends AbstractSoapInterceptor {
public static final String KEY_USER = "UserAuth";
#Resource
UserService userService;
public AuthInterceptor() {
// process after unmarshalling, so that method and header info are there
super(Phase.PRE_LOGICAL);
}
#Override
public void handleMessage(SoapMessage message) throws Fault {
Logger.getLogger(AuthInterceptor.class).trace("Intercepting service call");
Exchange exchange = message.getExchange();
BindingOperationInfo bop = exchange.getBindingOperationInfo();
Method action = ((MethodDispatcher) exchange.get(Service.class)
.get(MethodDispatcher.class.getName())).getMethod(bop);
if (action.isAnnotationPresent(AuthenticationRequired.class)
&& !authenticate(message)) {
Fault fault = new Fault(new Exception("Authentication failed"));
fault.setFaultCode(new QName("Client"));
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
Element detail = doc.createElementNS(Soap12.SOAP_NAMESPACE, "test");
detail.setTextContent("Failed to authenticate.\n" +
"Please make sure to send correct SOAP headers username and password");
fault.setDetail(detail);
} catch (ParserConfigurationException e) {
}
throw fault;
}
}
private boolean authenticate(SoapMessage msg) {
Element usernameNode = null;
Element passwordNode = null;
for (Header header : msg.getHeaders()) {
if (header.getName().getLocalPart().equals("username")) {
usernameNode = (Element) header.getObject();
} else if (header.getName().getLocalPart().equals("password")) {
passwordNode = (Element) header.getObject();
}
}
if (usernameNode == null || passwordNode == null) {
return false;
}
String username = usernameNode.getChildNodes().item(0).getNodeValue();
String password = passwordNode.getChildNodes().item(0).getNodeValue();
User user = null;
try {
user = userService.loginUser(username, password);
} catch (BusinessException e) {
return false;
}
if (user == null) {
return false;
}
msg.put(KEY_USER, user);
return true;
}
}
As mentioned above, here's the ExceptionHandler/-Logger. At first I wasn't able to use it in combination with JAX-RS (also via CXF, JAX-WS works fine now). I don't need JAX-RS anyway, so that problem is gone now.
#Aspect
public class ExceptionHandler {
#Resource
private Map<String, Boolean> registeredExceptions;
/**
* Everything in my project.
*/
#Pointcut("within(org.myproject..*)")
void inScope() {
}
/**
* Every single method.
*/
#Pointcut("execution(* *(..))")
void anyOperation() {
}
/**
* Log every Throwable.
*
* #param t
*/
#AfterThrowing(pointcut = "inScope() && anyOperation()", throwing = "t")
public void afterThrowing(Throwable t) {
StackTraceElement[] trace = t.getStackTrace();
Logger logger = Logger.getLogger(ExceptionHandler.class);
String info;
if (trace.length > 0) {
info = trace[0].getClassName() + ":" + trace[0].getLineNumber()
+ " threw " + t.getClass().getName();
} else {
info = "Caught throwable with empty stack trace";
}
logger.warn(info + "\n" + t.getMessage());
logger.debug("Stacktrace", t);
}
/**
* Handles all exceptions according to config file.
* Unknown exceptions are always thrown, registered exceptions only if they
* are set to true in config file.
*
* #param pjp
* #throws Throwable
*/
#Around("inScope() && anyOperation()")
public Object handleThrowing(ProceedingJoinPoint pjp) throws Throwable {
try {
Object ret = pjp.proceed();
return ret;
} catch (Throwable t) {
// We don't care about unchecked Exceptions
if (!(t instanceof Exception)) {
return null;
}
Boolean throwIt = registeredExceptions.get(t.getClass().getName());
if (throwIt == null || throwIt) {
throw t;
}
}
return null;
}
}
Short answer, the right way to abort in a client-side interceptor before the sending the request is to create the Fault with a wrapped exception :
throw new Fault(
new ClientException( // or any non-Fault exception, else blocks in
// abstractClient.checkClientException() (waits for missing response code)
"Error before sending the request"), Fault.FAULT_CODE_CLIENT);
Thanks to post contributors for helping figuring it out.
CXF allows you to specify that your interceptor goes before or after certain interceptors. If your interceptor is processing on the inbound side (which based on your description is the case) there is an interceptor called CheckFaultInterceptor. You can configure your interceptor to go before it:
public HeadersInterceptor(){
super(Phase.PRE_LOGICAL);
getBefore().add(CheckFaultInterceptor.class.getName());
}
The check fault interceptor in theory checks if a fault has occurred. If one has, it aborts the interceptor chain and invokes the fault handler chain.
I have not yet been able to test this (it is fully based on the available documentation I've come across trying to solve a related problem)

WCF Data Services UpdateObject not working

I have a Silverlight client with a grid getting data from WCF Data Service. Works fine.
However if I want to update some changed grid row, the service data context UpdateObject is not working:
DataServiceContext.UpdateObject(MyGrid.SelectedItem);
foreach (Object item in DataServiceContext.Entities)
{
//
}
DataServiceContext.BeginSaveChanges(SaveChangesOptions.Batch, OnChangesSaved, DataServiceContext);
I just have created a loop to inspect the values for the entities items and the value is not updated at all. BeginSaveChanges works fine, but it just uses not updated values.
Any ideas how to fix that?
thanks
Right a fully flushed out SaveChanges that will show the error message if EndSaveChanges() fails, like the code sample below. Obviously you can't use the console to write out your message in silverlight, but you get the idea.
For instance, when I wrote the following sample, I found that I was getting a forbidden error, because my entity set had EntitySetRights.AllRead, not EntitySetRights.All
class Program
{
private static AdventureWorksEntities svc;
static void Main(string[] args)
{
svc =
new AdventureWorksEntities(
new Uri("http://localhost:5068/AWDataService.svc",
UriKind.Absolute));
var productQuery = from p in svc.Products
where p.ProductID == 740
select p;
var product = productQuery.First();
ShowProduct(product);
product.Color = product.Color == "Silver" ? "Gray" : "Silver";
svc.UpdateObject(product);
svc.BeginSaveChanges(SaveChangesOptions.Batch, OnSave, svc);
ShowProduct(product);
Console.ReadKey();
}
private static void ShowProduct(Product product)
{
Console.WriteLine("Id: {0} Name: {1} Color: {2}",
product.ProductID, product.Name, product.Color);
}
private static void OnSave(IAsyncResult ar)
{
svc = ar.AsyncState as AdventureWorksEntities;
try
{
WriteResponse(svc.EndSaveChanges(ar));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void WriteResponse(DataServiceResponse response)
{
if(response.IsBatchResponse)
{
Console.WriteLine("Batch Response Code: {0}", response.BatchStatusCode);
}
foreach (ChangeOperationResponse change in response)
{
Console.WriteLine("Change code: {0}", change.StatusCode);
if(change.Error != null)
{
Console.WriteLine("\tError: {0}", change.Error.Message);
}
}
}
}

Resources