How to find roles of a user in cloudboost - cloudboost

I am trying to get all the roles assigned to user when user logs in, using the code below.
public class roles extends AsyncTask <String,Void,Void>{
#Override
protected Void doInBackground(String... params) {
final CloudUser user = new CloudUser();
final CloudRole role = new CloudRole("MCA");
user.setUserName(params[0]);
user.setPassword(params[1]);
try {
user.logIn(new CloudUserCallback() {
#Override
public void done(CloudUser cloudUser, CloudException e) throws CloudException {
if (cloudUser != null) {
System.out.println("login Successful");
System.out.println(cloudUser.getUserName());
cloudUser.isInRole(role);
}
if (e != null) {
System.out.println("In logn exception");
e.printStackTrace();
}
}
});
} catch (CloudException e) {
e.printStackTrace();
}
return null;
}
}
I am getting the following error:
FATAL EXCEPTION: AsyncTask #1
Process: com.rakesh_kr.image, PID: 31256
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassCastException: io.cloudboost.json.JSONArray cannot be cast to java.util.ArrayList
at io.cloudboost.CloudUser.isInRole(CloudUser.java:335)
at com.rakesh_kr.image.MainActivity$roles$1.done(MainActivity.java:174)
at io.cloudboost.CloudUser.logIn(CloudUser.java:219)
at com.rakesh_kr.image.MainActivity$roles.doInBackground(MainActivity.java:168)
at com.rakesh_kr.image.MainActivity$roles.doInBackground(MainActivity.java:155)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)

This is a bug that occured in versions of CloudBoost JavaSDK prior to v1.0.7, this has been fixed, please clone the latest sources from github or get the latest jar(1.0.7) which should be available on maven in a few hours from now.

Related

Reactive Java OneError Resume error handling

