I am trying to parse HL7 Message version 2.8 using HAPI. Before that am able to get value from each segment like MSH, EVN, PID, PV1. But now am getting value only from MSH seg other segments(EVN,PId,PV1) comes NULL. Please have look my code & give me solutions for that.
public class ADTService {
AWSCredentials awsCredentials = null;
AmazonDynamoDBClient amazonDynamoDBClient = null;
public Reply sendADTMessage() throws HL7Exception {
Reply reply = new Reply();
PatientInfo patientInfo = new PatientInfo();
byte[] valueDecoded= Base64.decode("TVNIfF5+XFwmfFNtYXJ0fDgwMDB8fEZ8MjAxMzA3MzExMzIyNTl8fEFEVF5BMDF8NDM0MzQzfFB8Mi44fHx8QUx8TkUKRVZOfFAwM3wyMDEzMDczMTEzMjI1OXx8T3x8MjAxMzA3MzExMzIyNTkKUElEfDF8UjQzNTQzNXxSNDM1NDM1fHxCQVRJU1RFXkFOVE9JTkVefHwxOTI1MDIyODAwMDAwMHxNfHx8fHx8fHx8fHw0MzgyNjEzMDcKUFYxfDF8SXxVLTAxXjQwN15BfHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHwyMDEwMTAwNTAwMDAwMA==");
String decodedADT = new String(valueDecoded);
System.out.println("Decoded value is " + decodedADT);
HapiContext context = new DefaultHapiContext();
context.setValidationContext(new NoValidation());
try {
Parser p = context.getGenericParser();
Message hapiMsg = p.parse(decodedADT);
System.out.println("Decoded value 1 is " + hapiMsg);
ADT_A01 adtMsg = (ADT_A01)hapiMsg;
MSH msh = adtMsg.getMSH();
PID pid = adtMsg.getPID();
EVN event = adtMsg.getEVN();
PV1 pv1 = adtMsg.getPV1();
System.out.println("MSH sending application "+msh.getSendingApplication().getNamespaceID().getValue());
System.out.println("MSH sending facility "+msh.getSendingFacility().getNamespaceID().getValue());
System.out.println("MSH receiving application "+msh.getReceivingApplication().getNamespaceID().getValue());
System.out.println("MSH receiving facility "+msh.getReceivingFacility().getNamespaceID().getValue());
System.out.println("MSH datetime of message "+msh.getDateTimeOfMessage().getValue());
System.out.println("MSH message control id "+msh.getMessageControlID().getValue());
System.out.println("MSH ADT Event "+msh.getMessageType().getMessageCode().getValue()+"-"+msh.getMessageType().getTriggerEvent().getValue());
System.out.println();
System.out.println("EVN recorded datetime "+event.getRecordedDateTime().getValue());
System.out.println();
System.out.println("PID patient id "+pid.getPatientIdentifierList(0).getIDNumber().getValue());
System.out.println("PID patient id "+pid.getPatientID().getValue());
System.out.println("PID last name "+pid.getPatientName(0).getFamilyName().getFn1_Surname().getValue());
System.out.println("PID first name "+pid.getPatientName(0).getGivenName().getValue());
System.out.println("PID dob "+pid.getDateTimeOfBirth().getValue());
System.out.println("PID gender "+pid.getAdministrativeSex().getIdentifier().getValue());
System.out.println();
System.out.println("PV1 admit datetime "+pv1.getAdmitDateTime().getValue());
System.out.println("PV1 bed status "+pv1.getBedStatus().getValueSetOID());
System.out.println("PV1 assigned patient location bed "+pv1.getAssignedPatientLocation().getBed().getNamespaceID().getValue());
System.out.println("PV1 assigned patient location room "+pv1.getAssignedPatientLocation().getRoom().getNamespaceID().getValue());
System.out.println("PV1 assigned patient location floor "+pv1.getAssignedPatientLocation().getFloor().getNamespaceID().getValue());
System.out.println("PV1 assigned patient location building "+pv1.getAssignedPatientLocation().getBuilding().getNamespaceID().getValue());
System.out.println("PV1 prior patient location bed "+pv1.getPriorPatientLocation().getBed().getNamespaceID().getValue());
System.out.println("PV1 prior patient location room "+pv1.getPriorPatientLocation().getRoom().getNamespaceID().getValue());
System.out.println("PV1 prior patient location fllor "+pv1.getPriorPatientLocation().getFloor().getNamespaceID().getValue());
System.out.println("PV1 prior patient location building "+pv1.getPriorPatientLocation().getBuilding().getNamespaceID().getValue());
System.out.println("PV1 discharge datetime "+pv1.getDischargeDateTime().getValue());
patientInfo.setSendingApplication(msh.getSendingApplication().getNamespaceID().getValue());
patientInfo.setSendingFacility(msh.getSendingFacility().getNamespaceID().getValue());
patientInfo.setPatientId(pid.getPatientIdentifierList(0).getIDNumber().getValue());
patientInfo.setGivenName(pid.getPatientName(0).getGivenName().getValue());
patientInfo.setAdministrativeSex(pid.getAdministrativeSex().getIdentifier().getValue());
} catch (Exception e) {
e.getStackTrace();
} finally{
try {
context.close();
} catch (IOException e) {
context = null;
e.printStackTrace();
}
}
patientInfo.setPatientDetails(decodedADT);
ADTService adtService = new ADTService();
adtService.savePatientDetails(patientInfo);
//System.out.println(ADTMessage.Contents);
reply = SubProcess();
return reply;
}
The trigger in event in MSH/9/2 (A01) does not match the event type code in EVN/1 (P03). The message structure in MSH/9/3 is missing.
Related
I used the netmq (VisualStudio 2022, by Nuget install netmq) as https://www.nuget.org/packages/NetMQ/ described.
One SubscriberSocket one thread to connect and receive message from one publisher. source code like below:
public void ZMQReceiveThread(string serverIP, int port)
{
//Create SubscriberSocket
SubscriberSocket subSocket = new SubscriberSocket();
//Connect to Publisher
subSocket.Connect("tcp://" + serverIP + ":" + port.ToString());
//Subscribe all topics
subSocket.Subscribe("");
//set timeout value
int timeout = 10000 * 300; //300ms
TimeSpan ts = new TimeSpan(timeout);
while (!_isStopEnabled)
{
NetMQMessage recvMessage = null;
bool bSuccess = subSocket.TryReceiveMultipartMessage(ts, ref recvMessage, 1);
if(bSuccess == true) //Recieve data successfully
{
//Handle the recvMessage
}
else //Timeout
{
//output log message
Loger.Error($"TryReceiveMultipartMessage({ts.TotalMilliseconds} ms) timeout...");
continue;
}
}
}
sometimes the subSocket.TryReceiveMultipartMessage() timeout although the publisher sent message continuously (we used another test app written in C language linked libzmq(https://github.com/zeromq/libzmq) which can receive the continuous message).
Any comments about this topic?
thanks a lot in advance.
I looked through the netmq source code(https://github.com/zeromq/netmq) but cannot find any clues about TryReceiveMultipartMessage()
I'm trying to start a conference by using UCMA 4.0 basic conferencing sample and first user endpoint stuck at establishing the call (it's lync is not ringing). Timeout exception is triggered after a while. What's the main problem ?
BTW, platform is being started already with discovering 3 application endpoints as established.
sip:kl.dev.local#dev.local;gruu;opaque=srvr:yyapp:EHghH8UXNVqIedXU3YgJyQAAYYApp
sip:kl.cdev.local#dev.local;gruu;opaque=srvr:yyapp:EHghH8UXNVqIedXU3YgJyQAAMachine1
sip:kl.dev.local#dev.local;gruu;opaque=srvr:yyapp:EHghH8UXNVqIedXU3YgJyQAAMachine2
sip:kl.dev.local#dev.local;gruu;opaque=srvr:yyapp:EHghH8UXNVqIedXU3YgJyQAAMachine3
'LyncGame.Gateway.TestConnection.vshost.exe' (CLR v4.0.30319: LyncGame.Gateway.TestConnection.vshost.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.SqlXml\v4.0_4.0.0.0__b77a5c561934e089\System.Data.SqlXml.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'LyncGame.Gateway.TestConnection.vshost.exe' (CLR v4.0.30319: LyncGame.Gateway.TestConnection.vshost.exe): Loaded 'System.Xml.Xsl.CompiledQuery.1'.
The thread 0x6e8 has exited with code 259 (0x103).
The thread 0x3dd4 has exited with code 259 (0x103).
The thread 0x2138 has exited with code 259 (0x103).
'LyncGame.Gateway.TestConnection.vshost.exe' (CLR v4.0.30319: LyncGame.Gateway.TestConnection.vshost.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Security\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Security.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The thread 0x3180 has exited with code 259 (0x103).
The thread 0x350c has exited with code 259 (0x103).
The thread 0x1698 has exited with code 0 (0x0).
The thread 0x3ef4 has exited with code 0 (0x0).
The thread 0x3f00 has exited with code 259 (0x103).
The thread 0x2a24 has exited with code 259 (0x103).
The thread 0x3fc0 has exited with code 259 (0x103).
The thread 0x3750 has exited with code 259 (0x103).
The thread 0x27b8 has exited with code 259 (0x103).
The thread 0x11e0 has exited with code 259 (0x103).
The thread 0x2214 has exited with code 259 (0x103).
The thread 0x1564 has exited with code 259 (0x103).
The thread 0x3740 has exited with code 259 (0x103).
The thread 0x28a8 has exited with code 259 (0x103).
The thread 0x1da8 has exited with code 259 (0x103).
A first chance exception of type 'Microsoft.Rtc.Signaling.OperationTimeoutException' occurred in Microsoft.Rtc.Collaboration.dll
class UCMAConference
{
#region Locals
// The IM to send upon joining the MCU.
private static String _messageToSend = "Hello, World!";
private Conference _conference;
private ApplicationEndpoint _callerEndpoint, _calleeEndpoint;
//Wait handles are only present to keep things synchronous and easy to read.
private AutoResetEvent _waitForCallEstablish = new AutoResetEvent(false);
private AutoResetEvent _waitForConferenceScheduling = new AutoResetEvent(false);
private AutoResetEvent _waitForConferenceJoin = new AutoResetEvent(false);
private AutoResetEvent _waitForMessageReceived = new AutoResetEvent(false);
private AutoResetEvent _waitForMessage2Received = new AutoResetEvent(false);
private AutoResetEvent waitForUserEndpointEstablish = new AutoResetEvent(false);
private AutoResetEvent _waitForShutdown = new AutoResetEvent(false);
private AutoResetEvent _waitForConversationInviteRemoteParticipants = new AutoResetEvent(false);
private InstantMessagingFlow _IMFlow;
private InstantMessagingFlow _IMFlow2;
#endregion
public Conference StartConference()
{
try
{
foreach (var item in PlatformDataProvider.DataProvider.AppEndpoints)
{
WriteLog.AddLine(item.EndpointUri + item.OwnerDisplayName);
Console.WriteLine(item.EndpointUri + item.OwnerDisplayName);
}
// to create end point(s)
UCMACoach ucmaCoach = new UCMACoach();
UserEndpointSettings settings = new UserEndpointSettings("sip:user8#dev.local");
UserEndpoint _userEndpoint = new UserEndpoint(PlatformDataProvider.DataProvider.CollabPlatform, settings);
_userEndpoint.BeginEstablish(ar =>
{
try
{
_userEndpoint.EndEstablish(ar);
waitForUserEndpointEstablish.Set();
}
catch (Exception ex)
{
WriteLog.AddLine("Error on establish: " + ex.Message);
waitForUserEndpointEstablish.Set();
}
}, null);
waitForUserEndpointEstablish.WaitOne();
WriteLog.AddLine("User endpoint has been established ");
_userEndpoint.LocalOwnerPresence.BeginSubscribe(r =>
{
}, null);
//IAsyncResult result = _userEndpoint.LocalOwnerPresence.BeginPublishPresence(Microsoft.Rtc.Collaboration.Presence.PresenceAvailability.Busy);
// Create a user endpoint, using the network credential object
// defined above.
_callerEndpoint = PlatformDataProvider.DataProvider.AppEndpoints[1];
/* friendly name for conference leader endpoint */
// Create a second user endpoint, using the network credential object
// defined above.
_calleeEndpoint = PlatformDataProvider.DataProvider.AppEndpoints[2];
/* friendly name for conference attendee endpoint */
// Get the URI for the user logged onto Microsoft Lync
String _ocUserURI = "sip:user9#dev.local";
// One of the endpoints schedules the conference in advance. At
// schedule time, all the conference settings are set.
// The base conference settings object, used to set the policies for the conference.
ConferenceScheduleInformation conferenceScheduleInformation = new ConferenceScheduleInformation();
// An open meeting (participants can join who are not on the list),
// but requiring authentication (no anonymous users allowed.)
conferenceScheduleInformation.AccessLevel = ConferenceAccessLevel.SameEnterprise;
// The below flag determines whether or not the passcode is optional
// for users joining the conference.
conferenceScheduleInformation.IsPasscodeOptional = true;
conferenceScheduleInformation.Passcode = "1357924680";
// The verbose description of the conference
conferenceScheduleInformation.Description = "StartReady | Conference Testing";
// The below field indicates the date and time after which the conference can be deleted.
conferenceScheduleInformation.ExpiryTime = System.DateTime.Now.AddHours(5);
// These two lines assign a set of modalities (here, only
// InstantMessage) from the available MCUs to the conference. Custom
// modalities (and their corresponding MCUs) may be added at this
// time as part of the extensibility model.
ConferenceMcuInformation instantMessageMCU = new ConferenceMcuInformation(McuType.InstantMessaging);
conferenceScheduleInformation.Mcus.Add(instantMessageMCU);
// Now that the setup object is complete, schedule the conference
// using the conference services off of Endpoint. Note: the conference
// organizer is considered a leader of the conference by default.
_callerEndpoint.ConferenceServices.BeginScheduleConference(conferenceScheduleInformation,
EndScheduleConference, _callerEndpoint.ConferenceServices);
// Wait for the scheduling to complete.
_waitForConferenceScheduling.WaitOne();
// Now that the conference is scheduled, it's time to join it. As we
// already have a reference to the conference object populated from
// the EndScheduleConference call, we do not need to get the
// conference first. Initialize a conversation off of the endpoint,
// and join the conference from the uri provided above.
Conversation callerConversation = new Conversation(_callerEndpoint);
callerConversation.ConferenceSession.StateChanged += new
EventHandler<StateChangedEventArgs<ConferenceSessionState>>(ConferenceSession_StateChanged);
// Join and wait, again forcing synchronization.
callerConversation.ConferenceSession.BeginJoin(_conference.ConferenceUri, null /*joinOptions*/,
EndJoinConference, callerConversation.ConferenceSession);
_waitForConferenceJoin.WaitOne();
// Placing the calls on the conference-connected conversation
// connects to the respective MCUs. These calls may then be used to
// communicate with the conference/MCUs.
InstantMessagingCall instantMessagingCall = new InstantMessagingCall(callerConversation);
// Hooking up event handlers and then placing the call.
instantMessagingCall.InstantMessagingFlowConfigurationRequested +=
this.instantMessagingCall_InstantMessagingFlowConfigurationRequested;
instantMessagingCall.StateChanged += this._call_StateChanged;
instantMessagingCall.BeginEstablish(EndCallEstablish, instantMessagingCall);
//Synchronize to ensure that call has completed.
_waitForCallEstablish.WaitOne();
//send conf invite
ConferenceInvitationDeliverOptions deliverOptions = new ConferenceInvitationDeliverOptions();
deliverOptions.ToastMessage = new ToastMessage("Welcome to conference of StartReady Demo");
ConferenceInvitation invitation = new ConferenceInvitation(callerConversation);
invitation.BeginDeliver(_ocUserURI, deliverOptions, EndDeliverInvitation, invitation);
// Synchronize to ensure that invitation is complete
_waitForConversationInviteRemoteParticipants.WaitOne();
//And from the other endpoint's perspective:
//Initialize a conversation off of the endpoint, and join the
//conference from the uri provided above.
Conversation calleeConversation = new Conversation(_calleeEndpoint);
calleeConversation.ConferenceSession.StateChanged += new
EventHandler<StateChangedEventArgs<ConferenceSessionState>>(ConferenceSession_StateChanged);
// Join and wait, again forcing synchronization.
calleeConversation.ConferenceSession.BeginJoin(_conference.ConferenceUri, null /*joinOptions*/,
EndJoinConference, calleeConversation.ConferenceSession);
_waitForConferenceJoin.WaitOne();
// Placing the calls on the conference-connected conversation
// connects to the respective MCUs. These calls may then be used to
//communicate with the conference/MCUs.
InstantMessagingCall instantMessagingCall2 = new InstantMessagingCall(calleeConversation);
//Hooking up event handlers and then placing the call.
instantMessagingCall2.InstantMessagingFlowConfigurationRequested +=
this.instantMessagingCall2_InstantMessagingFlowConfigurationRequested;
instantMessagingCall2.StateChanged += this._call_StateChanged;
instantMessagingCall2.BeginEstablish(EndCallEstablish, instantMessagingCall2);
//Synchronize to ensure that call has completed.
_waitForCallEstablish.WaitOne();
//Synchronize to ensure that all messages are sent and received
_waitForMessageReceived.WaitOne();
//Wait for shutdown initiated by user
//_waitForShutdown.WaitOne();
//UCMASampleHelper.PauseBeforeContinuing("Press ENTER to shutdown and exit.");
return _conference;
}
catch (Exception ex)
{
WriteLog.AddLine("Cannot start conference: " + ex.Message);
return null;
}
}
#region side methods
void ConferenceSession_StateChanged(object sender, StateChangedEventArgs<ConferenceSessionState> e)
{
ConferenceSession confSession = sender as ConferenceSession;
//Session participants allow for disambiguation.
WriteLog.AddLine("The conference session with Local Participant: " +
confSession.Conversation.LocalParticipant + " has changed state. " +
"The previous conference state was: " + e.PreviousState +
" and the current state is: " + e.State);
}
// Flow created indicates that there is a flow present to begin media
// operations with, and that it is no longer null.
public void instantMessagingCall_InstantMessagingFlowConfigurationRequested
(object sender, InstantMessagingFlowConfigurationRequestedEventArgs e)
{
InstantMessagingFlow instantMessagingFlow = sender as InstantMessagingFlow;
WriteLog.AddLine("Caller's Flow Created.");
instantMessagingFlow = e.Flow;
_IMFlow = instantMessagingFlow;
// Now that the flow is non-null, bind the event handlers for State
// Changed and Message Received. When the flow goes active, (as
// indicated by the state changed event) the program will send the
// IM in the event handler.
instantMessagingFlow.StateChanged += this.instantMessagingFlow_StateChanged;
// Message Received is the event used to indicate that a message has
// been received from the far end.
instantMessagingFlow.MessageReceived += this.instantMessagingFlow_MessageReceived;
}
// Flow created indicates that there is a flow present to begin media
// operations with, and that it is no longer null.
public void instantMessagingCall2_InstantMessagingFlowConfigurationRequested(
object sender, InstantMessagingFlowConfigurationRequestedEventArgs e)
{
InstantMessagingFlow instantMessagingFlow = sender as InstantMessagingFlow;
WriteLog.AddLine("Callee's Flow Created.");
instantMessagingFlow = e.Flow;
_IMFlow2 = instantMessagingFlow;
// Now that the flow is non-null, bind the event handlers for State
// Changed and Message Received. When the flow goes active, the
// program will send the IM in the event handler.
instantMessagingFlow.StateChanged += this.instantMessagingFlow2_StateChanged;
// Message Received is the event used to indicate that a message
// from the far end has been received.
instantMessagingFlow.MessageReceived += this.instantMessagingFlow2_MessageReceived;
}
private void instantMessagingFlow_StateChanged(object sender, MediaFlowStateChangedEventArgs e)
{
InstantMessagingFlow instantMessagingFlow = sender as InstantMessagingFlow;
WriteLog.AddLine("Flow state changed from " + e.PreviousState + " to " + e.State);
//When flow is active, media operations (here, sending an IM) may begin.
if (e.State == MediaFlowState.Active)
{
_IMFlow = instantMessagingFlow;
WriteLog.AddLine("Please type the message to send...");
string msg = Console.ReadLine();
//Send the message on the InstantMessagingFlow.
instantMessagingFlow.BeginSendInstantMessage(msg, EndSendMessage, instantMessagingFlow);
}
}
private void instantMessagingFlow2_StateChanged(object sender, MediaFlowStateChangedEventArgs e)
{
InstantMessagingFlow instantMessagingFlow = sender as InstantMessagingFlow;
WriteLog.AddLine("Flow state changed from " + e.PreviousState + " to " + e.State);
//When flow is active, media operations (here, sending an IM) may begin.
if (e.State == MediaFlowState.Active)
{
_IMFlow2 = instantMessagingFlow;
}
}
private void EndSendMessage(IAsyncResult ar)
{
InstantMessagingFlow instantMessagingFlow = ar.AsyncState as InstantMessagingFlow;
try
{
instantMessagingFlow.EndSendInstantMessage(ar);
WriteLog.AddLine("The message has been sent.");
}
catch (OperationTimeoutException opTimeEx)
{
// OperationFailureException: Indicates failure to connect the
// IM to the remote party due to timeout (called party failed
// to respond within the expected time).
// TODO (Left to the reader): Add error handling code
WriteLog.AddLine(opTimeEx.ToString());
}
}
private void instantMessagingFlow_MessageReceived(object sender, InstantMessageReceivedEventArgs e)
{
InstantMessagingFlow instantMessagingFlow = sender as InstantMessagingFlow;
//On an incoming Instant Message, print the contents to the console.
WriteLog.AddLine("In caller's message handler: " + e.Sender.DisplayName + " said: " + e.TextBody);
_waitForMessageReceived.Set();
}
private void instantMessagingFlow2_MessageReceived(object sender, InstantMessageReceivedEventArgs e)
{
InstantMessagingFlow instantMessagingFlow = sender as InstantMessagingFlow;
//On an incoming Instant Message, print the contents to the console.
WriteLog.AddLine("In callee's message handler: " + e.Sender.DisplayName + " said: " + e.TextBody);
WriteLog.AddLine("Message received will be echoed");
_messageToSend = "echo: " + e.TextBody;
//Send the message on the InstantMessagingFlow.
if (_IMFlow2 != null && _IMFlow2.State == MediaFlowState.Active)
{
_IMFlow2.BeginSendInstantMessage(_messageToSend, EndSendMessage, instantMessagingFlow);
}
else
WriteLog.AddLine("Could not echo message because flow was either null or inactive");
_waitForMessage2Received.Set();
}
private void EndCallEstablish(IAsyncResult ar)
{
Call call = ar.AsyncState as Call;
try
{
call.EndEstablish(ar);
WriteLog.AddLine("The call with Local Participant: " + call.Conversation.LocalParticipant +
" and Remote Participant: " + call.RemoteEndpoint.Participant +
" is now in the established state.");
}
catch (OperationFailureException opFailEx)
{
// OperationFailureException: Indicates failure to connect the
// call to the remote party.
// TODO (Left to the reader): Add error handling code
WriteLog.AddLine(opFailEx.ToString());
}
catch (RealTimeException exception)
{
// RealTimeException may be thrown on media or link-layer
//failures.
// TODO (Left to the reader): Add error handling code
WriteLog.AddLine(exception.ToString());
}
finally
{
//Again, just to sync the completion of the code.
_waitForCallEstablish.Set();
}
}
private void EndDeliverInvitation(IAsyncResult ar)
{
ConferenceInvitation invitation = ar.AsyncState as ConferenceInvitation;
try
{
invitation.EndDeliver(ar);
}
catch (OperationFailureException opFailEx)
{
// OperationFailureException: Indicates failure to connect the
// call to the remote party.
// TODO (Left to the reader): Add error handling code
WriteLog.AddLine(opFailEx.ToString());
}
catch (RealTimeException exception)
{
// RealTimeException may be thrown on media or link-layer failures.
// TODO (Left to the reader): Add error handling code
WriteLog.AddLine(exception.ToString());
}
finally
{
//Again, just to sync the completion of the code.
_waitForConversationInviteRemoteParticipants.Set();
}
}
private void EndScheduleConference(IAsyncResult ar)
{
ConferenceServices confSession = ar.AsyncState as ConferenceServices;
try
{
//End schedule conference returns the conference object, which
// contains the vast majority of the data relevant to that
// conference.
_conference = confSession.EndScheduleConference(ar);
WriteLog.AddLine("");
WriteLog.AddLine(" The conference is now scheduled.");
WriteLog.AddLine("");
}
catch (ConferenceFailureException confFailEx)
{
// ConferenceFailureException may be thrown on failures to
// schedule due to MCUs being absent or unsupported, or due to
// malformed parameters.
// TODO (Left to the reader): Add error handling code
WriteLog.AddLine(confFailEx.ToString());
}
//Again, for sync. reasons.
_waitForConferenceScheduling.Set();
}
private void EndJoinConference(IAsyncResult ar)
{
ConferenceSession confSession = ar.AsyncState as ConferenceSession;
try
{
confSession.EndJoin(ar);
}
catch (ConferenceFailureException confFailEx)
{
// ConferenceFailureException may be thrown on failures due to
// MCUs being absent or unsupported, or due to malformed parameters.
// TODO (Left to the reader): Add error handling code
WriteLog.AddLine(confFailEx.ToString());
}
catch (RealTimeException rTEx)
{
// TODO (Left to the reader): Add error handling code
WriteLog.AddLine(rTEx.ToString());
}
finally
{
//Again, for sync. reasons.
_waitForConferenceJoin.Set();
}
}
//Just to record the state transitions in the console.
void _call_StateChanged(object sender, CallStateChangedEventArgs e)
{
Call call = sender as Call;
//Call participants allow for disambiguation.
WriteLog.AddLine("The call with Local Participant: " + call.Conversation.LocalParticipant +
" has changed state. The previous call state was: " + e.PreviousState +
" and the current state is: " + e.State);
}
#endregion
}
}
The other thing that's really useful here is to run OCSLogger on the application server and see what comes back. You can run S4 to get SIP traces. Might just be something simple like you're not able to receive messages on 5061 (or whichever callback port you specified in your provisioning). If it's only failing on A/V, look at what addresses are being used in the SDP offer/answer and see if those are reachable as well. Again, OCSLogger (or the Lync CLS) and Snooper are your friends here.
I'm trying to respond to SNMP GET requests from SnmpB with SNMP4j 2.3.1 (running on Windows).
In "Discover" mode, SnmpB queries by broadcasting 255.255.255.255 (checked with Wireshark) and I receive a GET request with standard OID (sysDescr, sysUpTime, sysContact, sysName and sysLocation). It finds my instance with the information I coded ("My System", "Myself", ...) (note that it also works when I enter the IP address under the "IP networks" textboxes, though I don't see any traffic on Wireshark but I receive the GET request):
I did write a very simple MIB file that I imported into SnmpB. It defines a single Integer32 data that I want to retrieve using an SNMP GET request from SnmpB.
However, using the same code than for the standard sys* OID, SnmpB doesn't seem to receive that data ("Timeout" in red on the top-right):
I did try Wireshark to check network activity and I don't see anything, so I guess it takes place on localhost (which is not accessible with Wireshark on Windows)? But the traces below show it does not (peerAddress=192.168.56.1)...
Here is the MIB file (code follows):
MY-TEST-MIB DEFINITIONS ::= BEGIN
IMPORTS
enterprises, MODULE-IDENTITY, OBJECT-TYPE, Integer32
FROM SNMPv2-SMI;
myTest MODULE-IDENTITY
LAST-UPDATED "201412301216Z"
ORGANIZATION "My org"
CONTACT-INFO "Matthieu Labas"
DESCRIPTION "MIB Test"
REVISION "201412301216Z"
DESCRIPTION "Generated"
::= { enterprises 12121 }
myData OBJECT-TYPE
SYNTAX Integer32
MAX-ACCESS read-only
STATUS current
DESCRIPTION "My data for test"
::= { myTest 1 }
END
... and the code:
public class RespondGET implements CommandResponder {
public static final OID sysDescr = new OID("1.3.6.1.2.1.1.1.0");
public static final OID sysUpTime = new OID("1.3.6.1.2.1.1.3.0");
public static final OID sysContact = new OID("1.3.6.1.2.1.1.4.0");
public static final OID sysName = new OID("1.3.6.1.2.1.1.5.0");
public static final OID sysLocation = new OID("1.3.6.1.2.1.1.6.0");
public static final OID myData = new OID("1.3.6.1.4.1.12121.1.0");
private Snmp snmp;
public RespondGET() throws IOException {
MessageDispatcher dispatcher = new MessageDispatcherImpl();
dispatcher.addMessageProcessingModel(new MPv2c()); // v2c only
snmp = new Snmp(dispatcher, new DefaultUdpTransportMapping(new UdpAddress("192.168.56.1/161"), true));
snmp.addCommandResponder(this);
snmp.listen();
}
#Override
public void processPdu(CommandResponderEvent event) {
System.out.println("Received PDU "+event);
PDU pdu = event.getPDU();
switch (pdu.getType()) {
case PDU.GET:
List<VariableBinding> responses = new ArrayList<VariableBinding>(pdu.size());
for (VariableBinding v : pdu.getVariableBindings()) {
OID oid = v.getOid();
// Answer the usual SNMP requests
if (sysDescr.equals(oid)) {
responses.add(new VariableBinding(oid, new OctetString("My System description")));
} else if (sysUpTime.equals(oid)) {
responses.add(new VariableBinding(oid, new TimeTicks(ManagementFactory.getRuntimeMXBean().getUptime())));
} else if (sysContact.equals(oid)) {
responses.add(new VariableBinding(oid, new OctetString("Myself")));
} else if (sysName.equals(oid)) {
responses.add(new VariableBinding(oid, new OctetString("My System")));
} else if (sysLocation.equals(oid)) {
responses.add(new VariableBinding(oid, new OctetString("In here")));
} else if (myData.equals(oid)) { // MyData handled here
responses.add(new VariableBinding(oid, new Integer32(18)));
}
}
try {
CommunityTarget comm = new CommunityTarget(event.getPeerAddress(), new OctetString(event.getSecurityName()));
comm.setSecurityLevel(event.getSecurityLevel());
comm.setSecurityModel(event.getSecurityModel());
PDU resp = new PDU(PDU.RESPONSE, responses);
System.out.println(String.format("Sending response PDU to %s/%s: %s", event.getPeerAddress(), new String(event.getSecurityName()), resp));
snmp.send(resp, comm);
} catch (IOException e) {
System.err.println(String.format("Unable to send response PDU! (%s)", e.getMessage()));
}
event.setProcessed(true);
break;
default:
System.err.println(String.format("Unhandled PDU type %s.", PDU.getTypeString(pdu.getType())));
break;
}
}
public static void main(String[] args) throws IOException {
RespondGET rg = new RespondGET();
System.out.println("Listening...");
int n = 300; // 5 min
while (true) {
try { Thread.sleep(1000); } catch (InterruptedException e) { }
if (--n <= 0) break;
}
System.out.println("Stopping...");
rg.snmp.close();
}
}
It produces the following output when I click "discover" under SnmpB and right-click on myData in the MIB Tree and "Get" (slightly reformatted for readability):
Listening...
Received PDU CommandResponderEvent[securityModel=2, securityLevel=1, maxSizeResponsePDU=65535,
pduHandle=PduHandle[16736], stateReference=StateReference[msgID=0,pduHandle=PduHandle[16736],
securityEngineID=null,securityModel=null,securityName=public,securityLevel=1,
contextEngineID=null,contextName=null,retryMsgIDs=null], pdu=GET[requestID=16736, errorStatus=Success(0), errorIndex=0,
VBS[1.3.6.1.2.1.1.1.0 = Null; 1.3.6.1.2.1.1.3.0 = Null; 1.3.6.1.2.1.1.4.0 = Null; 1.3.6.1.2.1.1.5.0 = Null; 1.3.6.1.2.1.1.6.0 = Null]],
messageProcessingModel=1, securityName=public, processed=false, peerAddress=192.168.56.1/49561, transportMapping=org.snmp4j.transport.DefaultUdpTransportMapping#120d62b, tmStateReference=null]
Sending response PDU to 192.168.56.1/49561/public: RESPONSE[requestID=0, errorStatus=Success(0), errorIndex=0,
VBS[1.3.6.1.2.1.1.1.0 = My System description; 1.3.6.1.2.1.1.3.0 = 0:01:03.18; 1.3.6.1.2.1.1.4.0 = Myself; 1.3.6.1.2.1.1.5.0 = My System; 1.3.6.1.2.1.1.6.0 = In here]]
Received PDU CommandResponderEvent[securityModel=2, securityLevel=1, maxSizeResponsePDU=65535,
pduHandle=PduHandle[1047], stateReference=StateReference[msgID=0,pduHandle=PduHandle[1047],
securityEngineID=null,securityModel=null,securityName=public,securityLevel=1,
contextEngineID=null,contextName=null,retryMsgIDs=null], pdu=GET[requestID=1047, errorStatus=Success(0), errorIndex=0,
VBS[1.3.6.1.4.1.12121.1.0 = Null]], messageProcessingModel=1, securityName=public, processed=false, peerAddress=192.168.56.1/49560, transportMapping=org.snmp4j.transport.DefaultUdpTransportMapping#120d62b, tmStateReference=null]
Sending response PDU to 192.168.56.1/49560/public: RESPONSE[requestID=0, errorStatus=Success(0), errorIndex=0, VBS[1.3.6.1.4.1.12121.1.0 = 18]]
Stopping...
What am I missing here? Could that "just" be a network routing issue?
After setting up a VM and checking with Wireshark, it turned out I forgot to set, on the response PDU, the same request ID than the GET PDU.
It was solved by adding resp.setRequestID(pdu.getRequestID()); when building the response PDU
CommunityTarget comm = new CommunityTarget(event.getPeerAddress(), new OctetString(event.getSecurityName()));
comm.setSecurityLevel(event.getSecurityLevel());
comm.setSecurityModel(event.getSecurityModel());
PDU resp = new PDU(PDU.RESPONSE, responses);
resp.setRequestID(pdu.getRequestID()); // Forgot that!
snmp.send(resp, comm);
Thanks to #Jolta for his patience during New Year holiday and his insisting on using Wireshark for further checking. :)
As a part of my final year project in university I'm analysing Twitter data using graph entropy. To briefly outline the purposes:
I want to collect all tweet from a certain area (London) containing keywords "cold", "flu" etc. This part is done using Streaming API.
Then I want to access each of the user's (who tweeted about being ill, collected in previous section) list of followers and following to be able to build a graph for further analysis. And here I'm stuck.
I assume for the second part I should be using Search API, but I keep getting error 88 even for a single user.
Below is the code I use for the first part:
final TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
.getInstance();
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
User user = status.getUser();
long userid = user.getId();
String username = status.getUser().getScreenName();
String content = status.getText();
GeoLocation geolocation = status.getGeoLocation();
Date date = status.getCreatedAt();
if (filterText(content)) {
System.out.println(username+"\t"+userid);
System.out.println(content);
System.out.println(geolocation);
System.out.println(date);
try {
getConnections(userid);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//OTHER LISTENER METHODS
};
twitterStream.addListener(listener);
// London
double lat3 = 51.23;
double lat4 = 51.72;
double lon3 = -0.56;
double lon4 = 0.25;
double[][] bb = { { lon3, lat3 }, { lon4, lat4 } };
FilterQuery fq = new FilterQuery();
fq.locations(bb);
twitterStream.filter(fq);
private static boolean filterText(String tweet) {
return tweet.contains("flu")
|| tweet.contains("cold")
|| tweet.contains("cough")
|| tweet.contains("virus");
}
And this is what I'm trying to complete the second part with:
private static void getConnections(long id) throws TwitterException {
Twitter twitter = new TwitterFactory().getInstance();
long lCursor = -1;
IDs friendsIDs = twitter.getFriendsIDs(id, lCursor);
System.out.println(twitter.showUser(id).getName());
System.out.println("==========================");
do
{
for (long i : friendsIDs.getIDs())
{
System.out.println("follower ID #" + i);
System.out.println(twitter.showUser(i).getName());
}
}while(friendsIDs.hasNext());
}
Any suggestions?
When you receive error 88, that's Twitter telling you that you're being rate limited:
The request limit for this resource has been reached for the current rate limit window.
The search call is limited to either 180 or 450 calls in a 15 minute period. You can see the rate limits here and this documentation explains the rate limiting in detail.
As for how to get around it, you may have to throttle your search calls to the API. Twitter4J provides ways to inspect current limits/exhaustion which may help - see Twitter#getRateLimitStatus().
I am trying to write a simple application to send messages to a topic from use input and show messages published on topic.
There are two command line executables - one for publisher and another for subscriber.
When I publish messages on a topic, I can see the messages getting submitted to the topic.
The following command shows that there are messages on the topic (see F1.gif):-
show stat EMS.Test.Topic
The following command shows that the messages are getting consumed by the subscribers (see F2.gif)
show stat consumers topic=EMS.Test.Topic
However, I am not able to retrieve messages the EMS .NET API. It gets stuck on Message msg = subscriber.Receive();. I made sure the connection details and authentication details are correct because they are used when publishing the messages.
public string ReceiveMessagesFromTopic(string topicName)
{
TopicConnection connection = null;
string messageFromPublisher = string.Empty;
try
{
var factory = new TIBCO.EMS.TopicConnectionFactory(serverUrl);
connection = factory.CreateTopicConnection(userName, password);
TopicSession session = connection.CreateTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.CreateTopic(topicName);
TopicSubscriber subscriber = session.CreateSubscriber(topic);
connection.Start();
while (true)
{
Message msg = subscriber.Receive();
if (msg == null)
{
break;
}
if (msg is TextMessage)
{
TextMessage tm = (TextMessage) msg;
messageFromPublisher = tm.Text;
}
}
connection.Close();
}
catch (EMSException e)
{
if (connection!=null)
{
connection.Close();
}
throw;
}
return messageFromPublisher;
}
There was a silly mistake in my .NET code. the following while loop never returns so there is no return. I need to break the while loop when I get a message. Duh!!!!
while (true)
{
Message msg = subscriber.Receive();
if (msg == null)
{
break;
}
if (msg is TextMessage)
{
TextMessage tm = (TextMessage) msg;
messageFromPublisher = tm.Text;
break;
}
}