I am trying to read a url which is throwing a string. I am storing that string in some variable and trying to print that variable on my web page using jsp. When I print my string on my web page it is giving some junk characters. How can I get the original string?
Here is my jsp code:
Market.jsp
<%#page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
URL url;
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
List commodity1 = null;
List price1 = null;
int c, p = 0;
try {
// get URL content
String a = "http://122.160.81.37:8080/mandim/MarketWise?m=agra";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
// sb.append(inputLine);
String s = inputLine.replace("|", "\n");
s = s.replace("~", " ");
StringTokenizer str = new StringTokenizer(s);
while (str.hasMoreTokens())
{
String mandi = str.nextElement().toString();
String price = str.nextElement().toString();
list1.add(mandi);
list2.add(price);
}
}
commodity1 = list1.subList(0, 10);
// commodity10=list1.subList(90,100);
price1 = list2.subList(0, 10);
int c1 = 0;
int p1 = 0;
for (c1 = 0, p1 = 0; c1 < commodity1.size() && p1 < price1.size(); c1++, p1++) {
String x = (String) commodity1.get(c1);
String y = (String) price1.get(p1);
out.println(x);
out.println(y);
}
br.close();
//System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
%>
</body>
</html>
I am getting the following output
धान 1325 चावल 2050 ज�वर 920 जौ 810 मकई 1280 गेहू� 1420 जो 1050 बेजर - जय 800 उड़द 3600
How can I achieve my desired goal?
Thanks in advance
I think it'a an encoding issue on your system. I don't know JSP enough to tell you what, but when running your code as a pure java application on linux and changing out.println(); into System.out.println(); I can see the output as expected. (side node: the product names are asian names, so don't be as surprised as I was. expected in this case means that the characters are the same as when I do a wget call to the URL).
This means: your code is fine: It loads what you want. The problem is the presentation. HTML pages have their own encoding. I guess JSP makes this transparently (-> here I need external input how to do this), but the result must have one of this three solutions:
your page has a western encoding, and is not able to support asian characters. In this case your strings need to be encoded like this: ℘ or ℘
your page is utf8 or unicode encoded and directly supports this characters
even on utf8 encoded pages you can use encodings like in the first example
Whatever you chose to use: your output must match the format. This also means that your code needs to know the selected character set. And I'm sure JSP does. If you want to use the default implemented encoding, you need to find a function for this. have a look to Escape all strings in JSP/Spring MVC. This cannot be too hard.
Only if you are really crazy but don't know how to do it, use something like this (it's a hack!) function to encode your string:
private String encode(String str) {
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray())
if (ch < 128)
sb.append(ch);
else {
sb.append("&#x");
String hx = Integer.toHexString(ch);
while (hx.length() < 4)
hx = "0" + hx;
sb.append(hx);
sb.append(";");
}
return sb.toString();
}
Related
I want modify html file for convert this to pdf.
Currently I convert an html file to pdf using "ITextRenderer".
Currently:
OutputStream out = new FileOutputStream(htmlFileOutPutPath);
//Flying Saucer
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(htmlFilePath);
renderer.layout();
renderer.createPDF(out);
out.close();
//This success!! html file to pdf generated!
1- but more later I have the need to modify the html file before generating it as pdf, for this I think extract html file content and convert to string, then I replace some text on string html:
public String htmlFileToString() throws IOException {
StringBuilder contentBuilder = new StringBuilder();
String path = "C:/Users/User1/Desktop/to_pdf_replace.html";
BufferedReader in = new BufferedReader(new FileReader(path));
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
in.close();
String content = contentBuilder.toString();
return content;
}
2- Then Replace tags in string from html
public String replaceHTMLcontent(String strSource)
{
String name = "Ana";
String age = "23";
String html = strSource;
strSource = strSource.replace("##Name##", name);
strSource = strSource.replace("##Age##", age);
//## ## -> are my html custom tags to replace
return strSource;
}
MAIN:
public static void main(String[] args) {
String stringFromHtml = new DocumentBLL().htmlFileToString();
String stringFromHtmlReplaced = new DocumentBLL().replaceHTMLcontent(stringFromHtml );
}
But now I do not know how to replace the new string with the old html string of the html file
You can first convert the whole html file into a string and do
String.replace("What I want to replace", "What it will be replaced with.");
Or if say you want to replace text1 and it's in a specific line, you can iterate through the file line by line (will be read as string) and look if there's text1 and implement the code I used above.
In addition, you can use this
BufferedReader file = new BufferedReader(new FileReader("myFile.html"));
String line;
StringBuffer buffer = new StringBuffer();
while (line = file.readLine()) {
buffer.append(line);
buffer.append('\n');
}
String input = buffer.toString();
file.close();
input = input.replace("What I want to insert into", "What I (hi there) want to insert into");
FileOutputStream out = new FileOutputStream("myFile.html");
out.write(inputStr.getBytes());
out.close();
I am using this inside of a minecraft mod to read and write file and all the leading space are being converted to ? in the file.
file input sample:
{
"ReturnToStart": "1b",
file out put sample:
{
???"ReturnToStart": "1b",
//xxxxxxxxxxxxxxxxxxxxxxx
var ips = new java.io.FileInputStream("ABC.json");
var fileReader = new java.io.InputStreamReader(ips,"UTF-8");
var data1 = fileReader.read();
var data;
var start1 = "";
while(data1 != -1) {
data = String.fromCharCode(data1);
start1 = start1+data;
data1 = fileReader.read();
}
fileReader.close();
var fileWriter = new java.io.FileWriter("J_out2.txt");
fileWriter.write(start1);
fileWriter.close();
It looks like you are using Nashorn in Java 8. Basically that is JavaScript running in a Java VM with access to all Java objects. I don't think those are normal spaces, and I suspect these are non breaking spaces (with code 160). It would be interesting to see what the value of data1 is at these positions.
The JavaScript method String.fromCharCode doesn't convert UTF-8 codes properly in Nashorn. Actually this will never work because in UTF-8 a single character can be split over multiple characters, and the value that comes back from read is limited to 16 bits. Not enough.
Below is probably what you need. I have included but commented the start1 variable because you may want to use that in your code, but is not needed.
var fileReader = new java.io.InputStreamReader(
new java.io.FileInputStream("ABC.json"), "UTF-8");
var bufferedReader = new java.io.BufferedReader(fileReader);
var fileWriter = new java.io.OutputStreamWriter(
new java.io.FileOutputStream("J_out2.txt"),"UTF-8");
var line;
// var start1=new java.lang.StringBuilder();
while(line=bufferedReader.readLine()) {
// start1.append(line);
// start1.append('\n');
fileWriter.write(line);
fileWriter.write('\n');
}
fileWriter.close();
bufferedReader.close();
var ips = new java.io.FileReader("ABC.json");
var data1 = ips.read();
var data;
var start1 = "";
while(data1 != -1) {
data = String.fromCharCode(data1);
if (data1 ==11 ||data1 ==12 || data1 ==10) {
data1 = ips.read();
continue;
}
//npc.say(data1+" "+ data);
data = String.fromCharCode(data1);
start1 = start1+data;
data1 = ips.read();
}
ips.close();
npc.say(start1);
Well I took out line feed, vertical tab, and form feed (10,11,12) and it works.
i want to create license system in java.
I created function to check if license is true.
My code:
private static boolean isPurchased(String license)
{
try
{
URL url = new URL("http://mineverse.pl/haslicense.php?license=" + license);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = in.readLine();
in.close();
return Boolean.valueOf(str);
} catch (Exception e)
{
e.printStackTrace();
}
return false;
}
and chceck function onenable
if(this.isPurchased(license)){
String license = cfg.getString("Licensing_System.License");
System.out.println("Licencja" + license + " kupiona! Dziekujemy!");
System.out.println(this.isPurchased(license));
}else {
System.out.println("Licencja zostala sfalszowana! Zglaszam to do serwera autoryzacji!");
}
And my link:
http://mineverse.pl/haslicense.php?license=diverse12345
as you can see this link return true, (i did echo 'true';) but java console always return false (i want true because website have true at this link) and it logs:
Licencja zostala sfalszowana! Zglaszam to do serwera autoryzacji!
Whats wrong? How can i return true on my website to allow java learn this boolean?>
That's because your server is not just returning True or False. It is returning this instead:
<html>
</html>
True
and your code is only reading the first line <html> and parsing it as a boolean, which results in false.
To fix it, either read the whole body looking for True/False or return just True/False on your body.
The following code should work with the current html even if it contains the <html> tags:
URL url = new URL("http://mineverse.pl/haslicense.php?license=" + license);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = null;
boolean ret = false;
while ((str = in.readLine()) != null) {
str = str.toLowerCase();
if (str.contains("true")) {
ret = true;
break;
}
}
in.close();
return ret;
I tried your link http://mineverse.pl/haslicense.php?license=diverse12345 and it returns this:
<html>
</html>
True
When you pass that to Boolean.valueOf(...), the result will be false. The method Boolean.valueOf(...) will only return true if the string you pass it consists of exactly four characters: true.
You need to get rid of the HTML tags, the spaces and newlines, and case is also important; True will not work, it must be true.
Hi I am trying to set jsp variable into a javascript array. I tried, but I am not able to achieve this when I run my code. I do not get my output, I only see a blank screen.
Here is my code:
value.jsp
<script>
<%
URL url;
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
List commodity = null;
List pric = null;
int c = 0;
int p = 0;
try {
// get URL content
String a = "http://122.160.81.37:8080/mandic/commoditywise?c=paddy";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null)
{
System.out.println(inputLine);
// sb.append(inputLine);
String s=inputLine.replace("|", "\n");
s = s.replace("~"," ");
StringTokenizer str = new StringTokenizer(s);
while(str.hasMoreTokens())
{
String mandi = str.nextElement().toString();
String price = str.nextElement().toString();
list1.add(mandi);
list2.add(price);
}
}
commodity = list1.subList(0,10);
pric = list2.subList(0,10);
for (c = 0,p = 0; c < commodity.size()&& p<pric.size(); c++,p++)
{
String x = (String)commodity.get(c);
String y = (String)pric.get(p);
//out.println(y);
//out.println(x);}
%>
jQuery(function ($) {
var roles = [];
roles.push(<%= x%>)
roles.push(<%= y%>)
<%
}
%>
var counter = 0;
var $role = $('#role')
//repeat the passed function at the specified interval - it is in milliseconds
setInterval(function () {
//display the role and increment the counter to point to next role
$role.text(roles[counter++]);
//if it is the last role in the array point back to the first item
if (counter >= roles.length) {
counter = 0;
}
}, 400)
});
</script>
<%
br.close();
//System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
%>
How can I achieve my desired output?
When you output to JS from JSP, you have to make sure your output is valid JS.
Your current output will output a string with no quotes, which the JS interpreter will treat as JS code and not strings or arrays as you want.
In addition, you are producing 10 copies of the JS
jQuery(function ($) {
var roles = [];
roles.push(<%= x%>)
roles.push(<%= y%>)
and that function is never closed.
I would look for a decent JSON output library. That would simplify your life quite a bit here.
It looks like you are clearing the roles variable var roles = []; with each pass of the loop.
You might want to consider not posting the entire file, but pairing the example down to just the part you need help with.
You could also put the array into a JSON object and parse that in your javascript. That might be a cleaner implementation.
try enclosing the scriptlets with quotes like roles.push("<%= x%>") and also check the array initialization.
in my jsp application, i have called a web service from which i am getting data in json fromat as like below
code for getting json data is
String recv ="";
String recvbuff ="";
URL jsonpage = new URL("http://107.109.6.236:3000/api/tokens.json");
URLConnection urlcon = jsonpage.openConnection();
BufferedReader buffread = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
while ((recv = buffread.readLine()) != null)
recvbuff += recv;
buffread.close();
below is the recvbuff output.
[{"id":1,"session_id":"11611fba0cd57f2f0e62acf746d7f60b","link":"","created_at":"2013- 12-10T13:13:31.000Z","updated_at":"2013-12-10T13:13:31.000Z"},
{"id":2,"session_id":"848960680b00502fc3e4c9cf0652a5fe","link":"","created_at":"2013-12-10T13:13:31.000Z","updated_at":"2013-12-10T13:13:31.000Z"},
{"id":3,"session_id":"101155b2c4cef0034804ed9b6806422e","link":"","created_at":"2013-12-10T13:13:31.000Z","updated_at":"2013-12-10T13:13:31.000Z"},
{"id":4,"session_id":"ec1373a7bdd291f60266ab6f8445c23b","link":"","created_at":"2013-12-10T13:13:31.000Z","updated_at":"2013-12-10T13:13:31.000Z"},
{"id":5,"session_id":"3eb8b185f0cbd71ff004b30453c90f54","link":"","created_at":"2013-12-10T13:13:31.000Z","updated_at":"2013-12-10T13:13:31.000Z"}]
And i have a token_id like 3eb8b185f0cbd71ff004b30453c90f54 which will match with one of the session_id. If dont match with exact string it will redirect to error page.
For this i am using the following code.
if(recvbuff.contains(token_id)){
out.println("<br>Hello <b>"+token_id+"</b>! done");
}else{
response.sendRedirect(redirectURL);
}
How to get the exact match in jsp pages?
Try something like this(Write in scriplets as its a jsp page):
String ar = "[{\"id\":1,\"session_id\":\"11611fba0cd57f2f0e62acf746d7f60b\",\"link\":\"\",\"created_at\":\"2013- 12-10T13:13:31.000Z\",\"updated_at\":\"2013-12-10T13:13:31.000Z\"}, \n"
+ "{\"id\":2,\"session_id\":\"848960680b00502fc3e4c9cf0652a5fe\",\"link\":\"\",\"created_at\":\"2013-12-10T13:13:31.000Z\",\"updated_at\":\"2013-12-10T13:13:31.000Z\"},\n"
+ "{\"id\":3,\"session_id\":\"101155b2c4cef0034804ed9b6806422e\",\"link\":\"\",\"created_at\":\"2013-12-10T13:13:31.000Z\",\"updated_at\":\"2013-12-10T13:13:31.000Z\"},\n"
+ "{\"id\":4,\"session_id\":\"ec1373a7bdd291f60266ab6f8445c23b\",\"link\":\"\",\"created_at\":\"2013-12-10T13:13:31.000Z\",\"updated_at\":\"2013-12-10T13:13:31.000Z\"},\n"
+ "{\"id\":5,\"session_id\":\"3eb8b185f0cbd71ff004b30453c90f54\",\"link\":\"\",\"created_at\":\"2013-12-10T13:13:31.000Z\",\"updated_at\":\"2013-12-10T13:13:31.000Z\"}]";
String token_id = "3eb8b185f0cbd71ff004b30453c90f54";
JSONArray jsonArray = new JSONArray(ar);
boolean match_found = false;
o:
for (int i = 0; i < jsonArray.length(); i++) {
if (token_id.equals(jsonArray.getJSONObject(i).getString("session_id"))) {
match_found = true;
break o;
}
}
if(match_found == true)
{
response.sendRedirect("error.jsp");
}