Twitter4j: Exception in thread "Twitter4J Async Dispatcher[1]" java.lang.UnsupportedOperationException: Not supported yet - twitter4j

When i am trying to call the Twitter object in order to get the followers of a user, i got back the following exception: "Exception in thread "Twitter4J Async Dispatcher[1]" java.lang.UnsupportedOperationException: Not supported yet."
Do you have any idea, how to solve this issue?
Here is the related code part:
try {
Twitter twitter = new TwitterFactory().getInstance();
long lCursor = -1;
IDs friendsIDs = twitter.getFriendsIDs(user.getId(), lCursor);
do {
System.out.println("in do while iteration");
for (long i : friendsIDs.getIDs()) {
System.out.println("Follower ID #" + i);
System.out.println(twitter.showUser(i).getName());
}
} while (friendsIDs.hasNext());
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get friends' ids: " + te.getMessage());
System.exit(-1);
}
Thanks a lot

Related

handle Exceptions from API server in client server

I am trying to learn how to handle exception in APIs servers so I followed this where he has built API for birds, he finally reached to APIs like this:
#GetMapping(value = "/params")
public Bird getBirdRequestParam(#RequestParam("birdId") Long birdId) throws EntityNotFoundException {
Bird bird = birdRepository.findOne(birdId);
if(bird == null){
throw new EntityNotFoundException(Bird.class, "id", birdId.toString());
}
return bird;
}
and the ControllerAdvice has a method:
#ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<Object> handleEntityNotFound(
EntityNotFoundException ex) {
ApiError apiError = new ApiError(NOT_FOUND);
apiError.setMessage(ex.getMessage());
return buildResponseEntity(apiError);
}
the response will be a bird like this
{
"id": 1,
"scientificName": "Atlantic canary",
"specie": "serinus canaria",
"mass": 10,
"length": 11
}
or an exception details like this:
{
"apierror": {
"status": "NOT_FOUND",
"timestamp": "09-04-2018 10:11:44",
"message": "Bird was not found for parameters {id=2}"
}
but the problem is with my server that contacts with API
I am using :
public void gett(#RequestParam Long id) {
ResponseEntity<Bird> responseEntity = restTemplate.getForEntity("http://localhost:8181/params" + id, Bird.class);
bird = responseEntity.getBody();
model.addAttribute("birdform", bird);
return "bird";
}
the getForEntity is waiting for a response with bird body but an exception may be thrown in server and the response may be json of the error.
how to handle this problem in my client server?
in other words :
how to know in my client server that the api server has thrown an exception in json form.???
I have tried to get the response in "Object" variable and then try to know if it was excption or bird with "instance of" expression like this code
#GetMapping("/getbird")
public String getAll(#RequestParam Long id, Model model) {
ResponseEntity<Object> responseEntity = restTemplate.getForEntity("http://localhost:8181/api/bird/getone?id=" + id, Object.class);
if (responseEntity.getBody() instanceof Bird.class) {
Bird bird= (Bird) responseEntity.getBody();
model.addAttribute("Bird", bird);
return "bird-form";
}
else{
// something else
return "someview";
}
}
but first thing it didnot work (the instance of always return false)
the second thing is that this is a hard work to do with all my controllers' actions.
I hope that i could explain my problem clearly .
thanks....
You don't need to check the body of the response to see if you got an error. restTemplate.getForEntity() (and other methods) would throw an HttpClientErrorException if you get a 4XX response, or HttpServerErrorException if you get a 5XX response from the call.
To catch these exceptions, you can define a #ControllerAdvice with proper methods for exception handling:
#ControllerAdvice
class GlobalControllerExceptionHandler {
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 500
#ExceptionHandler(HttpClientErrorException.class)
public ApiError handle4xxFromClient(HttpClientErrorException ex) {
// construct and return a custom ApiError object
}
}
See https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc for details.
Two solutions :
Use a custom implementation error handler in your reste template.
restTemplate.setErrorHandler(customerErrorHandler)
Use the http status, rest template will throw an exception if it gets a bad http status from the server it is querying. Catch the exception and get the ApiError Object from the exception, and then throw and exception of your own that will be handled by your exception handler in your client server.
For these solutions to work, the server your are querying needs to send the right http status code when something wrong happens.

DotConnect PostgreSQL Update Command

string finalResult = "Failed";
using (PgSqlConnection myConnect = new PgSqlConnection(Resources.MyResources.DotConnectNewConnectionString))
{
try
{
myConnect.Open();
using (PgSqlCommand cmd = new PgSqlCommand("UPDATE salesforce.ent_inbound_correspondence_entity__c SET status__c = :status, status_change_date__c = CAST(:currentDate AS Date) WHERE deal_id__c = :projID AND correspondence_type__c= :cortype", myConnect))
{
cmd.Parameters.AddWithValue("status", status);
cmd.Parameters.AddWithValue("currentDate", DateTime.Now.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("projID", projectID);
cmd.Parameters.AddWithValue("cortype", "704(b) Model");
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
finalResult = "Success";
}
}
}
catch (PgSqlException ex)
{
throw ex;
}
finally
{
myConnect.Close();
}
}
return finalResult;
Hi All,
I am currently facing an issue when it comes to running an UPDATE query using DotConnect and PgSqlCommand. There are no exceptions occuring BUT whenever this is ran, cmd.ExecuteNonQuery() returns me 0. However, when I execute this query using 'absolute' values in PgAdmin, it has no issues at all.
Can anybody enlighten me on what is wrong with this piece of code? :(
Thank you!
EDIT: An exception message occurs with the following message: Message = "function get_xmlbinary() does not exist"
However, this function is not coded by me. I have no idea what this means.

Unable to get xmpp muc room information in android

I am using asmack library for my chat application.I am using below described code after successful login for getting Muc room information:
MultiUserChat mMultiUserChat = new MultiUserChat(connection,"VjNewMoiosandroid#conference.chat");
mMultiUserChat.join(USERNAME);
try {
if (mMultiUserChat.isJoined()==true) {
RoomInfo roomInfo=mMultiUserChat.getRoomInfo(connection,"VjNewMoiosandroid#conference.chat");}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I get this error while getting room information ,while i debug and check i am getting room information in log but nothing comes in roomInfo.
10-10 08:55:12.388: W/System.err(1821): java.lang.ClassCastException:
org.jivesoftware.smack.util.PacketParserUtils$2 cannot be cast to
org.jivesoftware.smackx.packet.DiscoverInfo 10-10 08:55:12.428:
W/System.err(1821): at
org.jivesoftware.smackx.ServiceDiscoveryManager.discoverInfo(ServiceDiscoveryManager.java:600)
10-10 08:55:12.458: W/System.err(1821): at
org.jivesoftware.smackx.ServiceDiscoveryManager.discoverInfo(ServiceDiscoveryManager.java:552)
10-10 08:55:12.478: W/System.err(1821): at
com.demo.xmppchat.CopyOfXMPPChatDemoActivity.getRoomInfo(CopyOfXMPPChatDemoActivity.java:469)
My chat room information i received in log
10-10 15:38:10.133: D/SMACK(26035): 03:38:10 PM RCV (1107887640): <iq
from='VjNewMoiosandroid#conference.chat' to='14393671556301070000#chat/Smack'
id='VWaeO-6' type='result'><query xmlns='http://jabber.org/protocol/disco#info'><identity
category='conference' type='text' name='VjNewMoiosandroid'/><feature var='
http://jabber.org/protocol/muc'/><feature var='muc_public'/><feature
var='muc_persistent'/><feature var='muc_open'/><feature var='muc_semianonymous'/><feature
var='muc_moderated'/><feature var='muc_unsecured'/><x xmlns='jabber:x:data'
type='result'><field type='hidden' var='FORM_TYPE'><value>
http://jabber.org/protocol/muc#roominfo</value></field><field label='Room description'
var='muc#roominfo_description'><value></value></field><field label='Number of occupants'
var='muc#roominfo_occupants'><value>1</value></field></x></query></iq>
I was using old asmack jar that is my issue ,I made some changes i used MultiUserChat class getRoomInfo() Method directly in my class
MultiUserChat mMultiUserChat = new MultiUserChat(connection,"VjNewMoiosandroid#conference.chat");
mMultiUserChat.join(USERNAME);
try {
if (mMultiUserChat.isJoined()==true) {
String roomInfo=getRoomInfo(connection, "VjNewMoiosandroid#conference.chat");}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I made one method as below
public static String getRoomInfo(Connection connection, String room)
throws XMPPException {
String roomInfo="";
try {
ServiceDiscoveryManager serviceDiscoveryManager=new ServiceDiscoveryManager(connection);
DiscoverInfo info = serviceDiscoveryManager.discoverInfo(room);
roomInfo=info.toXML();
} catch (XMPPException e) {
// TODO: handle exception
Log.e("xmpp", e.toString());
}
return roomInfo;
}
Do this way
Replace this line
RoomInfo roomInfo=mMultiUserChat.getRoomInfo(connection,"VjNewMoiosandroid#conference.chat");
With this
RoomInfo roomInfo=MultiUserChat.getRoomInfo(connection,"VjNewMoiosandroid#conference.chat");

UCMA 3.0 API Conferencing Error : Cannot join a different conference after receiving a conference invitation or conference escalation request

We have a UCMA 3.0 based application/bot that matches end users with experts. It migrates incoming one-one chat requests from end users into a multi user conference and then invites experts into the resulting multi user conference. The application itself continues to be a participant in the conference. At any given time, there may be several such conferences being brokered by our application but only one per end user. However, a single expert may be participating in more than one conference at the same time.
In our application logs we occasionally see the following exception.
Error in Conference Migration conf call # 63809878 ,Address :sip:xxxxxx#xxx.com;gruu;opaque=app:conf:focus:id:TQRREACE System.InvalidOperationException: Cannot join a different conference after receiving a conference invitation or conference escalation request.
at Microsoft.Rtc.Collaboration.ConferenceSession.VerifyAndGetConferenceAddress(String conferenceUri, String parameterName)
at Microsoft.Rtc.Collaboration.ConferenceSession.BeginJoinCommon(String conferenceUri, ConferenceJoinOptions options, AsyncCallback userCallback, Object state)
at Microsoft.Rtc.Collaboration.ConferenceSession.BeginJoin(String conferenceUri, ConferenceJoinOptions options, AsyncCallback userCallback, Object state)
at a(String A_0, String A_1, String A_2, Boolean A_3, Boolean A_4)
Below is the code snippet used to make conference. Previously this site was an OCS 2007 R2 Installation and was migrated to Lync 2010 Server.
Site is running in mixed mode. It occurs only on production server and we are not able to generate this exception on dev server, we
have tested it after generating more than 15 conferences simultaniously but no luck.
private void CreateAdHohConf(string user1Uri, string user2uri, string subject)
{
Exception exception = null;
// Create conference scheduling details for the conference.
ConferenceScheduleInformation scheduleInfo = new ConferenceScheduleInformation();
// Restrict the conference to invited users only.
scheduleInfo.AccessLevel = ConferenceAccessLevel.Everyone;
// Set a subject for the conference.
scheduleInfo.Subject = subject;
scheduleInfo.Description = subject;
scheduleInfo.ConferenceId = ConferenceServices.GenerateConferenceId();
scheduleInfo.ExpiryTime = System.DateTime.Now.AddHours(8);
scheduleInfo.IsPasscodeOptional = true;
scheduleInfo.PhoneAccessEnabled = false;
// Don't automatically assign a leader.
scheduleInfo.AutomaticLeaderAssignment = AutomaticLeaderAssignment.Everyone;
// Add the caller and recipient as participants.
scheduleInfo.Participants.Add(new ConferenceParticipantInformation("sip:" + user1Uri, ConferencingRole.Leader));
scheduleInfo.Participants.Add(new ConferenceParticipantInformation("sip:" + user2uri, ConferencingRole.Leader));
scheduleInfo.Mcus.Add(new ConferenceMcuInformation(McuType.ApplicationSharing));
scheduleInfo.Mcus.Add(new ConferenceMcuInformation(McuType.InstantMessaging));
scheduleInfo.Mcus.Add(new ConferenceMcuInformation(McuType.AudioVideo));
scheduleInfo.Mcus.Add(new ConferenceMcuInformation(McuType.Meeting));
//Scheduling conference
ConferenceServices objLocalConfSvc = lyncAgent.LocalEndpoint.ConferenceServices;
Conference confSession = null;
objLocalConfSvc.BeginScheduleConference(scheduleInfo,
result =>
{
try
{
confSession = objLocalConfSvc.EndScheduleConference(result);
}
catch (RealTimeException rtex)
{
exception = rtex;
}
catch (Exception ex)
{
exception = ex;
}
finally
{
_waitForConferenceScheduling.Set();
}
}, objLocalConfSvc);
_waitForConferenceScheduling.WaitOne();
//Begin Join conference
ConferenceSession objLocalConfSession=this.call.Conversation.ConferenceSession;
try
{
ConferenceJoinOptions joinOptions = new ConferenceJoinOptions() { CanManageLobby = false, JoinMode = JoinMode.Default };
objLocalConfSession.BeginJoin(new RealTimeAddress(confSession.ConferenceUri).Uri, joinOptions,
result => {
try
{
objLocalConfSession.EndJoin(result);
}
catch (Exception ex)
{
exception = ex;
}
finally
{
//Again, for sync. reasons.
_waitForConferenceJoin.Set();
}
}
, this.call.Conversation.ConferenceSession);
// Wait until join completes.new RealTimeAddress(this._conference.ConferenceUri).Uri,
_waitForConferenceJoin.WaitOne();
}
catch (InvalidOperationException ioex)
{
exception = ioex;
}
catch (Exception ex)
{
exception = ex;
}
//Begin Escalation
Conversation objLocalConv= this.call.Conversation;
try
{
objLocalConv.BeginEscalateToConference(
result =>
{
try
{
objLocalConv.EndEscalateToConference(result);
}
catch (Exception ex)
{
exception = ex;
}
finally
{
//Sync It
_waitForEscalation.Set();
}
}
, objLocalConv);
// Wait until escalation completes.
_waitForEscalation.WaitOne();
}
catch (InvalidOperationException ioex)
{
exception = ioex;
}
catch (Exception ex)
{
exception = ex;
}
finally
{
if (exception != null)
{
lyncAgent.Logger.Error( "Error in Conference Migration conf call # " + GetHashCode() + " , Address :" + confSession.ConferenceUri , exception);
}
}
}
Please suggest what could be the possible problem on priority basis.
Thanks in advance.
Does this method reside in an object where it is possible that it will be called by multiple sources at the same time?
If so, using what appears to be a class level variable like _waitForConferenceScheduling could be problematic. Thread A could end up accidentally letting Thread B proceed before Thread B's async action is actually completed. So Thread B could call .BeginEscalate before .EndJoin was called.
When I write UCMA code, I generally use nested callbacks to prevent this type of thing from happening.
Other than that, I'd recommend you run OCSLogger on your application server and the Lync Front End server to gather SIPStack, S3 and Collaboration logs. Looking at the actual SIP messages in detail will provide some clues.
You'd be looking for an INVITE to the conference and the response back to that INVITE.
We managed to detect the reason. It happens if any one in the participant list have already added any contact for meeting in conversation with our endpoint.

Monotouch data sync - why does my code sometimes cause sqlite errors?

I have the following calls (actually a few more than this - it's the overall method that's in question here):
ThreadPool.QueueUserWorkItem(Database.Instance.RefreshEventData);
ThreadPool.QueueUserWorkItem(Database.Instance.RefreshLocationData);
ThreadPool.QueueUserWorkItem(Database.Instance.RefreshActData);
1st point is - is it OK to call methods that call WCF services like this? I tried daisy chaining them and it was a mess.
An example of one of the refresh methods being called above is (they all follow the same pattern, just call different services and populate different tables):
public void RefreshEventData (object state)
{
Console.WriteLine ("in RefreshEventData");
var eservices = new AppServicesClient (new BasicHttpBinding (), new EndpointAddress (this.ServciceUrl));
//default the delta to an old date so that if this is first run we get everything
var eventsLastUpdated = DateTime.Now.AddDays (-100);
try {
eventsLastUpdated = (from s in GuideStar.Data.Database.Main.Table<GuideStar.Data.Event> ()
orderby s.DateUpdated descending
select s).ToList ().FirstOrDefault ().DateUpdated;
} catch (Exception ex1) {
Console.WriteLine (ex1.Message);
}
try {
eservices.GetAuthorisedEventsWithExtendedDataAsync (this.User.Id, this.User.Password, eventsLastUpdated);
} catch (Exception ex) {
Console.WriteLine ("error updating events: " + ex.Message);
}
eservices.GetAuthorisedEventsWithExtendedDataCompleted += delegate(object sender, GetAuthorisedEventsWithExtendedDataCompletedEventArgs e) {
try {
List<Event> newEvents = e.Result.ToList ();
GuideStar.Data.Database.Main.EventsAdded = e.Result.Count ();
lock (GuideStar.Data.Database.Main) {
GuideStar.Data.Database.Main.Execute ("BEGIN");
foreach (var s in newEvents) {
GuideStar.Data.Database.Main.InsertOrUpdateEvent (new GuideStar.Data.Event {
Name = s.Name,
DateAdded = s.DateAdded,
DateUpdated = s.DateUpdated,
Deleted = s.Deleted,
StartDate = s.StartDate,
Id = s.Id,
Lat = s.Lat,
Long = s.Long
});
}
GuideStar.Data.Database.Main.Execute ("COMMIT");
LocationsCount = 0;
}
} catch (Exception ex) {
Console.WriteLine("error InsertOrUpdateEvent " + ex.Message);
} finally {
OnDatabaseUpdateStepCompleted (EventArgs.Empty);
}
};
}
OnDatabaseUpdateStepCompleted - just iterates an updateComplete counter when it's called and when it knows that all of the services have come back ok it removes the waiting spinner and the app carries on.
This works OK 1st time 'round - but then sometimes it doesn't with one of these: http://monobin.com/__m6c83107d
I think the 1st question is - is all this OK? I'm not used to using threading and locks so I am wandering into new ground for me. Is using QueueUserWorkItem like this ok? Should I even be using lock before doing the bulk insert/update? An example of which:
public void InsertOrUpdateEvent(Event festival){
try {
if (!festival.Deleted) {
Main.Insert(festival, "OR REPLACE");
}else{
Main.Delete<Event>(festival);
}
} catch (Exception ex) {
Console.WriteLine("InsertOrUpdateEvent failed: " + ex.Message);
}
}
Then the next question is - what am I doing wrong that is causing these sqlite issues?
w://
Sqlite is not thread safe.
If you want to access Sqlite from more than one thread, you must take a lock before you access any SQLite related structures.
Like this:
lock (db){
// Do your query or insert here
}
Sorry, no specific answers, but some thoughts:
Is SqlLite even threadsafe? I'm not sure - it may be that it's not (to the wrapper isn't). Can you lock on a more global object, so no two threads are inserting at the same time?
It's possible that the MT GC is getting a little overenthusiastic, and releasing your string before it's been used. Maybe keep a local reference to it around during the insert? I've had this happen with view controllers, where I had them in an array (tabcontrollers, specificially), but if I didn't keep an member variable around with the reference, they got GC'ed.
Could you get the data in a threaded manner, then queue everything up and insert them in a single thread? Atleast as a test anyway.