read IRC data correctly in Processing - java

I am trying to read IRC and pull data from individual IRC messages in Processing. You can see the code (also with twitter library, ignore that) and I need some pointers on how I can pull the data out in the format of Nick:Message so it can be displayed in a visualization.
//Twitter
import twitter4j.conf.*;
import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.api.*;
import java.util.*;
// Import the net libraries
import processing.net.*;
// Declare a client
Client client;
Twitter twitter;
String searchString = "god";
List<Status> tweets;
String server = "irc.twitch.tv";
String nick = "NugShow";
//String user = "simple_bot";
int port = 6667;
String channel = "#nugshow";
String password = "xx";
String in = "butt";
String checkFor;
//bools
Boolean isLive = false;
int privMsgIndex;
int atIndex;
String playerSubstring;
// The channel which the bot will joString channel = "#irchacks";
int currentTweet;
void setup()
{
size(800,600);
frameRate(60);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("xx");
cb.setOAuthConsumerSecret("xx");
cb.setOAuthAccessToken("xx");
cb.setOAuthAccessTokenSecret("xx");
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
getNewTweets();
currentTweet = 0;
thread("refreshTweets");
thread("loopChat");
connectToServer();
//IRC
}
void draw()
{
if (client.available() > 0) {
String in = client.readString();
println(in);
}
if (isLive == false){
if (client.available() > 0) {
}
} else {
}
/*
fill(0, 40);
rect(0, 0, width, height);
currentTweet = currentTweet + 1;
if (currentTweet >= tweets.size())
{
currentTweet = 0;
}
Status status = tweets.get(currentTweet);
fill(200);
text(status.getText(), random(width), random(height), 300, 200);
delay(100);
*/
}
void joinChannel() {
String in = client.readString();
client.write( "JOIN " + channel + "\n\r" );
client.clear();
in = client.readString();
println(in);
if (in != null){
//println("Recieved data");
println(in);
//String inString = myClient.readStringUntil("");
isLive = true;
println(isLive);
}
}
void connectToServer()
{
client = new Client(this, server , 6667);
client.write( "PASS " + password + "\n\r" );
println(password + " sent!");
client.write( "NICK " + nick + "\n\r" );
println(nick + " sent!");
joinChannel();
}
void getNewTweets()
{
try
{
Query query = new Query(searchString);
QueryResult result = twitter.search(query);
tweets = result.getTweets();
}
catch (TwitterException te)
{
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
void refreshTweets()
{
while (true)
{
getNewTweets();
println("Updated Tweets");
delay(30000);
}
}
void loopChat()
{
while (true)
{
if (privMsgIndex != 0){
println(privMsgIndex);
//privMsgIndex = privMsgIndex - 15;
atIndex = in.indexOf("#");
println(atIndex);
//atIndex = atIndex + 1;
playerSubstring = in.substring(atIndex, privMsgIndex);
println(playerSubstring);
} else {
println("looped");
}
delay(300);
client.clear();
in = null;
}
}
void keyPressed()
{
}
void tweet()
{
try
{
Status status = twitter.updateStatus("This is a tweet sent from Processing!");
System.out.println("Status updated to [" + status.getText() + "].");
}
catch (TwitterException te)
{
System.out.println("Error: "+ te.getMessage());
}
}
The chat commands look like this: :nugshow!nugshow#nugshow.testserver.local PRIVMSG #nugshow :dddd where nugshow is the username, #nugshow is the channel, and dddd is the message. I need to get it into the format of nugshow: dddd.
there is a lot of header information that I'm not sure how to strip out of client.recieved buffer as well, it looks like this:
:testserver.local 001 nugshow :Welcome, GLHF!
:testserver.local 002 nugshow :Your host is testserver.local
:testserver.local 003 nugshow :This server is rather new
:testserver.local 004 nugshow :-
:testserver.local 375 nugshow :-
:testserver.local 372 nugshow :You are in a maze of twisty passages, all alike.
:testserver.local 376 nugshow :>
:nugshow!nugshow#nugshow.testserver.local JOIN #nugshow
:nugshow.testserver.local 353 nugshow = #nugshow :nugshow
:nugshow.testserver.local 366 nugshow #nugshow :End of /NAMES list
:jtv!jtv#jtv.testserver.local PRIVMSG nugshow :HISTORYEND nugshow

I would not recommend regex here. At least not if you want to be able to catch all types of IRC messages. The key is to look at the message code to know what you can actually get out of the message. As I'm also writing an IRC-client (just for giggles) I have some notes for you.
Be sure to answer any PINGs that the server sends you so you don't get kicked off. As the PING is sent with an identifier, you need to catch that and send it back. A simple way to do this is to check the last line that was sent from the server and substring it.
String line = inputStream.readLine();
if(line.substring(0,4).equals("PING")){
send("PONG " + line.substring(5)); // Assume you have some send-function.
}
This will make sure you don't get kicked off and can proceed to actually stay on a server.
As I mentioned, I do not recommend using regex for this as it would become a RegEx-of-doom. So, what I have done is to just split the line you get and put all the results in a String array.
String[] arr = line.split(" ");
As you know by your own message line you have posted, the IRC protocol separates things with spaces. So splitting at spaces in not all that shabby (we'll get how to deal with actual text in a bit).
The basic structure that is always the same (as far as I can tell) in messages is PREFIX COMMAND PARAM PARAM/TRAILING. So what does this mean? The PREFIX is where the message was sent from. Example ":user!user#host.com". The COMMAND is what the line actually is. You are looking for PRIVMSG here, but there are many, many, others that you might want to take care of. Like JOIN, PART, QUIT, 332 (current topic), 353 (nicks in channel, 404 (unable to send to channel), etc. etc. The PARAM and PARAM/TRAILING will all depend on the COMMAND.
So, what do we gain from splitting at spaces? This:
arr[0] = :user!user#host.com
arr[1] = COMMAND
arr[2] = PARAM
arr[3 onwards] = rest
We can now easily manage every command in it's own needed way.
Without further delay, lets get to your actual question, the PRIVMSG.
I will use this string: ":Chewtoy!chewtoy#stackoverflow.com PRIVMSG #stackoverflow :Ty: I saw your question and thought I should give you an answer."
After doing a split at the spaces, we get the array
arr[0] = :Chewtoy!chewtoy#stackoverflow.com
arr[1] = PRIVMSG
arr[2] = #stackoverflow
arr[3] = :Ty:
arr[4] = I
arr[5] = saw
...
As you can see, everything from 3 and onwards is the message you want. 0-2 is stuff that you need to be able to know who sent what where. My code for getting all this looks like this:
String[] arr = receivedLine.split(" ");
if(arr[1].equals("PRIVMSG")){
String[] usr = arr[0].split(!"); // Get the user, which is in usr[0]. Host in usr[1]
StringBuilder msg = new StringBuilder();
for(int i=3; i<arr.length; i++){ // We know the message starts at arr[3], so start counting from that.
msg.append(arr[i] + " ");
}
String chan = "";
if(arr[2].substring(0,1).equals("#")){ // We need to differentiate between sending to channel and sending a PM. The only difference in this is where the text is sent.
chan = arr[2];
} else{
chan = usr[0].substring(1); // substring(1) because we want Chewtoy, not :Chewtoy
}
// The result here will be:
// <#stackoverflow> Chewtoy: Ty: I saw your question and thought I should give you an answer.
sendItAllToWhereYouWantIt("<" + chan +"> " + usr[0].substring(1) + ": " + msg.substring(1));
}
Hope that helps.

Related

error when get value from marketdataincremental refresh

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.

Extracting .pst file to msg but not getting exact number of msg file

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.

Concatenate SMS via SMPP

I'm having an issue where I can't send SMS more than 255 words. I did my research a bit on how to concatenate the messages but I still can't get it to work. Can somebody advise me on this? Below is my code:
private int SMSMt(String pstrLoginName, String pstrServiceID, String
pstrCPID, String pstrMSISDN, String pstrKeyword, String pstrPriceCode,
String pstrChargeMSISDN, String pstrSubID, String pstrDstTrxID, String
pstrShortCode, String pstrSMS, String pstrLanguage, SubmitResult pobjRst)
{
int intResult = 0;
try
{
if (!this.mobjSMPP.mblnBound)
{
intResult = 9910;
}
else
{
SubmitSM objReq = new SubmitSM();
Address objSrcAddress = new Address();
Address objDstAddress = new Address();
objSrcAddress.setNpi((byte)1);
objSrcAddress.setTon((byte)0);
objSrcAddress.setAddress(pstrShortCode);
objDstAddress.setNpi((byte)1);
objDstAddress.setTon((byte)0);
objDstAddress.setAddress(pstrMSISDN);
objReq.setServiceType("");
objReq.setSourceAddr(objSrcAddress);
objReq.setDestAddr(objDstAddress);
objReq.setReplaceIfPresentFlag((byte)0);
objReq.setScheduleDeliveryTime("");
objReq.setValidityPeriod("");
objReq.setPriorityFlag((byte)1);
objReq.setRegisteredDelivery((byte)1);
objReq.setUserMessageReference((short)25);
WriteLog("pstrLanguage=" + pstrLanguage);
if (pstrLanguage.equals("1")) {
objReq.setDataCoding((byte)8);
WriteLog("Ori pstrSMS=" + pstrSMS);
objReq.setShortMessage(pstrSMS,"UTF_16BE");
//String HexStr = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "\u0eaa" + "C");
//WriteLog("HexStr=" + HexStr);
//pstrSMS = stringToHex(pstrSMS);
//StringConverter TestRun = new StringConverter(pstrSMS);
/*pstrSMS = HexStr;*/
//pstrSMS = new String("\u0eaa");
//pstrSMS = new String("0x0eaa");
/*pstrSMS = "世界您好";
WriteLog("Ori pstrSMS=" + pstrSMS);
//byte[] messageData = new ASCIIEncoding().encode(pstrSMS);
byte[] b = s.getBytes(StandardCharsets.US_ASCII);*/
WriteLog("Ori pstrSMS [unicode]=" + pstrSMS);
//byte[] textByte = pstrSMS.getBytes("UTF-16BE");
//WriteLog("HexCode [encoded with UTF-16BE]= " + textByte);
//pstrSMS = textByte.toString(); //cannot convert byte[] to string
}
else {
objReq.setDataCoding((byte)0);
objReq.setShortMessage(pstrSMS);
}
Setting user reference (setUserMessageReference) is not enough. You must set also number of fragments and fragment number. Depending on library methods.
Also, you must split message to 255 chunks on hand.
So if you have message 400 bytes, then you do something like this:
First fragment:
setReference=25
numberOfFragments=2
fragmentNumber=1
message=first 255 bytes
Second fragment:
setReference=25
numberOfFragments=2
fragmentNumber=2
message=rest 145 bytes
Also note, that many SMSC vendors allow SMPP to be fragmented internally.
There are 2 parameters in SMPP to deal with message:
1)Message(mandatory) (limited to 255 bytes)
2)Payload message(optional) (not limited)

How to get IP address through www.ipaddresslocation.org in Blackberry

I'm a newbie in Blackberry programming.
I'm trying get IP address, County, city, state/province through www.ipaddressslocation.org
My source :
String url = "http://www.ipaddresslocation.org/my-ip-address.php";
// HTTP connection
HttpConnection httpConnection = null;
// Stream connection
StreamConnection streamConnection = (StreamConnection) Connector
.open(url);
httpConnection = (HttpConnection) streamConnection;
int code = httpConnection.getResponseCode();
String strContent = "";
// Check response code
if (code == HttpConnection.HTTP_OK) {
InputStream is = httpConnection.openInputStream();
int length = (int) httpConnection.getLength();
// Content is empty
if (length != -1) {
byte incomingData[] = new byte[length];
is.read(incomingData);
strContent = new String(incomingData);
// Write content
} else {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1) {
bytestream.write(ch);
}
strContent = new String(bytestream.toByteArray());
bytestream.close();
}
}
When was finished this method, I have got the strContent return .
Detail content:
\ndocument.write('<table><tr><td>Hello, visitor from: <strong> Takatsuki, Japan</strong>');document.write('<img src=\'http://www.ipaddresslocation.org/flags/jp.png\'></td></tr>');document.write('<tr><td>Your Country Code: <b>JP</b></td></tr>');document.write('<tr><td>Your IP State: <b>Osaka</b></td></tr>');document.write('<tr><td>Your IP Address: <b>202.213.220.66</b></td></tr>');document.write('<tr><td>Your Hostname: <b>ns.isb.co.jp</b></td></tr>');document.write('<tr><td>Your ISP: <b>So-net Entertainment Corporation</b></td></tr>');document.write('<tr><td>Your Organization: <b>ISB CORP.</b></td></tr></table>');
How can I get the IP , country, state, city from above content?
Thanks and best regards !
As there is no standard format i.e. JSON or XML you have to parse the response by yourself. To write your scraper just check the response format carefully and design your algorithm.
For example, the response look like the following if we split the response by ";"..
document.write('<table><tr><td>Hello, visitor from: <strong> Dhaka, Bangladesh</strong>')
document.write('<img src=\'http://www.ipaddresslocation.org/flags/bd.png\'></td></tr>')
document.write('<tr><td>Your Country Code: <b>BD</b></td></tr>')
document.write('<tr><td>Your IP State: <b>Dhaka</b></td></tr>')
document.write('<tr><td>Your IP Address: <b>116.212.105.42</b></td></tr>')
document.write('<tr><td>Your Hostname: <b>ws9-tetrasoft-dm-ac1-p16.telnet.com.bd</b></td></tr>')
document.write('<tr><td>Your ISP: <b>Telnet Communication Limited</b></td></tr>')
document.write('<tr><td>Your Organization: <b>Telnet Communication Limited</b></td></tr></table>')
Then you can remove "document.write('" and "')" from each line..
then the response will become
<table><tr><td>Hello, visitor from: <strong> Dhaka, Bangladesh</strong>
<img src=\'http://www.ipaddresslocation.org/flags/bd.png\'></td></tr>
<tr><td>Your Country Code: <b>BD</b></td></tr>
<tr><td>Your IP State: <b>Dhaka</b></td></tr>
<tr><td>Your IP Address: <b>116.212.105.42</b></td></tr>
<tr><td>Your Hostname: <b>ws9-tetrasoft-dm-ac1-p16.telnet.com.bd</b></td></tr>
<tr><td>Your ISP: <b>Telnet Communication Limited</b></td></tr>
<tr><td>Your Organization: <b>Telnet Communication Limited</b></td></tr></table>
Now you can use any HTML parser or parse the remaining by yourself...
just break the problem...
for example to get the IP address, you need to parse the 5th line..
remove all the characters from index 0 to the index of <b> + 3.... this will remove the portion "<tr><td>Your IP Address: <b>" from that line.....
then remove the characters from the index of </b> to the last... this will remove the "" from that line.. and you will get "116.212.105.42" as the remaining...
I think it is not possible to parse it but we can use logic to get data from that string
but format should same for ever
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class StartUp extends UiApplication{
public static void main(String[] args) {
StartUp start=new StartUp();
start.enterEventDispatcher();
}
public StartUp() {
pushScreen(new simple());
}
}
class simple extends MainScreen
{
LabelField labl;
public simple() {
String str="\ndocument.write('<table><tr><td>Hello, visitor from: <strong> Takatsuki, Japan</strong>');document.write('<img src=\'http://www.ipaddresslocation.org/flags/jp.png\'></td></tr>');document.write('<tr><td>Your Country Code: <b>JP</b></td></tr>');document.write('<tr><td>Your IP State: <b>Osaka</b></td></tr>');document.write('<tr><td>Your IP Address: <b>202.213.220.66</b></td></tr>');document.write('<tr><td>Your Hostname: <b>ns.isb.co.jp</b></td></tr>');document.write('<tr><td>Your ISP: <b>So-net Entertainment Corporation</b></td></tr>');document.write('<tr><td>Your Organization: <b>ISB CORP.</b></td></tr></table>');";
str=str.substring(str.indexOf("document.write"));
String arr[]=split(str, "document.write('");
String s="";
int len=arr.length;
for(int i=0;i<len;i++){
if(i==0){
s=arr[i];
if(s.indexOf("<strong>")!=-1 && s.indexOf("</strong>")!=-1 ){
int sx=s.indexOf("<strong>")+8;
int dx=s.indexOf("</strong>");
System.out.println(s.substring(sx,dx));
labl=new LabelField(s.substring(sx,dx));
add(labl);
}
}else if(i==1){
s=arr[i];
if(s.indexOf("img src='")!=-1 && s.indexOf("'>")!=-1 ){
int sx=s.indexOf("'")+1;
int dx=s.indexOf("'>");
System.out.println(s.substring(sx,dx));
labl=new LabelField(s.substring(sx,dx));
add(labl);
}
}
else{
if(arr[i].indexOf("<b>")!=-1 && arr[i].indexOf("</b>")!=-1 ){
int sx=arr[i].indexOf("<b>")+3;
int dx=arr[i].indexOf("</b>");
System.out.println(arr[i].substring(sx,dx));
labl=new LabelField(arr[i].substring(sx,dx));
add(labl);
}
}
}
}
public static String[] split(String strString, String strDelimiter)
{
int iOccurrences = 0;
int iIndexOfInnerString = 0;
int iIndexOfDelimiter = 0;
int iCounter = 0;
// Check for null input strings.
if (strString == null)
{
throw new NullPointerException("Input string cannot be null.");
}
// Check for null or empty delimiter
// strings.
if (strDelimiter.length() <= 0 || strDelimiter == null)
{
throw new NullPointerException("Delimeter cannot be null or empty.");
}
// If strString begins with delimiter
// then remove it in
// order
// to comply with the desired format.
if (strString.startsWith(strDelimiter))
{
strString = strString.substring(strDelimiter.length());
}
// If strString does not end with the
// delimiter then add it
// to the string in order to comply with
// the desired format.
if (!strString.endsWith(strDelimiter))
{
strString += strDelimiter;
}
// Count occurrences of the delimiter in
// the string.
// Occurrences should be the same amount
// of inner strings.
while((iIndexOfDelimiter= strString.indexOf(strDelimiter,iIndexOfInnerString))!=-1)
{
iOccurrences += 1;
iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
}
// Declare the array with the correct
// size.
String[] strArray = new String[iOccurrences];
// Reset the indices.
iIndexOfInnerString = 0;
iIndexOfDelimiter = 0;
// Walk across the string again and this
// time add the
// strings to the array.
while((iIndexOfDelimiter= strString.indexOf(strDelimiter,iIndexOfInnerString))!=-1)
{
// Add string to
// array.
strArray[iCounter] = strString.substring(iIndexOfInnerString, iIndexOfDelimiter);
// Increment the
// index to the next
// character after
// the next
// delimiter.
iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
// Inc the counter.
iCounter += 1;
}
return strArray;
}
}
you will get output as following image

Can anyone help with a java problem regarding record stores?

I have this code. And basically this returns the correct data without the town qualities. When I add the town qualities the method returns nothing, not even the orginal data that it has been and I dont know why. Can anyone see a problem?
protected void listRecords() {
mListForm.deleteAll(); // clear the form
try {
RecordStore rs = RecordStore.openRecordStore("Details", true);
RecordEnumeration re = rs.enumerateRecords(null, new RecordSorter(), false);
while (re.hasNextElement()) {
byte [] recordBuffer = re.nextRecord();
String record = new String(recordBuffer);
// extract the name and the age from the record
int endOfName = record.indexOf(";");
int endOfDesc = record.indexOf(";" , endOfName + 1);
int endOfTown = record.indexOf (";", endOfDesc + 1);
String name = record.substring(0, endOfName);
String desc = record.substring(endOfName + 1, endOfDesc);
String town = record.substring(endOfDesc +1, endOfTown);
mListForm.append(name + " aged: "+ desc + " " + town);
}
rs.closeRecordStore();
}
catch(Exception e){
mAlertConfirmDetailsSaved.setString("Couldn't read details");
System.err.println("Error accessing database");
}
mDisplay.setCurrent(mListForm);
}
Have you tried running it in the debugger? Is the exception happening? Are the three semicolons present in the record? Is there a limit on mDisplay's string size? When setCurrent is called, is the mListForm correct?
In other words, what have you done so far and where is it definitely right, and where does it become wrong?

Categories

Resources