How to "split" in J2ME a String data containing new line characters? - java

I want to call a PHP webservice from my J2ME program. Here is the PHP function called :
...
$req="SELECT DISTINCT a.adc_id FROM adc a INNER JOIN utilisateur u ON a.adc_id=u.adc_id INNER JOIN transfert t ON u.user_code = t.user_code
WHERE t.user_code ='". $user_code ."' AND t.date_transfert='".$datejour."'";
$query=mysql_query($req) ;
while($ligne = mysql_fetch_array($query))
{
$chaine .=$ligne['adc_id'].';';
$chaine .= "\r\n" ;
}
return $chaine;
As you see there is the "\r\n" new-line character returned by the webservice among the column data. For example the returned String is :
12011;Michael;12/12/2012;
13455;Sue;14/05/2011;
So how to "split" this String data in J2ME so that I will get an array String[] containing the values :
12011;Michael;12/12/2012; and 13455;Sue;14/05/2011; ?

You will either have to write your own tokenizer or use one of the many available on the net.
One example could be this one from nokia's page
Usage example:
Tokenizer t = new Tokenizer(yourString, "\r\n");
while (t.hasMoreTokens()) {
String token = t.nextToken();
//do something with token
}

Related

Update JWT token field using numbus library

I have a Signed JWT token and I need to update an existing field, let's call it userName. I'm using NIMBUS + JOSE and. I figured out how to parse it and extract the claims:
SignedJWT.parse(token)
but parsing is not the only thing i need: I have update the field and reassemble its token back. Is there an easy way or any kind of idiomatic solution that will work without recreating the token from scratch.
I spend some time trying to figure out how to modify JWT token using the library.
And I used a quick and dirty solution:
// Split token into parts (parts are separated with '.'
final String[] tokenParts = token.split("\\.");
// decode payload part
final String decodedPayload =
new String(Base64.getDecoder().decode(tokenParts[1]), "UTF-8");
// enrich payload with additional userName field by adding it to the end of
// JSON. Remove the last character which is '}' and append data as String
final String updatedDecodedPayload =
decodedPayload.substring(0, decodedPayload.length() - 1)
+ ",\"userName\":\"" + "Richard" + "\"}";
// update payload with userId field and encode it back to base64
tokenParts[1] = Base64.getEncoder().encodeToString(
updatedDecodedPayload.getBytes()
);
final String updatedToken = String.join(".", tokenParts));

Java regex for google maps url?