Trying to save event has this flow ( the repo is reactive, this is just an example code for testing. I am new reactive, I am using io.projectreactor (3.3))
Validate an event, on failure, write to history
if validate is successful, write event to repo, any failures write to history
if validate fails write to history
inducing some failures to simulate the error condition
import reactor.core.publisher.Mono;
public class MyTest {
static int counter = 0;
public static void main(String args[]) throws InterruptedException
{
String array[] = {"1","2","3","4",null,"5"};
for(int i =0; i < 5; i++)
{
System.out.println("input:: "+array[i]);
new MyTest().createMessage(array[i]);
counter++;
Thread.sleep(500);
}
}
private void createMessage(String input)
{
new MyTest().onMessage(input)
.doOnSuccess(s -> System.out.println("----done::success-----"))
.onErrorResume(e ->
{System.out.println("---done::error --creatMessage::doOnError:: caused by "+e);
return Mono.empty();})
.subscribe();
}
private Mono<String> onMessage(String input)
{
return Mono.create(sink -> {
validate()
.onErrorResume(e -> {
System.out.println("error onMessage:: fail to validate");
sink.error(e);
return Mono.error(e);
})
.flatMap(a -> processObject(input))
.flatMap(h -> {
System.out.println("success onMessage :: save history");
new Service().saveHistory(input, false);
sink.success();
return Mono.just(h);
})
.subscribe();
});
}
private Mono<String> processObject(String input)
{
return Mono.create(sink -> {
new Service().saveEvent(input).flatMap(a -> {
System.out.println("success processObject");
sink.success(a);
return Mono.just(a);
}).onErrorResume(e -> {
new Service().saveHistory(input, true);
System.out.println("error processObject");
sink.error(e);
return Mono.error(e);
}).subscribe();
});
}
private Mono<String> validate()
{
counter++;
return Mono.create(sink -> {
if (counter % 3 == 0)
{
sink.error(new RuntimeException("Validate method error"));
return;
}
sink.success("validate is done ");
return;
});
}
}
Service Class
public class Service {
public Mono<String> saveEvent(String id)
{
return save(id)
.onErrorResume(e -> {
System.out.println("Error in save event");
return Mono.error(e);
}).doOnNext(e -> System.out.println("save event"));
}
public Mono<String> saveHistory(String id, boolean error)
{
return save(id)
.onErrorResume(e -> {
System.out.println("Error in save history");
return Mono.error(e);
}).doOnNext(e -> System.out.println("save history"));
}
public Mono<String> save(String id)
{
if (id == null)
{
throw new RuntimeException("Error saving");
}
return Mono.just("save success");
}
}
I am getting this exception
---done::error --creatMessage::doOnError:: caused by java.lang.RuntimeException: Validate method error
Exception in thread "main" reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.RuntimeException: Validate method error
Caused by: java.lang.RuntimeException: Validate method error
at sample.MyTest.lambda$validate$9(MyTest.java:77)
at reactor.core.publisher.MonoCreate.subscribe(MonoCreate.java:57)
at reactor.core.publisher.Mono.subscribe(Mono.java:4110)
at reactor.core.publisher.Mono.subscribeWith(Mono.java:4216)
at reactor.core.publisher.Mono.subscribe(Mono.java:3942)
at sample.MyTest.lambda$onMessage$5(MyTest.java:49)
at reactor.core.publisher.MonoCreate.subscribe(MonoCreate.java:57)
at reactor.core.publisher.Mono.subscribe(Mono.java:4110)
at reactor.core.publisher.Mono.subscribeWith(Mono.java:4216)
at reactor.core.publisher.Mono.subscribe(Mono.java:3942)
at sample.MyTest.createMessage(MyTest.java:30)
at sample.MyTest.main(MyTest.java:18)
Updated working code : based on #Michael Berry comments
public static void main(String args[]) throws InterruptedException
{
String array[] = {"1","2","3","4",null,"5"};
for(int i =0; i < 5; i++)
{
System.out.println("input:: "+array[i]);
new MyTest().createMessage(array[i]);
counter++;
Thread.sleep(500);
}
}
private void createMessage(String input)
{
new MyTest().onMessage(input)
.doOnSuccess(s -> System.out.println("----done::success-----"))
.onErrorResume(e ->
{
System.out.println("---done::error --creatMessage::doOnError:: caused by "+e);
return Mono.empty();
})
.subscribe();
}
private Mono<String> onMessage(String input) {
return validate()
.onErrorResume(e -> {
System.out.println("error onMessage:: fail to validate");
return Mono.error(e);
})
.flatMap(a -> processObject(input))
.flatMap(h -> {
System.out.println("success onMessage :: save history");
new Service().saveHistory(input, false);
return Mono.just(h);
});
}
private Mono<String> processObject(String input)
{
return new Service().saveEvent(input).flatMap(a -> {
System.out.println("success processObject");
return Mono.just(a);
}).onErrorResume(e -> {
new Service().saveHistory(input, true);
System.out.println("error processObject");
return Mono.error(e);
});
}
private Mono<String> validate()
{
counter++;
if (counter % 3 == 0)
{
return Mono.error(new RuntimeException("Validate method error"));
}
return Mono.just("validate is done ");
}
Result
save event
success processObject
success onMessage :: save history
----done::success-----
input:: 2
error onMessage:: fail to validate
---done::error --creatMessage::doOnError:: caused by java.lang.RuntimeException: Validate method error
input:: 3
save event
success processObject
success onMessage :: save history
----done::success-----
input:: 4
save event
success processObject
success onMessage :: save history
----done::success-----
input:: null
error onMessage:: fail to validate
---done::error --creatMessage::doOnError:: caused by java.lang.RuntimeException: Validate method error
You're getting an error here because of your onMessage() implementation, which is a bit bizarre:
You're wrapping a Mono in Mono.create(), which there's no reason to do;
You're subscribing on this inner publisher yourself - that's almost always the wrong thing to do, and won't necessarily do what you expect (subscribing to publishers should be handled by the framework, not your code.) In this case, the key thing is it means that it's treated separately, not part of your reactive chain, so your error handling probably isn't mapping to the inner publisher as you expect;
Your onErrorResume() call on this inner publisher itself returns an error, and there's no other error handling on this inner publisher - hence why that error is unhandled, so it then prints out the stack trace that you're seeing.
Instead, you most likely want your onMessage() method to read thus:
private Mono<String> onMessage(String input) {
return validate()
.onErrorResume(e -> {
System.out.println("error onMessage:: fail to validate");
return Mono.error(e);
})
.flatMap(a -> processObject(input))
.flatMap(h -> {
System.out.println("success onMessage :: save history");
new Service().saveHistory(input, false);
return Mono.just(h);
});
}
...without the Mono.create() (which is only really meant to be used by non-reactor callback APIs for compatibility purposes.) Your output with this change then reads as follows:
input:: 1
save event
success processObject
success onMessage :: save history
----done::success-----
input:: 2
error onMessage:: fail to validate
---done::error --creatMessage::doOnError:: caused by java.lang.RuntimeException: Validate method error
input:: 3
save event
success processObject
success onMessage :: save history
----done::success-----
input:: 4
save event
success processObject
success onMessage :: save history
----done::success-----
input:: null
error onMessage:: fail to validate
---done::error --creatMessage::doOnError:: caused by java.lang.RuntimeException: Validate method error

