Twitter4j automatically reconnection policy - twitter4j

I'm testing twitter4j to retrieve status filtered stream.
All works fine but I'm not able to find any information about the policy
twitter4j uses to reconnect in case of disconnection.
I can manage this event in this way:
public void onException(Exception ex) {
if (ex instanceof TwitterException){
TwitterException tw_ex = (TwitterException) ex;
//TODO: manage all disconnect causes
}else{
ex.printStackTrace();
}
}
...but does twitter4J automatically try to reconnect to the server?
If yes, what about the policy twitter4j use to retry the connection?
Thank you very much!

Related

When using shiro to realize stateless application, do i need to login every request?

I use shiro and jwt and try to realize a stateless web application.
When i extend AuthorizingRealm, do i need to executeLogin every request?
Here is my executeLogin method:
public static boolean executeLogin(ServletRequest request) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authorization = httpServletRequest.getHeader("Authorization");
if (authorization == null || "".equals(authorization.trim())) {
throw RequestException.fail("未含授权标示,禁止访问");
}
JwtToken token = new JwtToken(authorization, null, null);
// 提交给realm进行登入,如果错误他会抛出异常并被捕获
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (DisabledAccountException e) {
if (e.getMessage().equals("verifyFail")) {
throw new RequestException(ResponseCode.NOT_SING_IN.code, "身份已过期,请重新登录", e);
}
throw new RequestException(ResponseCode.SIGN_IN_INPUT_FAIL.code, e.getMessage(), e);
} catch (Exception e) {
e.printStackTrace();
throw new RequestException(ResponseCode.SIGN_IN_FAIL, e);
}
// 如果没有抛出异常则代表登入成功,返回true
return true;
}
By Stateless means that each request does not depend from the previous, however this does not mean that Shiro does not use sessions.
When the user does a successful login Shiro attaches to the HTTPResponse some cookies. When the client sends the cookies to each further request, Shiro automatically extracts the Subject (associates the cookies with the user) so, in your code, you can immediately call SecurityUtils.getSubject().
A realm is the wrong approch here as it usually have by definition a 1-to-1 correlation with a data source. What you actually want to do is to controll access to your servers resources, verifying a JWT from a client. This can be done by a AccessControlFilter, reading the authorization header and verifing its claims in the filters isAccessAllowed method. The methods return value defines wheather access is allowed or not.
You don't need to login a subject at all since the AccessControlFilter decides wheather access is granted or denied, either forwarding the user to the requested resource or redirecting a 401 - Unauthorized response.
Yes, you should log in for each request. This will attach the subject to the current thread and allow you to use features: like use annotations for authz.
As you are using stateless call, you have to login each time and generate new subject and also load authorization details with appropriate realm.
The another option you could try is, put subject in cache (ehCache) once successful login and then on every request you can get subject from Cache and use for authorization. This will avoid login and authorization object population on every request. But you have to make sure to remove object from cache on logout event.
Similar thing has been already done by one user at:
https://github.com/jikechenhao/springmvc-shiro-react-redux-restful-example

AndroidAsync TCP -- proper way to detect socket is no longer available using write?

I am wondering what is the proper way to check on the client side that a TCP socket opened using the AndroidAsync library is no longer available? This is in the case the (plain TCP, non-AndroidAsync) server did not initiate explicitly closing the socket (so the ClosedCallback is not invoked). For instance, when the server has been cold rebooted.
It seems that the DataCallback is available only when the server sends back data and can't be used to receive error messages.
It seems to me also that
Util.writeAll(socket, (byte[]) payload.array(), new CompletedCallback()
{
#Override
public void onCompleted(Exception ex)
{
if (ex != null)
{
Log.e(TAG, "write failed with ex message= " + ex.getMessage());
throw new RuntimeException(ex);
}
}
});
does not throw an Exception either.
So at this point I'm not sure how to detect the socket is no longer available even if the client periodically writes data to it.
It will throw an IOexception if you send enough data or call it enough times. It won't throw on the first call due to TCP buffering at both ends.
I ended up implementing some sort of a "ping"-alike periodic check. The client opens and immediately closes a TCP connection to the very same port using a plain Java NIO socket call (not using AndroidAsync). If that one times out, it is assumed that the connection has been lost, and a recovery attempt is made once it succeeds again. This periodic check is performed only when the app has focus, or is just awakened. This is clearly a far from ideal workaround but it seems to work for my purposes.
You could use the closed/end callbacks
socket.setClosedCallback(new CompletedCallback()
{
#Override
public void onCompleted(Exception ex)
{
}
});
socket.setEndCallback(new CompletedCallback()
{
#Override
public void onCompleted(Exception ex)
{
}
});

