com.google.code.gson cannot parse tamil results - java

So, I'm trying to fetch JSON results from https://api-thirukkural.vercel.app/api?num=1139 using Java-Telegram-Bot-Api and send it to telegram. I use com.google.code.gson dependency for parsing JSON.
The expected results from API:
{"number":1139,"sect_tam":"காமத்துப்பால்","chapgrp_tam":"களவியல்","chap_tam":"நாணுத் துறவுரைத்தல்","line1":"அறிகிலார் எல்லாரும் என்றேஎன் காமம்","line2":"மறுகின் மறுகும் மருண்டு.","tam_exp":"என்னைத் தவிர யாரும் அறியவில்லை என்பதற்காக என் காதல் தெருவில் பரவி மயங்கித் திரிகின்றது போலும்!","sect_eng":"Love","chapgrp_eng":"The Pre-marital love","chap_eng":"Declaration of Love's special Excellence","eng":"My perplexed love roves public street Believing that none knows its secret","eng_exp":"And thus, in public ways, perturbed will rove"}
Here is a piece of my java code:
String results = "";
Random random = new Random();
SendMessage message = new SendMessage();
String apiUrl = "https://api-thirukkural.vercel.app/api?num=" + random.nextInt(1329 + 1);
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
Scanner sc = new Scanner(url.openStream());
while (sc.hasNext()) {
results += sc.nextLine();
}
sc.close();
JSONArray jsonArray = new JSONArray("[" + results + "]");
JSONObject object = jsonArray.getJSONObject(0);
message.setChatId(update.getMessage().getChatId().toString());
message.setText("Number: " + object.getInt("number") + "\n\n" + object.getString("line1") + "\n"
+ object.getString("line2") + "\n\n" + object.getString("tam_exp") + "\n\n" + object.getString("eng_exp"));
conn.disconnect();
execute(message);
} catch (Exception e) {
e.printStackTrace();
}
The result in telegram:
Number: 1139
அறிகிலார� எல�லார�ம� என�றேஎன� காமம�
மற�கின� மற�க�ம� மர�ண�ட�.
என�னைத� தவிர யார�ம� அறியவில�லை என�பதற�காக என� காதல� தெர�வில� பரவி மயங�கித� திரிகின�றத� போல�ம�!
And thus, in public ways, perturbed will rove
Is this a problem in gson dependency? Can someone help me fix this? Thanks.

You need to specify the Charset on Scanner. That is probably the problem.
Example:
new Scanner(url.openStream(), StandardCharsets.UTF_8.name());
You should use the Charset that fits.

Related

Win32Exception: The parameter is incorrect

I am making an application that displays ur saved browser password(s) (right now I'm using Google Chrome) in an easy way. Everytime I run this code I get an error at byte[] newbyte = Crypt32Util.cryptUnprotectData(mybyte);. The code used is written below. This code provides some context. I never had this problem and after some research I can't find a clear solution. I hope someone can help me with it.
Code:
Connection connection = null;
connection = DriverManager.getConnection("jdbc:sqlite:" + path_to_copied_db);
PreparedStatement statement = connection.prepareStatement("SELECT `origin_url`,`username_value`,`password_value` FROM `logins`");
ResultSet re = statement.executeQuery();
StringBuilder builder = new StringBuilder();
while (re.next()) {
String pass = "";
try {
byte[] mybyte = (byte[])re.getBytes("password_value");
byte[] newbyte = Crypt32Util.cryptUnprotectData(mybyte); //Error on this line:71
pass = new String(newbyte);
}catch(Win32Exception e){
e.printStackTrace();
}
builder.append(user + ": " + re.getString("origin_url") + " " + re.getString("username_value") + " " + re.getBinaryStream("password_value") + "\n");
}
Error:
com.sun.jna.platform.win32.Win32Exception: The parameter is incorrect.
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:128)
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:103)
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:90)
at Client.Client.main(Client.java:71)

Issue load webpage after basic auth android