I want to parse all google map links inside a String. The format is as follows :
1st example
https://www.google.com/maps/place/white+house/#38.8976763,-77.0387185,17z/data=!3m1!4b1!4m5!3m4!1s0x89b7b7bcdecbb1df:0x715969d86d0b76bf!8m2!3d38.8976763!4d-77.0365298
https://www.google.com/maps/place/white+house/#38.8976763,-77.0387185,17z
https://www.google.com/maps/place//#38.8976763,-77.0387185,17z
https://maps.google.com/maps/place//#38.8976763,-77.0387185,17z
https://www.google.com/maps/place/#38.8976763,-77.0387185,17z
https://google.com/maps/place/#38.8976763,-77.0387185,17z
http://google.com/maps/place/#38.8976763,-77.0387185,17z
https://www.google.com.tw/maps/place/#38.8976763,-77.0387185,17z
These are all valid google map URLs (linking to White House)
Here is what I tried
String gmapLinkRegex = "(http|https)://(www\\.)?google\\.com(\\.\\w*)?/maps/(place/.*)?#(.*z)[^ ]*";
Pattern patternGmapLink = Pattern.compile(gmapLinkRegex , Pattern.CASE_INSENSITIVE);
Matcher m = patternGmapLink.matcher(s);
while (m.find()) {
logger.info("group0 = {}" , m.group(0));
String place = m.group(4);
place = StringUtils.stripEnd(place , "/"); // remove tailing '/'
place = StringUtils.stripStart(place , "place/"); // remove header 'place/'
logger.info("place = '{}'" , place);
String latLngZ = m.group(5);
logger.info("latLngZ = '{}'" , latLngZ);
}
It works in simple situation , but still buggy ...
for example
It need post-process to grab optional place information
And it cannot extract one line with two urls such as :
s = "https://www.google.com/maps/place//#38.8976763,-77.0387185,17z " +
" and http://google.com/maps/place/#38.8976763,-77.0387185,17z";
It should be two urls , but the regex matches the whole line ...
The points :
The whole URL should be matched in group(0) (including the tailing data part in 1st example),
in the 1st example , if the zoom level : 17z is removed , it is still a valid gmap URL , but my regex cannot match it.
Easier to extract optional place info
Lat / Lng extraction is must , zoom level is optional.
Able to parse multiple urls in one line
Able to process maps.google.com(.xx)/maps , I tried (www|maps\.)? but seems still buggy
Any suggestion to improve this regex ? Thanks a lot !
The dot-asterisk
.*
will always allow anything to the end of the last url.
You need "tighter" regexes, which match a single URL but not several with anything in between.
The "[^ ]*" might include the next URL if it is separated by something other than " ", which includes line break, tab, shift-space...
I propose (sorry, not tested on java), to use "anything but #" and "digit, minus, comma or dot" and "optional special string followed by tailored charset, many times".
"(http|https)://(www\.)?google\.com(\.\w*)?/maps/(place/[^#]*)?#([0123456789\.,-]*z)(\/data=[\!:\.\-0123456789abcdefmsx]+)?"
I tested the one above on a perl-regex compatible engine (np++).
Please adapt yourself, if I guessed anything wrong. The explicit list of digits can probably be replaced by "\d", I tried to minimise assumptions on regex flavor.
In order to match "URL" or "URL and URL", please use a variable storing the regex, then do "(URL and )*URL", replacing "URL" with regex var. (Asuming this is possible in java.) If the question is how to then retrieve the multiple matches: That is java, I cannot help. Let me know and I delete this answer, not to provoke deserved downvotes ;-)
(Edited to catch the data part in, previously not seen, first example, first line; and the multi URLs in one line.)
I wrote this regex to validate google maps links:
"(http:|https:)?\\/\\/(www\\.)?(maps.)?google\\.[a-z.]+\\/maps/?([\\?]|place/*[^#]*)?/*#?(ll=)?(q=)?(([\\?=]?[a-zA-Z]*[+]?)*/?#{0,1})?([0-9]{1,3}\\.[0-9]+(,|&[a-zA-Z]+=)-?[0-9]{1,3}\\.[0-9]+(,?[0-9]+(z|m))?)?(\\/?data=[\\!:\\.\\-0123456789abcdefmsx]+)?"
I tested with the following list of google maps links:
String location1 = "http://www.google.com/maps/place/21.01196755,105.86306012";
String location2 = "https://www.google.com.tw/maps/place/#38.8976763,-77.0387185,17z";
String location3 = "http://www.google.com/maps/place/21.01196755,105.86306012";
String location4 = "https://www.google.com/maps/place/white+house/#38.8976763,-77.0387185,17z/data=!3m1!4b1!4m5!3m4!1s0x89b7b7bcdecbb1df:0x715969d86d0b76bf!8m2!3d38.8976763!4d-77.0365298";
String location5 = "https://www.google.com/maps/place/white+house/#38.8976763,-77.0387185,17z";
String location6 = "https://www.google.com/maps/place//#38.8976763,-77.0387185,17z";
String location7 = "https://maps.google.com/maps/place//#38.8976763,-77.0387185,17z";
String location8 = "https://www.google.com/maps/place/#38.8976763,-77.0387185,17z";
String location9 = "https://google.com/maps/place/#38.8976763,-77.0387185,17z";
String location10 = "http://google.com/maps/place/#38.8976763,-77.0387185,17z";
String location11 = "https://www.google.com/maps/place/#/data=!4m2!3m1!1s0x3135abf74b040853:0x6ff9dfeb960ec979";
String location12 = "https://maps.google.com/maps?q=New+York,+NY,+USA&hl=no&sll=19.808054,-63.720703&sspn=54.337928,93.076172&oq=n&hnear=New+York&t=m&z=10";
String location13 = "https://www.google.com/maps";
String location14 = "https://www.google.fr/maps";
String location15 = "https://google.fr/maps";
String location16 = "http://google.fr/maps";
String location17 = "https://www.google.de/maps";
String location18 = "https://www.google.com/maps?ll=37.0625,-95.677068&spn=45.197878,93.076172&t=h&z=4";
String location19 = "https://www.google.de/maps?ll=37.0625,-95.677068&spn=45.197878,93.076172&t=h&z=4";
String location20 = "https://www.google.com/maps?ll=37.0625,-95.677068&spn=45.197878,93.076172&t=h&z=4&layer=t&lci=com.panoramio.all,com.google.webcams,weather";
String location21 = "https://www.google.com/maps?ll=37.370157,0.615234&spn=45.047033,93.076172&t=m&z=4&layer=t";
String location22 = "https://www.google.com/maps?ll=37.0625,-95.677068&spn=45.197878,93.076172&t=h&z=4";
String location23 = "https://www.google.de/maps?ll=37.0625,-95.677068&spn=45.197878,93.076172&t=h&z=4";
String location24 = "https://www.google.com/maps?ll=37.0625,-95.677068&spn=45.197878,93.076172&t=h&z=4&layer=t&lci=com.panoramio.all,com.google.webcams,weather";
String location25 = "https://www.google.com/maps?ll=37.370157,0.615234&spn=45.047033,93.076172&t=m&z=4&layer=t";
String location26 = "http://www.google.com/maps/place/21.01196755,105.86306012";
String location27 = "http://google.com/maps/bylatlng?lat=21.01196022&lng=105.86298748";
String location28 = "https://www.google.com/maps/place/C%C3%B4ng+vi%C3%AAn+Th%E1%BB%91ng+Nh%E1%BA%A5t,+354A+%C4%90%C6%B0%E1%BB%9Dng+L%C3%AA+Du%E1%BA%A9n,+L%C3%AA+%C4%90%E1%BA%A1i+H%C3%A0nh,+%C4%90%E1%BB%91ng+%C4%90a,+H%C3%A0+N%E1%BB%99i+100000,+Vi%E1%BB%87t+Nam/#21.0121535,105.8443773,13z/data=!4m2!3m1!1s0x3135ab8ee6df247f:0xe6183d662696d2e9";

