Formatting a JSON-Like String Without External Library - java

How can I go about formatting this string to give me the "gs" value?
{"status":1,"gs":"a2fdee457d64cd48f399f1a9fea4a977","user_type_id":1,"uid":-980}
I have looked at many of the similar questions on stack overflow, however, most suggest to use an external library. I do not want to use an external library because I am using this for libgdx, and an external library will just create unnecessary complications.

If you know specifically that you are looking for the value after "gs", then you can simply do the following:
// String input = [string in your question];
input = input.substring(input.indexOf("\"gs\"") + "\"gs\"".length()); // we move past the ':'
input = input.substring(input.indexOf('"') + 1); // move past the first '"' after "gs"
String gs = input.substring(0, input.indexOf('"'));
And now gs contains the string a2fdee457d64cd48f399f1a9fea4a977.

Related

Create a function for File.separator using Pattern Matcher

A static analysis tool when running on my java project gives "Portability Flaw In File Separator" error and I need to fix it. In my code, I have fileUnsafe. I want to use a method to convert it into fileSafe (explained below).
// Case 1
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
Similarly for paths like -
// Case 2
//no platform independence, good for Unix systems
File fileUnsafe = new File("/tmp/abc.txt");
// platform independent and safe to use across Unix and Windows
File fileSafe = new File(File.separator+"tmp"+File.separator+"abc.txt");
I have multiple of these file addresses throughout my project and I need to create some conversion method that could just take in this path as a string, append File.separator to it, and return it. Something like this -
File fileSafe = new File(someConversionMethod("/tmp/abc.txt"));
I tried this method but it gives me NullPointerException on case 2.
public static String someConversionMethod(String target) {
Pattern ptr = Pattern.compile("[\\\\\\\\|/]+");
Matcher mtr = ptr.matcher(target);
return mtr.replaceAll(File.separator + "" + File.separator);
}
Any help either fixing this method or suggesting a graceful way to handle this situation would be appreciated.
nit - I referred to Replacing character with File.separator using java.regex Pattern Matcher but it didn't really help my case.
I would try splitting the string at the file separator into an array like so.
String str = "/tmp/abc.txt";
String result = "";
String rgx = "\\\\|/";
String [] arrOfStr = str.split(rgx);;
Then you can add your File.separator back in using a for loop. Like this:
for (int i = 1; i < arrOfStr.length ; i++)
result += File.separator + arrOfStr[i];
I start from index one because the first slash gets doubled in the resulting string.
Since this is a one time change, you could use the regex find and replace in Eclipse
For the first case:
use Regex: ^File\sfileUnsafe\s=\snew File\(\"(?<folder1>[^\/]+)\/(?<fileName>[^\.]+)(?<extension>\.\w{3})\"\);
Replace with: File fileSafe = new File("${folder1}"+File.separator+"${fileName}${extension}");
Demo
For the second case:
use Regex: ^File\sfileUnsafe\s=\snew File\(\"\/(?<folder1>[^\/]+)\/(?<fileName>[^\.]+)(?<extension>\.\w{3})\"\);
Replace with: File fileSafe = new File(File.separator+"${folder1}"+File.separator+"${fileName}${extension}");
Demo
if you have more than one folder, you could continue this pattern and fix them.
I admit, this is not a clean straight forward way, but will get the job done.

How to get only filename without .mp3 and .mp4 extension in android?

I have audio and video names like this :
- azan1(1).mp3
- Funny.mp4
So I need an only AudioName as azan and VideoName as Funny. I am newbie in android and don't know how can I get only filename? How can I achieve this in code.??
Try this way to get filename without extension:-
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
In Java , simple and efficient way to get the filename
String resultName= filename.split("\\.")[0].split("\\(")[0];
As mentioned by 44kksharma, you can split the String at the . to get the extension. The only problem as I can see is if the file name contains . elsewhere (for an instance filename.test.mp3) - the file is an mp3 but one could argue filename.test is a part of the file name. If you think of it like that, this is the right approach using splitting:
String resultName = filename.split("\\.mp")[0];
If you have other extensions, you can do this:
String resultName = filename.split("\\.mp|\\.wav|\\.otherformat")[0];
mp3 and mp4 with have mp in them, therefore files with either extension is guaranteed to have .mp.
Using | is or in regex.
Alternatively, you can use the replaceAll method:
String result = filename.replaceAll("\\.mp3|\\.mp4", "");
replace works too, but as it doesn't use regex I find it ends up replacing the wrong chars or ends up screwing up the replacement.
Finally, you could use substring too, but using one-liners is possible with regex(/non-regex using replace) with split(), replace() and replaceAll()
if(audioname.contions(.mp3)
{
String audiostr= audioname.replace(".mp3", "");
}
if(videoname.contions(.mp4)
{
String videostr= videoname.replace(".mp3", "");
}
Set the String in your required textview

Crawling & parsing results of querying google-like search engine

I have to write parser in Java (my first html parser by this way). For now I'm using jsoup library and I think it is very good solution for my problem.
Main goal is to get some information from Google Scholar (h-index, numbers of publications, years of scientific carier). I know how to parse html with 10 people, like this:
http://scholar.google.pl/citations?mauthors=Cracow+University+of+Economics&hl=pl&view_op=search_authors
for( Element element : htmlDoc.select("a[href*=/citations?user") ){
if( element.hasText() ) {
String findUrl = element.absUrl("href");
pagesToVisit.add(findUrl);
}
}
BUT I need to find information about all of scientists from asked university. How to do that? I was thinking about getting url from button, which is guiding us to next 10 results, like that:
Elements elem = htmlDoc.getElementsByClass("gs_btnPR");
String nextUrl = elem.attr("onclick");
But I get url like that:
citations?view_op\x3dsearch_authors\x26hl\x3dpl\x26oe\x3dLatin2\x26mauthors\x3dAGH+University+of+Science+and+Technology\x26after_author\x3dslQKAC78__8J\x26astart\x3d10
I have to translate \x signs and add that site to my "toVisit" sites? Or it is a better idea inside jsoup library or mayby in other library? Please let me know! I don't have any other idea, how to parse something like this...
I have to translate \x signs and add that site to my "toVisit" sites...I don't have any other idea, how to parse something like this...
The \xAA is hexadecimal encoded ascii. For instance \x3d is =, and \x26 is &. These values can be converted using Integer.parseInt with radix set to 16.
char c = (char)Integer.parseInt("\\x3d", 16);
System.out.println(c);
If you need to decode these values without a 3rd party library, you can do so using regular expressions. For example, using the String supplied in your question:
String st = "citations?view_op\\x3dsearch_authors\\x26hl\\x3dpl\\x26oe\\x3dLatin2\\x26mauthors\\x3dAGH+University+of+Science+and+Technology\\x26after_author\\x3dslQKAC78__8J\\x26astart\\x3d10";
System.out.println("Before Decoding: " + st);
Pattern p = Pattern.compile("\\\\x([0-9A-Fa-f]{2})");
Matcher m = p.matcher(st);
while ( m.find() ){
String c = Character.toString((char)Integer.parseInt(m.group(1), 16));
st = st.replaceAll("\\" + m.group(0), c);
m = p.matcher("After Decoding: " + st);//optional, but added for clarity as st has changed
}
System.out.println(st);
You currently get a URL like this using your code:
citations?view_op\x3dsearch_authors\x26hl\x3dpl\x26oe\x3dLatin2\x26mauthors\x3dAGH+University+of+Science+and+Technology\x26after_author\x3dQPQwAJz___8J\x26astart\x3d10
You have to extract that bold part (using a regex), and use that to construct the URL for getting the next page of search results, which looks like this:
scholar.google.pl/citations?view_op=search_authors&hl=plmauthors=Cracow+University+of+Economic&after_author=QPQwAJz___8J
You can then get that next page from this URL and parse using Jsoup, and repeat for getting all the next remaining pages.
Will put together some example code later.

Concatenating to a file name before the ‘.’ Filename extension in Java

I can’t seem to find a way of concatenating to a file name before the “.” extension in Java and I’m not entirely sure how I would go about this.
I have already tried:
String s = r + "V1";
Where the variable r contains the value of myFile.txt and the output is: myFile.txtV1, but what I need to achieve is myFileV1.txt as I don’t want to overwrite the existing file with the same name but concatenate the V1 before the . filename extension when the file is written.
Thanks
In case file name can contain more then one dot like foo.bar.txt you should find index of last dot (String#lastIndexOf(char) can be useful here).
To get file name without extension (foo.bar part) substring(int, int) full file name from index 0 till index of that last dot.
To get extension (.txt part from last dot till the end of string) substring(int) from last dot index.
So your code can look like:
int lastDotIndex = r.lastIndexOf('.');
String s = r.substring(0, lastDotIndex ) + "V1" + r.substring(lastDotIndex);
Another approach is to use Apache Commons IO's FilenameUtils class to get the file's base name and extension.
import org.apache.commons.io.FilenameUtils;
...
File file = ...
String filename = file.getName();
String base = FilenameUtils.removeExtension(filename);
String extension = FilenameUtils.getExtension(filename);
String result = base + "-something-here" + "." + extension;
Look at String.indexOf() and String.substring() to split the string up and rebuild your updated version.
Try this (assuming that you have only one '.' in the name of your file):
String[] x = r.split("\\.");
String s = x[0]+"V1."+x[1];
Another apache commons method based on StringUtils.substringBeforeLast() and StringUtils.substringAfterLast:
String newPath = StringUtils.substringBeforeLast(filePath, ".") +
"_updated." + StringUtils.substringAfterLast(filePath, ".");
NB: You still need to check if the file actually contains the dot character or otherwise the result won't be consistent.
String s = r.substring(0,r.indexOf(".")) + "V1" + r.substring(a.indexOf("."));
Reminder that extensions are technically platform specific. Also, you probably want to have separate variables for the name and extension and combine them together at the end. Last caveat is that this code will not work if there are multiple period symbols in the filename (e.g. hello.world.txt)

How to change the width and height of an html file using java

I wanted to change width="xyz" , where (xyz) can be any particular value to width="300". I researched on regular expressions and this was the one I am using a syntax with regular expression
String holder = "width=\"340\"";
String replacer="width=\"[0-9]*\"";
theWeb.replaceAll(replacer,holder);
where theWeb is the string
. But this was not getting replaced. Any help would be appreciated.
Your regex is correct. One thing you might be forgetting is that in Java all string methods do not affect the current string - they only return a new string with the appropriate transformation. Try this instead:
String replacement = 'width="340"';
String regex = 'width="[0-9]*"';
String newWeb = theWeb.replaceAll(regex, replacement); // newWeb holds new text
Better use JSoup for manipulating and extracting data, etc. from Html
See this link for more details:
http://jsoup.org/

Categories