This problem really has me scratching my head.
I have a chat application that parses xml from the server. It is successful parsing the message text, msg id, but I am getting a nullpointerException for the UserID but I am pulling it from the same location. Please help
// Get messages
NodeList messageList = documentElement.getElementsByTagName("MESSAGE");
ret.messages = new ChatStruct[messageList.getLength()];
Log.v("response","Message Length " + messageList.getLength());
for (int i = 0; i < messageList.getLength(); i++) {
Element messageNode = (Element) messageList.item(i);
ret.messages[i] = new ChatStruct();
// Get messageId
try {
Element messageIdNode = (Element) messageNode.getElementsByTagName("ID").item(0);
String messageId = messageIdNode.getFirstChild().getNodeValue();
System.out.println("messageId = " + messageId);
ret.messages[i].id = Long.parseLong(messageId);
//Log.v("Util","Message ID " + Long.parseLong(messageId));
} catch (Exception e) {
ret.messages[i].id = 0l;
// e.printStackTrace();
}
// Get text
try {
Element textNode = (Element) messageNode.getElementsByTagName("TEXT").item(0);
String text = textNode.getFirstChild().getNodeValue();
System.out.println("text = " + text);
ret.messages[i].textMessage = text.trim();
//Log.v("Util","Message text " + text.trim());
} catch (Exception e) {
ret.messages[i].textMessage = "";
// e.printStackTrace();
}
// Get userId
try {
//ret.messages[i].userId = 1;
//Log.v("Util # userID node","userID should be 1");
Element userIdNode = (Element) messageNode.getElementsByTagName("USERID").item(0);
Log.i("Util # userID node","userIdNode set");
String userId = userIdNode.getFirstChild().getNodeValue();
//String userId = "1";
Log.i("Util # userID node","userId String set");
System.out.println("userId = " + userId);
ret.messages[i].userId = Long.parseLong(userId);
//ret.messages[i].userId = 1;
} catch (Exception e) {
Log.v("Util # userID node", "there was an error " + e);
ret.messages[i].userId = 0l;
// e.printStackTrace();
}
I can hard code the string and it works but other than that the error occurs at
String userId = userIdNode.getFirstChild().getNodeValue();
It makes it up to commented line of code confirming the userIDNode is set
I can't figure out why userID is not coming in from the server here is the XML:
<MESSAGE>
<ID><?php echo $row_shouts['msgid']; ?></ID>
<USERID><?php echo $row_shouts['userid']; ?></USERID>
<GENDER><?php echo $row_shouts['gender']; ?></GENDER>
<ONLINE><?php echo $row_shouts['account_status'];?></ONLINE>
<TDATE><?php echo datee("h:i:s M, d Y", strtotime($row_shouts['date'])); ?></TDATE>
<ICONID><?php echo $iconid; ?></ICONID>
<PIC><?php echo $PIC; ?></PIC>
<MSGPIC><?php echo $row_shouts['media']; ?></MSGPIC>
<PICDATE><?php echo strtotime($row_shouts['picdate']); ?></PICDATE>
<ALIAS><![CDATA[<?php echo $row_shouts['nickname'];?>]]></ALIAS>
<TEXT><![CDATA[<?php echo $mesg;?>]]></TEXT>
</MESSAGE>
Did you check with the DTD file for the supplied Xml, May be USERID is not clearly defined there.
[please share the error logs]
What's the execption say if you print the stack trace? It might be because the user id isn't a long and you're trying to parse it. I don't see any errors in the retrieval of the user id.
Related
I got an error in my quickfixj Application. First, I got an error like this:
Out of order repeating group members
After that, I added this text into my initiator.config:
ValidateUserDefinedFields=N
ValidateIncomingMessage=N
But now I got another error in my application:
quickfix.FieldNotFound: Field was not found in message, field=55
at quickfix.FieldMap.getField(FieldMap.java:223)
at quickfix.FieldMap.getString(FieldMap.java:237)
at com.dxtr.fastmatch.marketdatarequestapps.TestMarketdataRequest.fromApp(TestMarketdataRequest.java:38)
at quickfix.Session.fromCallback(Session.java:1847)
at quickfix.Session.verify(Session.java:1791)
at quickfix.Session.verify(Session.java:1862)
at quickfix.Session.next(Session.java:1047)
at quickfix.Session.next(Session.java:1204)
at quickfix.mina.SingleThreadedEventHandlingStrategy$SessionMessageEvent.processMessage(SingleThreadedEventHandlingStrategy.java:163)
at quickfix.mina.SingleThreadedEventHandlingStrategy.block(SingleThreadedEventHandlingStrategy.java:113)
at quickfix.mina.SingleThreadedEventHandlingStrategy.lambda$blockInThread$1(SingleThreadedEventHandlingStrategy.java:145)
at quickfix.mina.SingleThreadedEventHandlingStrategy$ThreadAdapter$RunnableWrapper.run(SingleThreadedEventHandlingStrategy.java:267)
at java.lang.Thread.run(Thread.java:748)
My code for get value of symbols is :
public void fromApp(quickfix.Message message, SessionID sessionID)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
try {
String symbol = message.getString(Symbol.FIELD);
System.out.println(" FromApp " + message);
message.getString(TransactTime.FIELD);
// String seqNo = message.getString(MsgSeqNum.FIELD);
double bid = message.getDouble(MDEntryPx.FIELD);
double ask = message.getDouble(MDEntryPx.FIELD);
// System.out.println(seqNo + " " + message);
} catch (FieldNotFound fieldNotFound) {
fieldNotFound.printStackTrace();
}
}
I have also using this code
public void onMessage (MarketDataIncrementalRefresh message, SessionID sessionID) throws FieldNotFound{
try
{
MDReqID mdreqid = new MDReqID();
SendingTime sendingtime = new SendingTime();
NoMDEntries nomdentries = new NoMDEntries();
quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries group
= new quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries();
MDUpdateAction mdupdateaction = new MDUpdateAction();
DeleteReason deletereason = new DeleteReason();
MDEntryType mdentrytype = new MDEntryType();
MDEntryID mdentryid = new MDEntryID();
Symbol symbol = new Symbol();
MDEntryOriginator mdentryoriginator = new MDEntryOriginator();
MDEntryPx mdentrypx = new MDEntryPx();
Currency currency = new Currency();
MDEntrySize mdentrysize = new MDEntrySize();
ExpireDate expiredate = new ExpireDate();
ExpireTime expiretime = new ExpireTime();
NumberOfOrders numberoforders = new NumberOfOrders();
MDEntryPositionNo mdentrypositionno = new MDEntryPositionNo();
message.getField(nomdentries);
message.getField(sendingtime);
message.getGroup(1, group);
int list = nomdentries.getValue();
for (int i = 0; i < list; i++)
{
message.getGroup(i + 1, group);
group.get(mdupdateaction);
if (mdupdateaction.getValue() == '2')
System.out.println("Enter");
group.get(deletereason);
group.get(mdentrytype);
group.get(mdentryid);
group.get(symbol);
group.get(mdentryoriginator);
if (mdupdateaction.getValue() == '0')
group.get(mdentrypx);
group.get(currency);
if (mdupdateaction.getValue() == '0')
group.get(mdentrysize);
}
System.out.printf("Got Symbol {0} Price {1}",
symbol.getValue(), mdentrypx.getValue());
}catch (Exception ex)
{
System.out.println("error" + ex);
}
but i also get error like this
quickfix.FieldNotFound: Field was not found in message, field=55
at quickfix.FieldMap.getField(FieldMap.java:223)
at quickfix.FieldMap.getString(FieldMap.java:237)
at com.dxtr.fastmatch.marketdatarequestapps.TestMarketdataRequest.fromApp(TestMarketdataRequest.java:39)
at quickfix.Session.fromCallback(Session.java:1847)
at quickfix.Session.verify(Session.java:1791)
at quickfix.Session.verify(Session.java:1862)
at quickfix.Session.next(Session.java:1047)
at quickfix.Session.next(Session.java:1204)
at quickfix.mina.SingleThreadedEventHandlingStrategy$SessionMessageEvent.processMessage(SingleThreadedEventHandlingStrategy.java:163)
at quickfix.mina.SingleThreadedEventHandlingStrategy.block(SingleThreadedEventHandlingStrategy.java:113)
at quickfix.mina.SingleThreadedEventHandlingStrategy.lambda$blockInpacket_write_wait: Connection to 3.13.235.241 port 22: Broken pipe
and here the value i check in my message.log
8=FIX.4.2^A9=0217^A35=X^A34=7291^A49=Fastmatch1^A52=20200401-10:47:59.833^A56=MDValueTrade2UAT1^A262=VT_020^A268=02^A279=2^A55=GBP/CHF^A269=0^A278=1140851192^A270=1.19503^A271=02000000^A279=0^A55=GBP/CHF^A269=0^A278=1140851194^A270=1.19502^A271=06000000^A10=114^A
my broker have send to me the price and etc
My question is: how to fix my problem from this code ?
First, I got an error like this:
Out of order repeating group members
Your data dictionary doesn't match your counterparty's. Fix that and this will go away.
After that, I added this text into my initiator.config:
ValidateUserDefinedFields=N
ValidateIncomingMessage=N
This did not fix anything -- it HIDES your actual problem and has you looking at a new fake problem.
What you need to do:
Your configuration has this, right?
UseDataDictionary=Y
DataDictionary=path/to/FIXnn.xml
# or if FIX5:
AppDataDictionary=path/to/FIX5n.xml
TransportDataDictionary=path/to/FIXT.xml
Find your counterparty's documentation, and make sure your xml file's messages and fields match what they say they're going to send you. Make sure all repeating groups have the same fields in the same order.
Here is some documentation about how the Data Dictionary xml file is structured. It's pretty easy.
I need to get the ID of room by its name from JSONObject.
I uploaded Json file here: https://gitlab.com/JaroslavVond/json/blob/master/Json
So I know the name of the room (Kitchen1) and I need to write some function in Java that will return me the ID of the room (in this case "1").
Any ideas how to do that?
So far I have something like this:
private static String GetIdRoom(String room) {
String id = "";
JSONObject myResponse = SendHTTP("/groups", "GET", "");
try {
// some code to get ID of room
} catch (Exception ex) {
System.out.println("error - " + ex);
}
return null ;
}
Iterator<?> ids = myResponse.keys();
while( ids.hasNext() ) {
id = (String) ids.next();
if(myResponse.getJSONObject(id).getString("name").equals(room)){
return id;
}
}
I am trying to extract pst file into msg.
I am using aspose jar. I share my code where we get exact number of file in each subfolder.
public static void displayFolderAndMessageInformationForPSTFile(String dataDir) {
// Load the Outlook PST file
PersonalStorage pst = PersonalStorage.fromFile(dataDir + "allen.pst");
// Get the folders information
FolderInfoCollection folderInfoCollection = pst.getRootFolder().getSubFolders();
// Browse through each folder to display folder name and number of messages
for (int i = 0; i < folderInfoCollection.size(); i++) {
FolderInfo folderInfo = (FolderInfo) folderInfoCollection.get_Item(i);
System.out.println("FolderId: " + folderInfo.getEntryIdString());
System.out.println("Folder: " + folderInfo.getDisplayName());
System.out.println("Total items: " + folderInfo.getContentCount());
System.out.println("Total unread items: " + folderInfo.getContentUnreadCount());
System.out.println("-----------------------------------");
}
}
FolderId: AAAAAJJu05VTxVRJlC5mJefQvVeCgAAA
Folder: Inbox
Total items: 66
Total unread items: 0
But when extract message content then i get different number of msg. It give only 49 msg in inbox folder.
The following below code:
public static void main(String[] args) {
String pstFileName = dataDir + "allen.pst";
// Load the Outlook PST file
PersonalStorage pst = PersonalStorage.fromFile(pstFileName);
// Get the folders and messages information
FolderInfo folderInfo = pst.getRootFolder();
// Create a folder for this PST
String strRootFolderName = "allen.pst".replace(".pst", "") + ".Java";
new File(dataDir + strRootFolderName).mkdir();
// Call the recursive method to extract msg files from each folder
extractMsgFiles(folderInfo, pst, dataDir + strRootFolderName);
}
private static void extractMsgFiles(FolderInfo folderInfo, PersonalStorage pst, String strPSTFile) {
// Display the folder name
System.out.println("Folder: " + folderInfo.getDisplayName());
// Create folder to store the messages
String folderName = strPSTFile + "\\" + folderInfo.getDisplayName();
new File(folderName).mkdir();
// Loop through all the messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.getContents();
for (int i = 0; i < messageInfoCollection.size(); i++) {
MessageInfo messageInfo = (MessageInfo) messageInfoCollection.get_Item(i);
System.out.println("Saving message " + messageInfo.getSubject() + "....");
// Get the message in MapiMessage instance
MapiMessage message = pst.extractMessage(messageInfo);
// Delete special characters which are invalid to use as windows file name
String messageName = null;
if (message.getSubject() == null || message.getSubject().isEmpty() == true) {
messageName = getRidOfIllegalFileNameCharacters(messageInfo.getEntryIdString());
} else {
messageName = getRidOfIllegalFileNameCharacters(message.getSubject());
}
// Save this message to disk in MSG format
message.save(folderName + "\\" + messageName + ".msg");
}
// Call this method recursively for each subfolder
if (folderInfo.hasSubFolders() == true) {
for (int i = 0; i < folderInfo.getSubFolders().size(); i++) {
FolderInfo subfolderInfo = (FolderInfo) folderInfo.getSubFolders().get_Item(i);
extractMsgFiles(subfolderInfo, pst, strPSTFile);
}
}
}
Help me... Where did i make mistake ? I am new in Aspose.
Please have a look at the following code snippet for extracting message files. You may use this method in place of your extractMsgFiles method.
private static void ExtractMsgFiles(FolderInfo folderInfo, PersonalStorage pst)
{
// display the folder name
Console.WriteLine("Folder: " + folderInfo.DisplayName);
Console.WriteLine("==================================");
// loop through all the messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.GetContents();
foreach (MessageInfo messageInfo in messageInfoCollection)
{
Console.WriteLine("Saving message {0} ....", messageInfo.Subject);
// get the message in MapiMessage instance
MapiMessage message = pst.ExtractMessage(messageInfo);
// save this message to disk in msg format
message.Save(message.Subject.Replace(":", " ") + ".msg");
// save this message to stream in msg format
MemoryStream messageStream = new MemoryStream();
message.Save(messageStream);
}
// Call this method recursively for each subfolder
if (folderInfo.HasSubFolders == true)
{
foreach (FolderInfo subfolderInfo in folderInfo.GetSubFolders())
{
ExtractMsgFiles(subfolderInfo, pst);
}
}
}
You may visit the link Working with Messages in a PST File in case you are interested in more details.
I work with Aspose as Developer evangelist.
The emails not having unique subject names could be causing this issue? I had this exact issue when doing something similar in Powershell. Putting an autonumber in the filename could help get around this.
I am trying to fetch fb user's "friend list" and his/her "about" but when i do i am getting null value of certain field like i comment below.
System.out.println(loginUser.getId()); //show id
System.out.println(loginUser.getName()); //Show Name
System.out.println(loginUser.getFirstName()); //show null
System.out.println(loginUser.getGender()); //show null
System.out.println(loginUser.getAbout()); //show null
I've been trying the graph-api explorer to see what I'm getting for gender
Its shows here
Code:
String code = request.getParameter("code");
String URLEncodedRedirectURI = URLEncoder.encode("http://localhost:8080/bitspedia-fetchfbfriends/FriendsListServlet");
String MY_ACCESS_TOKEN = "";
String authURL = "https://graph.facebook.com/oauth/access_token?" +
"client_id=" + FriendsListServlet.APP_ID + "&" +
"redirect_uri=" + URLEncodedRedirectURI + "&" +
"client_secret=" + FriendsListServlet.APP_SECRET + "&" +
"code=" + code;
URL url = new URL(authURL);
String result = readURL(url);
String[] pairs = result.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
if (kv[0].equals("access_token")) {
MY_ACCESS_TOKEN = kv[1];
}
}
FacebookClient facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN, FriendsListServlet.APP_SECRET);
Connection<User> friends = null;
try {
User loginUser = facebookClient.fetchObject("me", User.class);
request.setAttribute("loginUser", loginUser);
friends = facebookClient.fetchConnection("/me/friends", User.class);
System.out.println(loginUser.getId()); //shows id
System.out.println(loginUser.getName()); //Shows name
System.out.println(loginUser.getFirstName()); //shows null
System.out.println(loginUser.getWebsite()); //shows null
System.out.println(loginUser.getAbout()); //shows null
} catch (FacebookException e) {
e.printStackTrace();
}
List<User> friendsList = friends.getData();
It has very small issue, you didn't provide parameter of null showing value so doing small changes it works fine.
User loginUser = facebookClient.fetchObject("me", `Parameter.with("fields","first_name,last_name,posts")););`
I want to get value from control oid from LDAP: For example when I use Linux ldapsearch:
ldapsearch -H ldap://host:port -x -wsecret -D "cn=manager,managedElementId=HSS1"
-b "dn" "objectClass=ConfigOAM" -E"1.3.6.1.4.1.637.81.2.10.10"
I get results:
...
**control: 1.3.6.1.4.1.637.81.2.10.10 false AgEB**
objectClass: top
objectClass: ConfigOAM
confOAMId: 1
...
My java code looks:
LDAPConnection connection = new LDAPConnection();
connection.connect(hostName, port);
connection.bind(LDAPConnection.LDAP_V3, userDN, password);
String returnedAttributes[] = {"+", "*"};
boolean attributeOnly = false;
String oid;
LDAPSearchResults results = connection.search("", LDAPConnection.SCOPE_BASE, "(objectClass=*)", returnedAttributes, attributeOnly);
LDAPEntry entry = results.next();
System.out.println("\n" + entry.getDN());
System.out.println(" Attributes: ");
LDAPAttributeSet attributeSet = entry.getAttributeSet();
Iterator allAttributes = attributeSet.iterator();
while(allAttributes.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute)allAttributes.next();
String attrName = attribute.getName();
System.out.println(" " + attrName);
Enumeration allValues = attribute.getStringValues();
while(allValues.hasMoreElements()) {
oid = (String) allValues.nextElement();
if ( (attrName.equalsIgnoreCase("supportedExtension")) || (attrName.equalsIgnoreCase("supportedControl"))) {
System.out.println(" " + oid);
}
}
}
and the result is:
...
supportedControl
2.16.840.1.113730.3.4.2
1.2.840.113556.1.4.319
1.2.826.0.1.3344810.2.3
1.3.6.1.1.12
1.3.6.1.4.1.637.81.2.10.11
**1.3.6.1.4.1.637.81.2.10.10**
1.3.6.1.4.1.637.81.2.10.9
1.3.6.1.4.1.637.81.2.10.6
...
Please suggest me or advice how can I get the additional value "false AgEB" in java as I get it in ldapsearch?
You would need to add the control to the search request and be able to interpret the response.
There are soem examples available:
http://www.novell.com/documentation/developer/samplecode/jldap_sample/
-jim
Thank you for your answer :)
I made something like this from samples available on this site and from others soruces:
lc.connect( ldapHost, ldapPort );
lc.bind( ldapVersion, loginDN, password.getBytes("UTF8"));
LDAPControl ldapCtrl = new LDAPControl("1.3.6.1.4.1.637.81.2.10.10", false, null);
LDAPSearchConstraints cons = lc.getSearchConstraints();
cons.setControls( ldapCtrl );
lc.setConstraints(cons);
LDAPSearchResults searchResults = lc.search("",LDAPConnection.SCOPE_BASE, "(objectclass=*)", returnedAttributes,attributeOnly , cons);
LDAPControl[] controls = searchResults.getResponseControls();
but my "controls" varaible is always null, even if supportedControls are listed
LDAPEntry entry1 = searchResults.next();
System.out.println("\n" + entry1.getDN());
System.out.println(" Attributes: ");
LDAPAttributeSet attributeSet1 = entry1.getAttributeSet();
Iterator allAttributes1 = attributeSet1.iterator();
while(allAttributes1.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute)allAttributes1.next();
String attrName = attribute.getName();
System.out.println(" " + attrName);
Enumeration allValues1 = attribute.getStringValues();
while(allValues1.hasMoreElements()) {
oid = (String) allValues1.nextElement();
if ( (attrName.equalsIgnoreCase("supportedExtension")) || (attrName.equalsIgnoreCase("supportedControl"))) {
System.out.println(" " + oid);
}
}
}
Maybe the searchResults options are wrong?