How do I connect to a UNIX domain socket running an HTTP server using Netty?

I am trying to connect to a Docker UNIX domain socket using Netty. Here's my attempt so far.
#PostConstruct
public void init() throws Exception {
io.netty.bootstrap.Bootstrap bootstrap = new io.netty.bootstrap.Bootstrap();
bootstrap
.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.remoteAddress(new DomainSocketAddress("/var/run/docker.sock"))
.handler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel
.pipeline()
.addLast(new SimpleChannelInboundHandler<HttpObject>() {
#Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
System.out.println(httpObject);
}
});
}
});
final Channel channel = bootstrap.connect().sync().channel();
final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/services", Unpooled.EMPTY_BUFFER);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
channel.writeAndFlush(request);
channel.closeFuture().sync();
System.out.println("DONE");
}
At the moment I am getting
Caused by: java.nio.channels.UnsupportedAddressTypeException: null
Is there an example on how to do HTTP connections to UDS using Netty? So far I only found raw UDS and TCP HTTP but not combined.
Here's a working implementation.
io.netty.bootstrap.Bootstrap bootstrap = new io.netty.bootstrap.Bootstrap();
final EpollEventLoopGroup epollEventLoopGroup = new EpollEventLoopGroup();
try {
bootstrap
.group(epollEventLoopGroup)
.channel(EpollDomainSocketChannel.class)
.handler(new ChannelInitializer<UnixChannel>() {
#Override
public void initChannel(UnixChannel ch) throws Exception {
ch
.pipeline()
.addLast(new HttpClientCodec())
.addLast(new HttpContentDecompressor())
.addLast(new SimpleChannelInboundHandler<HttpObject>() {
private StringBuilder messageBuilder = new StringBuilder();
#Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
messageBuilder.append(content.content().toString(StandardCharsets.UTF_8));
if (msg instanceof LastHttpContent) {
System.out.println(messageBuilder);
}
} else {
System.out.println(msg.getClass());
}
}
});
}
});
final Channel channel = bootstrap.connect(new DomainSocketAddress("/var/run/docker.sock")).sync().channel();
final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/services", Unpooled.EMPTY_BUFFER);
request.headers().set(HttpHeaderNames.HOST, "daemon");
channel.writeAndFlush(request);
channel.closeFuture().sync();
} finally {
epollEventLoopGroup.shutdownGracefully();
}
Few things to note:
Use the EpollEventLoopGroup and EpollDomainSocketChannel with a ChannelInitializer<UnixChannel>.
HTTP requires new HttpCodec() in the pipeline to use the Netty HTTP objects.
The data may be chunked so you need to assemble it and wait for the LastHttpContent object
https://github.com/trajano/netty-docker-daemon-socket

Exception in step at specflow