Get all HTTP url from a webpage

I am creating a simple utility to retrieve all HTTP URL's from a webpage.
Initially I had planned to use a HTML parsing library to parse out the HREF tags but I got to know that I need to retrieve the URL contained inside the script too (Example script below) hence I started trying out regular expression to get all the HTTP url from the web page but for some reason my regular expression is not working properly.
The URL can be inside a javascript
<script>
if(jQuery.browser.msie)
{
var v= 'http://test.com/test/test';
}
</script>
My program:
try {
BufferedReader in=new BufferedReader(new FileReader("c:\\sample\\sample.html"));
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
String pattern = "http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(inputLine.replaceAll("http://", "\nhttp://"));
while (!m.hitEnd()) {
if (m.find()) {
System.out.println("Found value: " + m.group(0));
} else {
//System.out.println("NO MATCH");
}
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Can someone help me fix this issue or let me know the best way to retrieve all URL's from a web page?
Description
Your expression has a typo. It should make the s optional.
https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?
^
Also I recommend:
replacing the (...) capture groups with non capture groups like (?:...)
you don't need to escape a . inside a character group [.]
add a test to ensure you're not captureing the close quotes surrounding your url
rewrite your section looking for /folder/subfolder sections as a repeating non-capture group looking for the initial slash followed by the folder name
regex: https?:\/\/(?:[\w-]+.)+(?::\d+)?(?:\/[\w\/_.]*)*?(?:\?\S+)?(?=['"\s])
as a Java string: "https?:\\/\\/(?:[\\w-]+.)+(?::\\d+)?(?:\\/[\\w\\/_.]*)*?(?:\\?\\S+)?(?=['\"\\s])"
Example
Live Demo
Sample Text
<script>
if(jQuery.browser.msie)
{
var v= 'http://test.com/test/test';
}
</script>
<a class="test" href="http://blablablablabla.com">Third Link</a>
Matches
[0] => http://test.com/test/test
[1] => http://blablablablabla.com
try using this
\A'http:\/\/[\w\W]+'\z
this will check that your url must be starting from http:// and is an string in starting and ending and as in between the url nowadys anything can come so we will have to allow special character like ?:,-_/\ and also the numbers digits etc.
so this will get you all the urls present in the file.

java explode a line/string like php explode

I'm making a java program that would run on a local server.
Server takes request from client using PHP .
<?php
$file = fopen('temp.txt', 'a+');
$a=explode(':',$_GET['content']);
fwrite($file,$a[0].':'.$a[1]. '\n');
fclose($file);
?>
Now I have file "temp.txt" on local server.
Java Program should open the file read line by line and each like should be divided/exploded ":" (In a line there's only one ':' )
I have tried in many ways, but could not get exactly like how PHP splits the line.
Is it possible to use same/similar explode function in JAVA.
Yes, in Java you can use the String#split(String regex) method in order to split the value of a String object.
Update:
For example:
String arr = "name:password";
String[] split = arr.split(":");
System.out.println("Name = " + split[0]);
System.out.println("Password = " + split[1]);
You can use String.split in Java to "explode" each line with ":".
Edit
Example for a single line:
String line = "one:two:three";
String[] words = line.split(":");
for (String word: words) {
System.out.println(word);
}
Output:
one
two
three

Quote retweets Twitter4j

I have a problem when using twitter4j, when I get timeline using this code :
try {
ResponseList<Status> tweets = twitter.getHomeTimeline();
for(Status s : tweets){
Tweet temp = new Tweet(new URL(s.getUser().getProfileImageURL()),s.getUser().getName(),"#"+s.getUser().getScreenName() , s.getText());
tweetsPanel.add(temp);
}
} catch (TwitterException | MalformedURLException e) {
e.printStackTrace();
}
(Tweet is local class) everything is OK except the retweets in the timeline are displayed as "Quote Retweet":
RT #SOMEONE : the tweet.
I want it like the website, just a normal retweet.
on twitter4j the retweets are shown in format
RT #user : tweet
because is the actual form a rt takes in text. If you put on twitter a tweet with this same format it will be parsed as a normal retweet from twitter itself.
the only way you can edit this out is to parse the text and eliminate the first part manually.
try something like:
String tweetText = "";
String [] splitted=s.getText().split(":");
if(splitted.lenght>2)
for (int i=1;i<splitted.lenght-1;i++)
{
tweetText+=splitted[i]+":";
}
tweetText+=splitted[splitted.lenght-1];
return tweetText;
by starting the for on i=1 you will avoid adding the first split that contains the RT #user, by adding the splitted[i]+":" you will put back eventual other ":" present in the tweet that split will otherwise eliminate. Of course you don't want to introduce a ":" that was not there, so the last piece of splitted goes outside the for, without the +":"

Categories