I need to load webpage after basic auth, but the sessionid in my code is not concatenated to url (I get this 10-08 10:17:27.424 20143-20143/com.example.marco.bella D/WebView: loadUrl=https://unimol.esse3.cineca.it/auth/Logon.do;jsessionid=
)...i don't know why...i show you my code!
variable cookie get the correct sessionID.
Thanks in advance!
URL url = null;
try {
url = new URL("https://unimol.esse3.cineca.it/auth/Logon.do");
} catch (MalformedURLException e) {
}
HttpURLConnection httpRequest = null;
try {
httpRequest = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
httpRequest.setRequestMethod("GET");
} catch (ProtocolException e) {
}
String cookie = "";
httpRequest.setDoInput(true);
String authString = "user" + ":" + "pass";
byte[] authEncBytes = android.util.Base64.encode(authString.getBytes(), android.util.Base64.DEFAULT);
String authStringEnc = new String(authEncBytes);
httpRequest.addRequestProperty("Authorization", "Basic " + authStringEnc);
System.out.println("auth:" + "" + authStringEnc);
DefaultHttpClient httpclient = new DefaultHttpClient();
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
cookie=cookies.get(i).toString();
}
}
webView.loadUrl("https://unimol.esse3.cineca.it/auth/Logon.do;jsessionid="+cookie);
(I get this 10-08 10:17:27.424 20143-20143/com.example.marco.bella
D/WebView:
loadUrl=https://unimol.esse3.cineca.it/auth/Logon.do;jsessionid= )...i
don't know why
The problem I can think of by looking only the portion you have posted here is that you are Overriding cookie variable inside your for loop and there is a high possibility on any iteration of cookies, one or more than 1 cookie exist whose value is blank.
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
cookie=cookies.get(i).toString(); // This line is the culprit
}
You should check if the value of the cookie is null or empty.
Replace the culprit line with below line
I am using a utility of Strings class (isNullOrEmpty) of Guava library to check if value is null or empty, you can use your own implementation for this,
if(Strings.isNullOrEmpty(cookies.get(i).toString())) {
continue;
} else {
cookie=cookies.get(i).toString();
}
Now if during iteration you get id which you confirmed that you are getting in console statement then it will definitely get loaded up.

Get specific parts of a string that contains garbage data

So I have these strings that I'm getting that contains a lot of garbage data which i don't want
"http://v20.lscache8.c.youtube.com/videoplayback?id=271de9756065677e&itag=17&ip=0.0.0.0&ipbits=0&expire=999999999999999999"&sparams=ip,ipbits,expireip,ipbits,expire,id,itag&signature=3DCD3F79E045F95B6AF661765F046FB0440FF01606A42661B3AF6BAF046F012549CC9BA34EBC80A9"
So basicly I just want it to search trough the string for videoplayback?id=
*and just copy whats between videoplayback?id= and &
271de9756065677e
and then continue to go trough the string and Grab the signature in the same way
So anyone can help me with the logic and examples how to do this ?
Since your "string that contains garbage data" is actually a URL you should use the URL class
Have a look at the tutorial Parsing a URL
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
String url = "http://v20.lscache8.c.youtube.com/videoplayback?id=271de9756065677e&itag=17&ip=0.0.0.0&ipbits=0&expire=999999999999999999"&sparams=ip,ipbits,expireip,ipbits,expire,id,itag&signature=3DCD3F79E045F95B6AF661765F046FB0440FF01606A42661B3AF6BAF046F012549CC9BA34EBC80A9";
URL aURL = new URL(url);
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
}
}
The output should be:
protocol = http
authority = v20.lscache8.c.youtube.com:80
host = v20.lscache8.c.youtube.com
port = 80
path = /videoplayback
query = id=271de9756065677e&itag=17&ip=0.0.0.0&ipbits=0&expire=999999999999999999"&sparams=ip,ipbits,expireip,ipbits,expire,id,itag&signature=3DCD3F79E045F95B6AF661765F046FB0440FF01606A42661B3AF6BAF046F012549CC9BA34EBC80A9
In order to parse the query, use URLEncodedUtils
String url = "http://v20.lscache8.c.youtube.com/videoplayback?id=271de9756065677e&itag=17&ip=0.0.0.0&ipbits=0&expire=999999999999999999"&sparams=ip,ipbits,expireip,ipbits,expire,id,itag&signature=3DCD3F79E045F95B6AF661765F046FB0440FF01606A42661B3AF6BAF046F012549CC9BA34EBC80A9";
List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");
for (NameValuePair param : params) {
System.out.println(param.getName() + "=" + param.getValue());
}
The output should be:
id=271de9756065677e
itag=17
ip=0.0.0.0
ipbits=0
expire=999999999999999999"
sparams=ip,ipbits,expireip,ipbits,expire,id,itag
signature=3DCD3F79E045F95B6AF661765F046FB0440FF01606A42661B3AF6BAF046F012549CC9BA34EBC80A9

