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.
Related
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 am trying to get one chapter at a time of a book. I am using the Paul Seigmann library. However, I am not sure how to do it but I am able to get all the text from the book. Not sure where to go from there.
// find InputStream for book
InputStream epubInputStream = assetManager
.open("the_planet_mappers.epub");
// Load Book from inputStream
mThePlanetMappersBookEpubLib = (new EpubReader()).readEpub(epubInputStream);
Spine spine = new Spine(mThePlanetMappersBookEpubLib.getTableOfContents());
for (SpineReference bookSection : spine.getSpineReferences()) {
Resource res = bookSection.getResource();
try {
InputStream is = res.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = r.readLine()) != null) {
line = Html.fromHtml(line).toString();
Log.i("Read it ", line);
mEntireBook.append(line);
}
} catch (IOException e) {
}
I don't know if you're still looking for an answer, but...
I'm working on it too right now. This is the code I have to retrieve the content of all the epub file:
public ArrayList<String> getBookContent(Book bi) {
// GET THE CONTENTS OF ALL PAGES
StringBuilder string = new StringBuilder();
ArrayList<String> listOfPages = new ArrayList<>();
Resource res;
InputStream is;
BufferedReader reader;
String line;
Spine spine = bi.getSpine();
for (int i = 0; spine.size() > i; i++) {
res = spine.getResource(i);
try {
is = res.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
// FIRST PAGE LINE -> <?xml version="1.0" encoding="utf-8" standalone="no"?>
if (line.contains("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>")) {
string.delete(0, string.length());
}
// ADD THAT LINE TO THE FINAL STRING REMOVING ALL THE HTML
string.append(Html.fromHtml(formatLine(line)));
// LAST PAGE LINE -> </html>
if (line.contains("</html>")) {
listOfPages.add(string.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return listOfPages;
}
private String formatLine(String line) {
if (line.contains("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd")) {
line = line.substring(line.indexOf(">") + 1, line.length());
}
// REMOVE STYLES AND COMMENTS IN HTML
if ((line.contains("{") && line.contains("}"))
|| ((line.contains("/*")) && line.contains("*/"))
|| (line.contains("<!--") && line.contains("-->"))) {
line = line.substring(line.length());
}
return line;
}
As you may have notice I need to improve the filter, but I have every chapter of that book in my ArrayList. Now I just need to call that ArrayList like myList.get(0); and is done.
To show the text in a proper way, I'm using the bluejamesbond:textjustify library (https://github.com/bluejamesbond/TextJustify-Android).
It is easy to use and powerful.
I hope it helps you, and if anybody finds a better way to filter that html, notice me, please.
My code uses BufferedReader to read columns of data in a text file. The text file looks like:
Year.....H2OIN....CO2IN
0.000......0.0..........0.0
1.000......2.0..........6.0
2.000......3.0..........7.0
3.000......4.0..........8.0
My formatting code looks like:
try {
FileInputStream file = new FileInputStream(inputFile);
BufferedReader in = new BufferedReader(new InputStreamReader(file));
f = new Formatter("M:\\TESTPACK\\AL6000803OUT.TXT");
while((line = in.readLine()) != null) {
if (line.startsWith(" 0.000"))
break;
}
while((line = in.readLine()) != null) {
stream = line.split(parse);
start = line.substring(6,9);
if (start.equals("000")) {
H2OIN = Double.parseDouble(stream[1]);
CO2IN = Double.parseDouble(stream[2]);
f.format("%s ", H2OIN);
f.format("%s ", CO2IN);
}
}
}catch (FileNotFoundException e) {
}catch (IOException e) {
}
f.close();
However, my output file looks like:
2.0 6.0 3.0 7.0 4.0 8.0
While I want it to look like:
2.0 3.0 4.0
6.0 7.0 8.0
I need a suggestion for how to apply formatting to the data strings, not the data itself. Essentially I need to transpose columns of data to rows of data. The duplicate post suggested was not the problem I'm trying to solve.
You'll need to include two StringBuffers. One for your H2OIN row and another for your CO2IN row.
Like so:
With your other declarations...
StringBuffer H2OINRow = new StringBuffer();
StringBuffer CO2INRow = new StringBuffer();
In your if (start.equals("000")) block...
// in place of the f.format calls
H2OINRow.Append(H2OIN + " ");
CO2INRow.Append(CO2IN + " ");
After your while loops...
f.format("%s\n", H2OINRow);
f.format("%s\n", CO2INRow);
I suggest you gather all the values you want on each line in a different List.
So instead, your while loop would look like :
List<String> h2oValues = new ArrayList<String>();
List<String> c02Values = new ArrayList<String>();
while((line = in.readLine()) != null) {
stream = line.split(parse);
start = line.substring(6,9);
if (start.equals("000")) {
H2OIN = Double.parseDouble(stream[1]);
CO2IN = Double.parseDouble(stream[2]);
h2oValues.add(H2OIN);
c02Values.add(CO2IN);
}
}
After that, loop the values of h2oValues to write them in a line and do the same for c02Values
for (String value : h2oValues) {
f.format("%s ", value);
}
// Add a end of line character... using the system one, you might want to change that
f.format(%n);
for (String value : h2oValues) {
f.format("%s ", c02Values);
}
For the end line, see this question if you want to change it.
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();
}
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");
}