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
Related
The overall project is creating a system manager for airports. It keeps track of airports, flights, seating sections, seats and other relevent info for each of those catagories. The initial system is set up by importing from a file that's formatted a certain way. I'm having problems parsing the file properly to set up the initial system. the data is parsed from the file and used as method parameters to create the objects: Airport, Airline, Flight, FlightSection, and Seat.
the formatting is:
[list-of-airport-codes] {list-of-airlines}
list-of-airport-codes ::= comma-separated strings
list-of-airlines ::= airline-name1[flightinfo-list1], airline-name2[flightinfo-list2], airlinename3[flightinfo-list3], …
flightinfo-list ::= flightID1|flightdate1|originAirportCode1|destinationAirportCode1[flightsectionlist1], flightID2|flightdate2|originAirportCode2|destinationAirportCode2[flightsection-list2], …
flightdate ::= year, month, day-of-month, hours, minutes
flightsection-list ::= sectionclass: seat-price: layout: number-of-rows, …
sectionclass ::= F, B, E (for first class, business class, economy class)
layout ::= S, M, W (different known seating layouts)
example:
[DEN,NYC,SEA,LAX]{AMER[AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],
AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3], …], UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3], UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2], …], FRONT[…], USAIR[…]}
I tried brute forcing it using a combination of delimiters and while loops. The code successfully creates the Airports, first Airline and Flighsections, but when it gets to creating the second airline it crashes, because i'm not looping properly, and having a hard time getting it right. My code for it as of now, is a mess, and if you're willing to look at it, I would appreciate any constructive input. My question is what would be a better way to approach this? A different design approach? Maybe a smarter way to use the delimiters?
Thanks in advance for your help!!
here's what i've tried.
private void readFile(File file){
System.out.println("reading file");
Scanner tempScan;
String result;
String temp = "";
scan.useDelimiter("\\[|\\{");
try{
// AIRPORTS
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|\\]");
while(tempScan.hasNext()){
temp = tempScan.next();
sysMan.createAirport(temp);
}
tempScan.close();
/* AIRLINE
* FLIGHT
* FLIGHTSECTION
*/
do{
// AIRLINE (loop<flight & fsection>)
result = scan.next();
sysMan.createAirline(result);
// FLIGHT
result = scan.next();
tempScan = new Scanner(result);
do{
tempScan.useDelimiter(",|\\|");
ArrayList flightInfo = new ArrayList();
while(tempScan.hasNext()){
if(tempScan.hasNextInt()){
flightInfo.add(tempScan.nextInt());
} else {
flightInfo.add(tempScan.next());
}
}
tempScan.close();
sysMan.createFlight(sysMan.getLastAddedAirline(),(String)flightInfo.get(0), (int)flightInfo.get(1), (int)flightInfo.get(2), (int)flightInfo.get(3), (int)flightInfo.get(4), (int)flightInfo.get(5), (String)flightInfo.get(6), (String)flightInfo.get(7));
// FLIGHTSECTION (loop<itself>)
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|:|\\]");
ArrayList sectInfo = new ArrayList();
int i = 1;
while(!temp.contains("|")){
if(tempScan.hasNextInt()){
sectInfo.add(tempScan.nextInt());
} else {
temp = tempScan.next();
if(temp.equals(""))
break;
char c = temp.charAt(0);
sectInfo.add(c);
}
if(i == 4){
sysMan.createSection(sysMan.getLastAddedAirline(), sysMan.getLastAddedFlightID(), (char)sectInfo.get(0), (int)sectInfo.get(1), (char)sectInfo.get(2), (int)sectInfo.get(3));
i = 1;
sectInfo = null;
sectInfo = new ArrayList();
continue;
}
i++;
}
}while(!temp.equals("\\s+"));
}while(!temp.contains("\\s+"));
}catch(NullPointerException e){
System.err.println(e);
}
}
I'd rather chunk it down by regexp mathing the outer bounds, have a look, I took it a couple of levels broken.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tokeni {
static String yolo = "[DEN,NYC,SEA,LAX]{AMER["
+ "AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],"
+ "AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3]],"
+ "UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3],"
+ "UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2]]}";
public static void main(String[] args) {
Matcher airportCodesMatcher = Pattern.compile("\\[(.*?)\\]").matcher(yolo);
airportCodesMatcher.find();
String[] airportCodes = airportCodesMatcher.group(1).split(",");
Matcher airLinesMatcher = Pattern.compile("\\{(.*?)\\}").matcher(yolo);
airLinesMatcher.find();
String airLinesStr = airLinesMatcher.group(1);
System.out.println(airLinesStr);
Pattern airLinePattern = Pattern.compile("\\D+\\[(.*?)\\]\\]");
Matcher airLineMatcher = airLinePattern.matcher(airLinesStr);
while( airLineMatcher.find() ) {
String airLineStr = airLineMatcher.group(0).trim();
if(airLineStr.startsWith(",")) {
airLineStr = airLineStr.substring(1, airLineStr.length()).trim();
}
System.out.println(airLineStr);
Matcher airLineNameMatcher = Pattern.compile("[A-Z]+").matcher(airLineStr);
airLineNameMatcher.find();
String airLineName = airLineNameMatcher.group(0).trim();
System.out.println(airLineName);
airLineStr = airLineStr.substring(airLineStr.indexOf("[")+1, airLineStr.length());
Matcher airLineInfoMatcher = Pattern.compile("\\D+(.*?)\\]").matcher(airLineStr);
while(airLineInfoMatcher.find()) {
String airLineInfoStr = airLineInfoMatcher.group(0).trim();
if(airLineInfoStr.startsWith(",")) {
airLineInfoStr = airLineInfoStr.substring(1, airLineInfoStr.length()).trim();
}
System.out.println(airLineInfoStr);
}
}
}
}
I needed to pick specific parts of a very big string (that's being decoded from a QR code) to set as text in TextView elements in Android.
//*these are the parts of the string whose corresponding values I need as a text for my TextViews.*
String uid, name, gname, gender, house, street, ps, po, dist, subdist, state, pin, address, dob;
//*this 'string' object holds the decoded qr string*
String string = "uid="001" name="Akbar Shah" gender="M" yob="1989" gname="Jahangir Shah" co="S/O: Jahangir Shah" house="45/5" street="Huzurey Ala Street" vtc="Alibagh" po="Bagnan" dist="Faridabad" subdist="Alamgarh" state="Andhra" pc="6754674" dob="15/04/89"";
//*this is where I am using substring() to get a specific part of the string value*
uid = string.substring(string.indexOf("uid=")+5, string.indexOf("name=")-2);
name = string.substring(string.indexOf("name=")+6, string.indexOf("gender=")-2);
gname = string.substring(string.indexOf("gname=")+7, string.indexOf("co=")-2);
gender = string.substring(string.indexOf("gender=")+8, string.indexOf("yob=")-2);
house = string.substring(string.indexOf("house=")+7, string.indexOf("street=")-2);
street = string.substring(string.indexOf("street=")+8, string.indexOf("vtc=")-2);
ps = string.substring(string.indexOf("vtc=")+5, string.indexOf("po=")-2);
po = string.substring(string.indexOf("po=")+4, string.indexOf("dist=")-2);
dist = string.substring(string.indexOf("dist=")+6, string.indexOf("subdist=")-2);
subdist = string.substring(string.indexOf("subdist=")+9, string.indexOf("state=")-2);
state = string.substring(string.indexOf("state=")+7, string.indexOf("pc=")-2);
pin = string.substring(string.indexOf("pc=")+4, string.indexOf("dob=")-2);
dob = string.substring(string.indexOf("dob=")+5, string.indexOf("/>")-1);
//*this is where I have concatenated the whole address parts into one*
address = house+", "+street+", \nPS - "+ps+", \nPO - "+po+", \nDistrict - "+dist+", \nSub-Division - "+subdist+", \nState - "+state+", \nPin Code - "+pin;
TextView tv_uid, tv_name, tv_gName, tv_gender, tv_address, tv_dob;
//*this is where I then setText those substrings for appropriate TextViews*
tv_uid.setText(uid);
tv_name.setText(name);
tv_gName.setText(gname);
tv_gender.setText(gender);
tv_address.setText(address);
tv_dob.setText(dob);
The way I have done this can only work if the decoded QR string format remains the same, i.e. if the string decoded now is this:
String string = "uid="001" name="Akbar Shah" gender="M" yob="1989" gname="Jahangir Shah" co="S/O: Jahangir Shah" house="45/5" street="Huzurey Ala Street" vtc="Alibagh" po="Bagnan" dist="Faridabad" subdist="Alamgarh" state="Andhra" pc="6754674" dob="15/04/89"";
Then, my way of extracting won't work if the string looks something like this:
String string = "uid="002" name="Amar Tripathi" gender="M" yob="1990" vtc="Alibagh" po="Bagnan" dist="Faridabad" state="Andhra" pc="6754674" dob="15/04/89"";
Or, like this:
String string = "uid="003" name="Anthony Gonzalis" gender="M" yob="1985" gname="Jahangir Shah" house="45/5" street="Huzurey Ala Street" lm="Behind the Meat shop" loc="Galianwalabagh" vtc="Alibagh" dist="Faridabad" state="Andhra" pc="6754674" dob="15/04/89"";
As you may have already noticed, substring() cannot be used universally for all cases because the last two string values have some parts missing in them. So if I specify to extract a particular substring which is sandwiched between gname and co, except for the first case, in the last two cases it won't be able to find co and hence the execution of the code line return error.
Is there a better way to do it?
P.S. Can I just extract all the string parts from inside " "?
E.g. "001" is the part of the string from which I just want to get the 001 part which is inside the double quotes.
you could use a regex, for example "\w*="([^"]*(?="))". This checks the following:
\w* matches word-characters (like letters and numbers) until
= the '=' is reached which simply matches the character '=',
[^"]* first matches the^'"'-character (which represents the opening '"'-character) and then every character that is not '"' until
(?=") is reached which checks if the next character is an '"'-character (which represents the closing '"'-character)
Use this regex like so: myString.replace("\w*="([^"]*(?="))", "\1"). That will replace the whole Name="myName" with simply myName.
Hope this helps
First I created a DataAttributes class.
DataAttributes.java
public class DataAttributes {
// declare xml attributes of QR code xml response
public static final String
DATA_TAG = "PrintLetterBarcodeData",
UID_ATTR = "uid",
NAME_ATTR = "name",
GENDER_ATTR = "gender",
GNAME_ATTR = "gname",
HOUSE_ATTR = "house",
STREET_ATTR = "street",
LM_ATTR = "lm",
LOC_ATTR = "loc",
VTC_ATTR = "vtc",
PO_ATTR = "po",
DIST_ATTR = "dist",
SUBDIST_ATTR = "subdist",
STATE_ATTR = "state",
PC_ATTR = "pc",
DOB_ATTR = "dob";
}
After QR code is being scanned and stored in a string.
In your activity where you want to display the scanned data, in my case its QRActivity... so I made a method with single argument -> (String scanData) in QRActivity class in QRActivity.java
Inside which the following code is written
Log.d("QR Code",scanData);
XmlPullParserFactory pullParserFactory;
try {
// init the parserfactory
pullParserFactory = XmlPullParserFactory.newInstance();
// get the parser
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(new StringReader(scanData));
// parse the XML
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
Log.d("QR Code","Start document");
} else if(eventType == XmlPullParser.START_TAG && DataAttributes.DATA_TAG.equals(parser.getName())) {
// extract data from tag
//uid
uid = parser.getAttributeValue(null,DataAttributes.UID_ATTR);
//name
name = parser.getAttributeValue(null,DataAttributes.NAME_ATTR);
//gender
gender = parser.getAttributeValue(null,DataAttributes.GENDER_ATTR);
// guardian name
gname = parser.getAttributeValue(null,DataAttributes.GNAME_ATTR);
// house number
house = parser.getAttributeValue(null,DataAttributes.HOUSE_ATTR);
// Street name
street = parser.getAttributeValue(null,DataAttributes.STREET_ATTR);
// landmark
lm = parser.getAttributeValue(null,DataAttributes.LM_ATTR);
// locality
loc = parser.getAttributeValue(null,DataAttributes.LOC_ATTR);
// village town city
vtc = parser.getAttributeValue(null,DataAttributes.VTC_ATTR);
// Post Office
po = parser.getAttributeValue(null,DataAttributes.PO_ATTR);
// district
dist = parser.getAttributeValue(null,DataAttributes.DIST_ATTR);
// sub-division
subdist = parser.getAttributeValue(null,DataAttributes.SUBDIST_ATTR);
// state
state = parser.getAttributeValue(null,DataAttributes.STATE_ATTR);
// Post Code
pc = parser.getAttributeValue(null,DataAttributes.PC_ATTR);
// Date of Birth
dob = parser.getAttributeValue(null,DataAttributes.DOB_ATTR);
} else if(eventType == XmlPullParser.END_TAG) {
Log.d("QR Code","End tag "+parser.getName());
} else if(eventType == XmlPullParser.TEXT) {
Log.d("QR Code","Text "+parser.getText());
}
// update eventType
eventType = parser.next();
}
// display the data on screen
String na = "N/A";
if (uid == null){
tv_uid.setText(na);
}else {
tv_uid.setText(uid);
}
if (name == null){
tv_name.setText(na);
}else {
tv_name.setText(name);
}
if (gender == null){
tv_gender.setText(na);
}else {
tv_gender.setText(gender);
}
if (gname == null){
tv_gName.setText(na);
}else {
tv_gName.setText(gname);
}
if (house == null){
tv_house.setText(na);
}else {
tv_house.setText(house);
}
if (street == null){
tv_street.setText(na);
}else {
tv_street.setText(street);
}
if (lm == null){
tv_lm.setText(na);
}else {
tv_lm.setText(lm);
}
if (loc == null){
tv_loc.setText(na);
}else {
tv_loc.setText(loc);
}
if (vtc == null){
tv_vtc.setText(na);
}else {
tv_vtc.setText(vtc);
}
if (po == null){
tv_po.setText(na);
}else {
tv_po.setText(po);
}
if (dist == null){
tv_dist.setText(na);
}else {
tv_dist.setText(dist);
}
if (subdist == null){
tv_subdist.setText(na);
}else {
tv_subdist.setText(subdist);
}
if (state == null){
tv_state.setText(na);
}else {
tv_state.setText(state);
}
if (pc == null){
tv_pc.setText(na);
}else {
tv_pc.setText(pc);
}
if (dob == null){
tv_dob.setText(na);
}else {
tv_dob.setText(dob);
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The above code is a sample of how I used XMLPullParserFactory to fragment a string into appropriate pieces and then show them separately.
Now you use the method appropriate for your purpose in the Activity. I just showed my way of implementing the XMLPullParserFactory to split the string.
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.
I have a field that I am trying to set the length of 25 to by using StringBuilder and then populate it with string values in specific positions within that field. However, when I get a print out of the values in that field the value looks like this:
M0
Obviously I am needing to remove the "�" values from that field. Any help/direction would be appreciated.
Here is my code:
String b44 = toRequestIsoMessage.getString(B44_ADD_RESPONSE_DATA.bitId);
if (b44 == null) {
// ***** 20130604 MS - Told Ralph since that position 1 is space filled initially in the request to the CORE so that he can modify for the AVS. *****
String avsValue = " ";
try {
StringBuilder revB44Value = new StringBuilder();
revB44Value.setLength(25);
revB44Value.insert(0, avsValue);
if (decision.cidResponse.responseCode != null) {
revB44Value.insert(1, decision.cidResponse.responseCode);
} else {
revB44Value.insert(1, " ");
}
if (decision.cvvResponse.responseCode != null) {
revB44Value.insert(13, decision.cvvResponse.responseCode);
} else {
revB44Value.insert(13, " ");
}
String revB44 = revB44Value.toString();
toRequestIsoMessage.setString(B44_ADD_RESPONSE_DATA.bitId, revB44Value.toString());
} catch (InternalISOMsgException e) {
LOGGER.info(FormatData.fullStackTrace(e));
}
}
i have a list of url's i need to filter specific domain and subdomain. say i have some domains like
http://www.example.com
http://test.example.com
http://test2.example.com
I need to extract urls which from domain example.com.
Working on project that required me to determine if two URLs are from the same sub domain (even when there are nested domains). I worked up a modification from the guide above. This holds out pretty well thus far:
public static boolean isOneSubdomainOfTheOther(String a, String b) {
try {
URL first = new URL(a);
String firstHost = first.getHost();
firstHost = firstHost.startsWith("www.") ? firstHost.substring(4) : firstHost;
URL second = new URL(b);
String secondHost = second.getHost();
secondHost = secondHost.startsWith("www.") ? secondHost.substring(4) : secondHost;
/*
Test if one is a substring of the other
*/
if (firstHost.contains(secondHost) || secondHost.contains(firstHost)) {
String[] firstPieces = firstHost.split("\\.");
String[] secondPieces = secondHost.split("\\.");
String[] longerHost = {""};
String[] shorterHost = {""};
if (firstPieces.length >= secondPieces.length) {
longerHost = firstPieces;
shorterHost = secondPieces;
} else {
longerHost = secondPieces;
shorterHost = firstPieces;
}
//int longLength = longURL.length;
int minLength = shorterHost.length;
int i = 1;
/*
Compare from the tail of both host and work backwards
*/
while (minLength > 0) {
String tail1 = longerHost[longerHost.length - i];
String tail2 = shorterHost[shorterHost.length - i];
if (tail1.equalsIgnoreCase(tail2)) {
//move up one place to the left
minLength--;
} else {
//domains do not match
return false;
}
i++;
}
if (minLength == 0) //shorter host exhausted. Is a sub domain
return true;
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
return false;
}
Figure I'd leave it here for future reference of a similar problem.
I understand you are probably looking for a fancy solution using URL class or something but it is not required. Simply think of a way to extract "example.com" from each of the urls.
Note: example.com is essentially a different domain than say example.net. Thus extracting just "example" is technically the wrong thing to do.
We can divide a sample url say:
http://sub.example.com/page1.html
Step 1: Split the url with delimiter " / " to extract the part containing the domain.
Each such part may be looked at in form of the following blocks (which may be empty)
[www][subdomain][basedomain]
Step 2: Discard "www" (if present). We are left with [subdomain][basedomain]
Step 3: Split the string with delimiter " . "
Step 4: Find the total number of strings generated from the split. If there are 2 strings, both of them are the target domain (example and com). If there are >=3 strings, get the last 3 strings. If the length of last string is 3, then the last 2 strings comprise the domain (example and com). If the length of last string is 2, then the last 3 strings comprise the domain (example and co and uk)
I think this should do the trick (I do hope this wasn't a homework :D )
//You may clean this method to make it more optimum / better
private String getRootDomain(String url){
String[] domainKeys = url.split("/")[2].split("\\.");
int length = domainKeys.length;
int dummy = domainKeys[0].equals("www")?1:0;
if(length-dummy == 2)
return domainKeys[length-2] + "." + domainKeys[length-1];
else{
if(domainKeys[length-1].length == 2) {
return domainKeys[length-3] + "." + domainKeys[length-2] + "." + domainKeys[length-1];
}
else{
return domainKeys[length-2] + "." + domainKeys[length-1];
}
}
}