How can I determine why onFailure is triggered in GWT-RPC?

I have a project that does 2 RPC calls and then saves the data that the user provided in tha datastore. The first RPC call works ok, but from the second I always recieve the onFailure() message. How can I determine why the onFailure() is triggered? I tried caught.getCause() but it doesn't return anything.
feedbackService.saveFeedback(email,studentName,usedTemplates,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
caught.getCause();
Window.alert("Failure!");
}
public void onSuccess(String result) {
Window.alert("Saved!");
}
});
Throwable instance is instance of an Exception. You can check if it is a custom Exception like this:
if (caught instanceOf CustomException){
or if you want to show the message of exception you can use the getMessage():
Window.alert("Failure: " + caught.getMessage());
GWT-rpc is not not easy to ebug if an error occurs.
The easiest part is th check if the Exception is part of StatusCodeException.
A Statuscode of 404 means, you are pointing to a wrong endpoint
0 means, that
The searver is unreachable
You don't have permissions to check, if the server is available (X-domain-request)
You can use the Chrome-Web-Inspector to bedug GWT-RPC
You should be able to see all calls from the browser to you backend.
The most common failures are because of serialization of object. You have to ensure, that all dtransferred object implement java.io.Serializable
Most of the time it will just be a server side exception being raised which fires the onFailure() method.
Try putting breakpoints on your server side. That should help you pinpoint what's going wrong.

Smack service discovery without login gives bad-request(400)

I am trying to discover items that a pubsub service provides. When I log into the target server, I can get the response successfully. But when I connect bu do not login, it gives a bad request error.
This is the code:
ConnectionConfiguration config = new ConnectionConfiguration(serverAddress, 5222);
config.setServiceName(serviceName);
connection = new XMPPConnection(config);
connection.connect();
connection.login(userName, password); //!!!when I remove this line, bad request error is received
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
DiscoverItems items;
try {
items = discoManager.discoverItems("pubsubservice." + serverName);
} catch (XMPPException e) {
e.printStackTrace();
}
Is there a way to discover items when the user is not logged in, but the connection is established?
No, you must authenticate to send stanzas to any JID in XMPP (otherwise they would not be able to reply to you, since they wouldn't know your address).
Perhaps one option for you is anonymous authentication. Most servers support it, and it creates a temporary account on the server for you, with a temporary JID. You don't need a password, and login time is quick.
#MattJ is correct and you could try using anon login. That will get you part way there.
Your current request will only get you the nodes though, after which you will have to get the items for each node. It would be simpler to use PubsubManager to get the information you want since it provides convenience methods for accessing/using all things pubsub.
Try the documentation here, the getAffiliations() method is what you are looking for.
BTW, I believe the typical default service name for pubsub is pubsub not pubsubservice. At least this is the case for Openfire.

Commit transaction then send email

In Java, let's say I have a transaction that once it is committed, I want to do another action, in this case, send an email.
Therefore,
try {
transaction.begin()
...
transaction.commit()
// point 1
Utility.sendEmail(...)
} catch (Exception e) {
transaction.rollback();
}
Is it possible for the thread to die/get killed at point 1 and not send an email ?
Any way to minimize this ? JTA + JMS perhaps, where the action of sending a message is part of a transaction ?
I'm investigating an issue and exploring whether this is possible. JVM is still alive (no OOM). I do not know the inner working of the app server so not sure if this is possible.
I can't say for sure if the rollback() in the catch clause has any effect if the commit() was OK and sendEmail() threw an exception. The quickest way to test this is to throw an exception from the sendEmail() method and see if the transaction was actually committed.
The way I would put it though, is to move the sendEmail() call away from your try block:
try {
transaction.begin()
...
transaction.commit()
} catch (Exception e) {
transaction.rollback();
}
try {
// point 1
Utility.sendEmail(...)
} catch (Exception e) {
// handle it
}
This way you can control what will happen if a rollback was made.
Also, I think that sending the email to a JMS queue is in most cases a good idea. Doing it like that will give your DB code permission to continue and supposedly give feedback to your user that everything went OK and the email will be sent whenever it fits the email controller's schedule. For example, there might be a connection issue with your email server and the email sending would hang for say 30 seconds before throwing an exception and your user would see this as a very long button click.