How to parse this URL in java

I have a URL like this
http://my.my.info/action/doning/something?mailParams=iCgGugAIdMW3CqkYbZ/dGYVqljerVjzbKLvTQCyuosHzxisIrgYf8rcKqRhtn90Z0eVGZ+vx43P4g+umFmddNdDufWv/nDwbCgqBwHs9OYVd5g4VKuFO4jTfF1NiW+KjUi3JubtJT+0F7p+wPHEpTRwJJ+O0eevojx6DioK3cLGejz5UdfIrqzOVNT05TaPKFie4yZxbXfA=
I need it in key value pair not as a query string.
my out put should be
mailParams = iCgGugAIdMW3CqkYbZ/dGYVqljerVjzbKLvTQCyuosHzxisIrgYf8rcKqRhtn90Z0eVGZ+vx43P4g+umFmddNdDufWv/nDwbCgqBwHs9OYVd5g4VKuFO4jTfF1NiW+KjUi3JubtJT+0F7p+wPHEpTRwJJ+O0eevojx6DioK3cLGejz5UdfIrqzOVNT05TaPKFie4yZxbXfA=
i could not parse this string since the above is encoded. I have used URLEncodedUtils to parse this but it returns
mailParams = iCgGugAIdMW3CqkYbZ/dGYVqljerVjzbKLvTQCyuosHzxisIrgYf8rcKqRhtn90Z0eVGZ vx43P4g umFmddNdDufWv/nDwbCgqBwHs9OYVd5g4VKuFO4jTfF1NiW KjUi3JubtJT 0F7p wPHEpTRwJJ O0eevojx6DioK3cLGejz5UdfIrqzOVNT05TaPKFie4yZxbXfA
which is not at all relevant can some one help me to do this?
Try using java.net.URL
A sample code below.
URL aURL = new URL("http://my.my.info/action/doning/something?mailParams=iCgGugAIdMW3CqkYbZ/dGYVqljerVjzbKLvTQCyuosHzxisIrgYf8rcKqRhtn90Z0eVGZ+vx43P4g+umFmddNdDufWv/nDwbCgqBwHs9OYVd5g4VKuFO4jTfF1NiW+KjUi3JubtJT+0F7p+wPHEpTRwJJ+O0eevojx6DioK3cLGejz5UdfIrqzOVNT05TaPKFie4yZxbXfA=");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
If need to split the link to get the parameters
use String#split which takes the regex as a arguments
String link="http://my.my.info/action/doning/something?mailParams=iCgGugAIdMW3CqkYbZ/dGYVqljerVjzbKLvTQCyuosHzxisIrgYf8rcKqRhtn90Z0eVGZ+vx43P4g+umFmddNdDufWv/nDwbCgqBwHs9OYVd5g4VKuFO4jTfF1NiW+KjUi3JubtJT+0F7p+wPHEpTRwJJ+O0eevojx6DioK3cLGejz5UdfIrqzOVNT05TaPKFie4yZxbXfA=";
String[] mailparams=link.split("\\?");
System.out.print(mailparams[1]);
You can also
Use URL#getQuery
String link="http://my.my.info/action/doning/something?mailParams=iCgGugAIdMW3CqkYbZ/dGYVqljerVjzbKLvTQCyuosHzxisIrgYf8rcKqRhtn90Z0eVGZ+vx43P4g+umFmddNdDufWv/nDwbCgqBwHs9OYVd5g4VKuFO4jTfF1NiW+KjUi3JubtJT+0F7p+wPHEpTRwJJ+O0eevojx6DioK3cLGejz5UdfIrqzOVNT05TaPKFie4yZxbXfA=";
URL aURL = new URL(link);
System.out.println( aURL.getQuery());
OUTPUT:
mailParams=iCgGugAIdMW3CqkYbZ/dGYVqljerVjzbKLvTQCyuosHzxisIrgYf8rcKqRhtn90Z0eVGZ+vx43P4g+umFmddNdDufWv/nDwbCgqBwHs9OYVd5g4VKuFO4jTfF1NiW+KjUi3JubtJT+0F7p+wPHEpTRwJJ+O0eevojx6DioK3cLGejz5UdfIrqzOVNT05TaPKFie4yZxbXfA=
URL aURL = null;
try {
aURL = new URL("http://my.my.info/action/doning/something?mailParams=iCgGugAIdMW3CqkYbZ/dGYVqljerVjzbKLvTQCyuosHzxisIrgYf8rcKqRhtn90Z0eVGZ+vx43P4g+umFmddNdDufWv/nDwbCgqBwHs9OYVd5g4VKuFO4jTfF1NiW+KjUi3JubtJT+0F7p+wPHEpTRwJJ+O0eevojx6DioK3cLGejz5UdfIrqzOVNT05TaPKFie4yZxbXfA=");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(aURL.getQuery());

Input formatted date and time in Swing to get nodes using GET REST

I am required to input start time and end time and in swing java that I will further send to a URL to get some selected nodes created in this time using GET REST call.
URL is:
http://wisekar.iitd.ernet.in/active/api_resources.php/method/mynode
?key=YOUR_API_KEY_HERE
&startTime=START_TIME[Optional]
&endTime=END_TIME[Optional]en
The website will take take the input (time stamps) as they are given in the image.
Screenshot Of my window
Now my code is here:
class Algorithm extends JFrame implements ActionListener {
private static String ENDPOINT =
"http://wisekar.iitd.ernet.in/active/api_"
+ "resources.php/method/mynode.json?key=api_key";
Algorithm() {
// label1 = new JLabel();.....
panel = new JPanel(new GridLayout(5, 2));
//adding in panel label1,text1 ...
add(panel, BorderLayout.CENTER);
SUBMIT.addActionListener(this);
setTitle("Optimal Travel Route");
}
public void actionPerformed(ActionEvent ae) {
try {
//String value1 = text1.getText();..
URL url = new URL(ENDPOINT + "&datasetId=" + value3
+ "&startTime=" + value1 + "&endTime=" + value2);
System.out.println(url);
HttpURLConnection httpCon;
httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoInput(true);
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(
httpCon.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
} catch (IOException ex) {
Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class AlgorithmDemo {
public static void main(String arg[]) {
try {
Algorithm frame = new Algorithm();
frame.setSize(450, 200);
frame.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
I have tried everything; I have commented it. Using this code, I am getting the nodes when I am typing the generated URL in the browser, but it is not giving the result on the console when I am printing. What is wrong in my code? Can someone tell me how should date and time should be passed to the GET. Please help. When I only input the data set ID, it gives me all the nodes of that data set ID. According to me, there is some problem in passing the time stamps.
Unfortunately when I ran a quick test I got an unauthorized response.
But it looks like the issue is the string is not url safe.
Yo need to ensure your spaces are converted to %20.
This will also be why it works using and browser as the browser address bar will do this for you behind the scenes.
If you use:
String urlSafeValue1 = URLEncoder.encode(value1, "UTF-8");
String urlSafeValue2 = URLEncoder.encode(value2, "UTF-8");
String urlSafeValue3 = URLEncoder.encode(value3, "UTF-8");
The arguments will be made url safe.
try this my friend ...
String httpURL = ENDPOINT + URLEncoder.encode("&datasetId=" + value3
+ "&startTime=" + value1 + "&endTime=" + value2, "UTF-8");
URLConnection urlConnection = new URL(httpURL).openConnection();
urlConnection.connect();
If your time stamps are on the format in the screenshot, they contain spaces which must be escaped in URLs. Try
value1 = value1.replaceAll(" ", "+");
and similarly for value2 before constructing the URL.

Categories

Resources