I'm calling in a function to step (specflow),
Then(step's string)
and in step I throw an exception. I want to catch the exception with a different function and not in the step itself. Do someone know how to do it?
Thanks
This is not possible with SpecFlow.
SpecFlow interprets an exception in an step as error and stops the execution of the Scenario.
What you can do, is to catch the exception in your step and save it in a field of the binding class. Then in the second step you can check this field.
like this:
[Binding]
public class BindingClass
{
private Exception _exception;
[When("an exception is thrown")
public void ExceptionThrown()
{
try {
.... //your code that throws an exception
}
catch(Exception e)
{
_exception = e;
}
}
[Then("the exception has the message '(.*)'")]
public void ExceptionHasTheMessage(string message)
{
if (_exception != null)
{
Assert.Equal(_exception.Message, message);
}
}
}
I use the AfterStep hook available in SpecFlow.
The code looks like this:
[AfterStep]
public void AfterStep()
{
if(_scenarioContext.ScenarioExecutionStatus.ToString().Equals("TestError"))
{
Logger.LogScreenshot(exception, _scenarioContext.ScenarioInfo.Title);
}
}
This piece of code will catch your exception and remaining steps will be skipped.

Stopping Fitnesse (Slim) on any exception

We've found the "Fail Fast" principle crucial for improving maintainability of our large Fitnesse-based battery of tests. Slim's StopTestException is our saviour.
However, it's very cumbersome and counterproductive to catch and convert any possible exception to those custom StopExceptions. And this approach doesn't work outside of fixtures. Is there a way to tell fitnesse (preferably using Slim test system) to stop test on any error / exception?
Update: corresponding feature request https://github.com/unclebob/fitnesse/issues/935
Most of the exceptions coming from fixtures are possible to conveniently convert to the StopTestException by implementing the FixtureInteraction interface, e.g.:
public class StopOnException extends DefaultInteraction {
#Override
public Object newInstance(Constructor<?> constructor, Object... initargs) throws InvocationTargetException, InstantiationException, IllegalAccessException {
try {
return super.newInstance(constructor, initargs);
} catch (Throwable e) {
throw new StopTestException("Instantiation failed", e);
}
}
#Override
public Object methodInvoke(Method method, Object instance, Object... convertedArgs) throws InvocationTargetException, IllegalAccessException {
try {
return super.methodInvoke(method, instance, convertedArgs);
} catch (Throwable e) {
throw new StopTestException(e.getMessage(), e);
}
}
public static class StopTestException extends RuntimeException {
public StopTestException(String s, Throwable e) {
super(s, e);
}
}
}

spring websocket : SubProtocolWebSocketHandler

I have stability problems with Spring web-sockets. Sometimes I have a similar exception to that describe in https://jira.spring.io/browse/SPR-12812.
The patch is not available, then I have implemented my own code with a custom SubProtocolWebSocketHandler.
public class WBSSubProtocolWebSocketHandler extends SubProtocolWebSocketHandler {
private static final Logger LOG = LoggerFactory.getLogger(WBSSubProtocolWebSocketHandler.class);
public WBSSubProtocolWebSocketHandler(MessageChannel clientInboundChannel, SubscribableChannel clientOutboundChannel) {
super(clientInboundChannel, clientOutboundChannel);
}
#Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
LOG.debug("WebSocket Connection closed for client with session ID {}", session.getId());
}
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// WebSocketHandlerDecorator could close the session
// https://jira.spring.io/browse/SPR-12812
if (!session.isOpen()) {
LOG.warn("WebSocket Connection established for client with session ID {} was closed.", session.getId());
return;
}
super.afterConnectionEstablished(session);
LOG.debug("WebSocket Connection established for client with session ID {}", session.getId());
}
#Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
super.handleTransportError(session, exception);
LOG.warn("WebSocket transport error for client with session ID {}", session.getId());
}
#Override
public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {
super.handleMessage(session, message);
LOG.debug("Websocket incoming message ({}) from client with session ID {}", message.getPayload().toString(), session.getId());
}
#Override
public void handleMessage(Message message) throws MessagingException {
super.handleMessage(message);
LOG.debug("Websocket incoming message : {}, header {}", message);
}
}
Now my problem is to reproduce the exception to see if the problem is solved. I tried various ways, but without success. I can not reproduce the closing of the connection. Does anyone have an idea?
We also have a second problem. The client application (angularjs application) sometimes reports that the socket-web connection is lost. But I do not understand why because on the server I have no error / warning in the logs.
How can I identify the problem and reproduce it?

Resources