Use a json script from java, possible? - javascript

I am trying to create a java program that retrieves a METARs from the stations like this:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class metar{
public static void main(String[] args) throws IOException {
URL aURLGlobal=null;
Document doc;
String fichier ="stations.txt";
try {
InputStream ips=new FileInputStream(fichier);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
// need http protocol
String ligne;
while ((ligne=br.readLine())!=null){
URL aURL = new URL( "https://www.aviationweather.gov/adds/metars/?station_ids="+ligne+"&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&submitmet=Submit");
// System.out.println("******************city num"+aURL.toString()+"**************************");
doc = Jsoup.connect(aURL.toString()).get();
String element= doc.select("FONT").first().ownText();
System.out.println(element);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
stations.txt :
LSGG
LFMD
LFMN
LFQB
LFMK
LFCR
LFML
LFMI
LFMY
LFRK
result :
LSGG 201620Z 22018KT 7000 -RA FEW014 SCT025 OVC045 13/10 Q1010 TEMPO 4000 RA BR
LFMD 201600Z AUTO 23017G28KT 200V280 CAVOK 18/10 Q1008
LFMN 201600Z 07015KT CAVOK 17/12 Q1007 TEMPO WS ALL RWY
LFQB 201600Z AUTO 32006KT 9999 -RA BKN004/// BKN035/// BKN042/// ///TCU 08/08 Q1005
LFMK 201600Z AUTO 28015KT 240V300 CAVOK 20/03 Q1018
LFCR 201600Z AUTO 25015KT 9999 OVC018 13/10 Q1018
LFML 201530Z 25017KT CAVOK 17/10 Q1016 NOSIG
LFMI 201600Z AUTO 29014KT CAVOK 17/09 Q1016
LFMY 201600Z AUTO 28012KT 250V310 CAVOK 17/09 Q1016
LFRK 201600Z AUTO 29012KT 9999 BKN036 OVC044 09/08 Q1009
I am now looking to parse a json file METARs,
I found a metar.js script to parse any metar
http://epeli.github.io/metar.js/
My question is (I do not know too in json): did i can use it to parse all of my METARs and copied in one json file, that is to say call the file parser.js from java.
someone can help me please..
Edit :
THANKS A LOT FOR YOUR IDEA
CODE:
package tests;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class test {
public static void main(String[] args) throws IOException, ScriptException, NoSuchMethodException {
URL aURLGlobal=null;
Document doc;
String fichier ="stations.txt";
try {
InputStream ips=new FileInputStream(fichier);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
// need http protocol
String ligne;
while ((ligne=br.readLine())!=null){
URL aURL = new URL( "https://www.aviationweather.gov/adds/metars/?station_ids="+ligne+"&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&submitmet=Submit");
// System.out.println("******************city num"+aURL.toString()+"**************************");
doc = Jsoup.connect(aURL.toString()).get();
String element= doc.select("FONT").first().ownText();
System.out.println(element);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:\\metar.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("parseMETAR", element);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}}
error :
LSGG 201620Z 22018KT 7000 -RA FEW014 SCT025 OVC045 13/10 Q1010 TEMPO 4000 RA BR
Exception in thread "main" java.lang.NoSuchMethodException: No such function parse
at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:197)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:381)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:187)
at tests.test.main(test.java:52)
as I told you, json is a black box for me, it is the parse function to be used in metar.js, and I put my metar parameter recevid from the previous step,
Thanks for your help

Related

Bar code scan and generate in xpages

I need to use barcodes in an xpages application, both to generate the barcode and to read it. Does anyone know of any libraries I can use on the application? Has anyone used these features in a xpages application? How do I find out the barcode pattern?
I am using ZXing for creating and reading different types of barcodes.
For Java 6 there is an older version available: Solvoj ZXing
EDIT:
Import http://central.maven.org/maven2/com/solvoj/zxing-java6/core-java6/3.2.0/core-java6-3.2.0.jar
Import http://central.maven.org/maven2/com/solvoj/zxing-java6/javase-java6/3.2.0/javase-java6-3.2.0.jar
Create a managed bean
Add the bean to your XPage
Managed Bean
package ch.hasselba.xpages;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.faces.context.FacesContext;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.ibm.xsp.webapp.XspHttpServletResponse;
public class ZXingBean {
public void generateDemoQRCode() {
FacesContext fc = FacesContext.getCurrentInstance();
XspHttpServletResponse response = (XspHttpServletResponse) fc.getExternalContext().getResponse();
try {
response.setContentType("image/png");
response.getOutputStream().write(generateQRCode("Hello World!", 200, 200 ));
} catch (IOException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
fc.responseComplete();
}
public byte[] generateQRCode(String text, int width, int height)
throws WriterException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitMatrix matrix = new MultiFormatWriter().encode(text,
BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToStream(matrix, "png", baos,
new MatrixToImageConfig());
return baos.toByteArray();
}
}
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config>
<managed-bean>
<managed-bean-name>zxingBean</managed-bean-name>
<managed-bean-class>ch.hasselba.xpages.ZXingBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
XAgent
<xp:view
xmlns:xp="http://www.ibm.com/xsp/core"
rendered="false"
viewState="nostate">
<xp:this.beforeRenderResponse><![CDATA[#{javascript:zxingBean.generateDemoQRCode()}]]></xp:this.beforeRenderResponse>
</xp:view>
I am using Barcode4J in an XPages application to generate bar codes: http://barcode4j.sourceforge.net/.

Cross Origin requests at server side

Hi I am facing issue in cross origin requests at server side when trying to open file which is retrieved from database using java.I am unaware of this cross orgin requests.When file is clicked then it is giving error as
jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/JR00432239/Desktop/trial/src/temp/filetest1.docx. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Can anyone please help me to resolve this issue.
Here is my java code:
package fileretrieve;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import dbConnection.Dbconn;
#MultipartConfig
public class FileRetrieve extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String onelevel=request.getParameter("onelevel");
Connection conn = null; // connection to the database
String message = null;
Statement st = null;// message will be sent back to client
try {
// connects to the database
conn = Dbconn.getConnection();
st = conn.createStatement();
PreparedStatement ps=conn.prepareStatement("select data from files1 where board=?");
ps.setString(1,onelevel);
//out.print("<table width=25% border=1>");
// out.print("<center><h1>Result:</h1></center>");
ResultSet rs=ps.executeQuery();
/* Printing column names */
ResultSetMetaData rsmd=rs.getMetaData();
int count=0;
while(rs.next())
{
count=count+1;
FileOutputStream fos = new FileOutputStream("C:\\Users\\JR00432239\\Desktop\\trial\\src\\temp\\filetest"+count+".docx");
fos.write(rs.getBytes(1));
fos.close();
// out.print("<tr>");
// out.print("<td>"+rsmd.getColumnName(1)+"</td>");
// out.print("<td>"+count+"</td></tr>");
// getServletContext().getRequestDispatcher("/home.html").forward(request, response);
System.out.println("writing...");
response.getWriter().write("{\"name\":\""+count+"\",\"path\":\"C:/Users/JR00432239/Desktop/trial/src/temp/filetest"+count+".docx\"}");
}
// out.print("</table>");
//
}catch (Exception e2)
{
e2.printStackTrace();
}
finally{
// request.setAttribute("data", data);
// RequestDispatcher rd =request.getRequestDispatcher("userview.jsp");
//
out.close();
}
// forwards to the message page
// getServletContext().getRequestDispatcher("/home.html").forward(request, response);
}
}
Here is my html code:
Submit
Here is my javascript page:
$("#retrieve").click(function(){
$.ajax({
url : 'FileRetrieve',
method:"POST",
data : {
onelevel : $('#onelevel').val()
},
crossDomain: true,
success : function(responseText) {
var data=JSON.parse(responseText)
$("#files_data").html('')
$("#files_data").html('<table><tr><td><button onclick="getFile()">'+data.name+'</button></td></tr></table>')
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
return false;
});
If you're using chrome, as a simple solution try a chrome extention like Allow-Control-Allow-Origin:*
https://chrome.google.com/webstore/detail/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info-dialog
if not fixed,
run chrome using command line with the flag
path/to/chrome.exe --allow-file-access-from-files
or just switch to firefox and check whether the issue is still there
this would be a quick-fix only in the development
EDIT
As far as I know, best thing you can do is make the files available in http server and access them using http protocol.

Can an Android App fill a web form without showing the web form to the user?

This is a conceptual idea for learning purpose. I don't know whether it is possible or not.
I have an Android activity with some text fields and a button. The same form is in the web. What I need is;
when user fill and press the button on the android interface, it should fill the web form and press the button on web form (may be using JAVA script or something, I don't know).
I don't need the codes, but just an exact idea how to do this. :)
Please check the image for what I have in my mind. But I cannot determine how and where to apply a JAVA script (if needed)
Can anyone give me an idea please.
Interesting question!
I can think on two alternatives:
You could post the android form to the service that the web form uses in its target attribute.
If you need to fill the web form and post it:
2.1 When you press the OK button in the android form, you can open the web form in a webView (which could be hidden somehow), setting in the url the parameters containing the android form fields' values.
2.2 In the web form, using javascript, check if there are parameters in the URL. If parameters are present, then fill the form and submit it (also using javascript).
That's the round about way of doing it. Instead, you should just have your android form make a direct HTTP request just like the submit of the form would.
This is a simple method.Whether you are doing in php,asp or jsp write the code for the same for the page to insert the data and apply the GET method. Then build the page(where you need) for selecting the data and encode into json form. Then in your android try applying the following code:(by changing the url and the form fields name):
package ex.even78;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.database.CursorJoiner.Result;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class firstact extends Activity implements Z{
/** Called when the activity is first created. */
EditText edt;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edt=(EditText)findViewById(R.id.EditText01);
tv=(TextView)findViewById(R.id.TextView01);
setContentView(R.layout.main);
}
public void method(View v) throws ClientProtocolException, IOException, JSONException
{
HttpClient hc=new DefaultHttpClient();
HttpPost hp=new HttpPost("http://www.akshaychatterjee.in/aks.php");
ArrayList<NameValuePair> al=new ArrayList<NameValuePair>();
al.add(new BasicNameValuePair("phone", "3828929"));
al.add(new BasicNameValuePair("session", "dsfsd"));
hp.setEntity(new UrlEncodedFormEntity(al));
HttpResponse hr=hc.execute(hp);
InputStream in=hr.getEntity().getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(in,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String ss;
while((ss=br.readLine())!=null)
{
sb.append(ss+"\n");
}
}
public void getdata(View v) throws ClientProtocolException, IOException, JSONException
{
HttpClient hc=new DefaultHttpClient();
HttpPost hp=new HttpPost("http://www.akshaychatterjee.in/aks1.php");
ArrayList<NameValuePair> al=new ArrayList<NameValuePair>();
al.add(new BasicNameValuePair("phone","34232"));
hp.setEntity(new UrlEncodedFormEntity(al));
HttpResponse hr=hc.execute(hp);
InputStream in=hr.getEntity().getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(in,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String ss;
while((ss=br.readLine())!=null)
{
sb.append(ss+"\n");
}
JSONObject jo=new JSONObject(sb.toString());
String pass=jo.getString("session");
Toast.makeText(this, pass, 1).show();
in.close();
/*class db extends AsyncTask<String, Void, String>
{
StringBuilder sb;
String pass;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
HttpClient hc=new DefaultHttpClient();
HttpPost hp=new HttpPost("http://www.akshaychatterjee.in/aks1.php");
ArrayList<NameValuePair> al=new ArrayList<NameValuePair>();
al.add(new BasicNameValuePair("phone","34232"));
try {
hp.setEntity(new UrlEncodedFormEntity(al));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpResponse hr = null;
try {
hr = hc.execute(hp);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream in = null;
try {
in = hr.getEntity().getContent();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(in,"iso-8859-1"),8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sb=new StringBuilder();
String ss;
try {
while((ss=br.readLine())!=null)
{
sb.append(ss+"\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pass;
}
protected void onPostExecute(String... arg0) {
tv.setText(pass);
}
}*/
//db d=new db();
//d.execute();
}
}
i.e. you have to use the HTtpclient to knock your server and HTTPOst to apply the method to the form to get the data and collect them by connecting through a JSONobject .(BasicNamevaluepair are used to add the data or insert it or select by its field's name in the form in arraylist form.)
For auto filling you take the resonse data from mobile in that website in another page by httppost and then by applying ajax in the form page you take the data entered in the other page in the fields ,without refreshing it should come.

Converting Byte[] to Image

I want to convert byt[] to image in client side. I have tried the below code but it isn't working. I receive the data1 value but not able to convert it to image.
Client Side :
function getPic(name) {
$.post("/Chat/ProfliePic", {
name : name+".png"
}, function(data1, status) {
alert(data1);
$("#profImg").attr("src","data:image/png;base64," + data1);
});
}
Server Side :
package servlets;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/ProfliePic")
public class ProfliePic extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProfliePic() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
File f = new File("/Users/shilu/MyProject/Chat/Photo/" + name);
byte[] data = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new java.io.FileInputStream(f));
in.readFully(data);
in.close();
response.setContentType("image/png");
ServletOutputStream out = response.getOutputStream();
out.write(data);
out.flush();
out.close();
}
Please tell me where I went wrong...

I am trying to play video using jquery but anchor tag not working while im trying to display video names?

package controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.sun.corba.se.spi.orbutil.fsm.Action;
import bean.Video;
import dao.Dao;
import daoimpl.daoImpl;
public class DisplayVideo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Dao dao=new daoImpl();
String action=request.getParameter("action");
if(action.equals("display")){
ArrayList<Video>al=dao.getAllVideo();
//PrintWriter pw=response.getWriter();
Gson gson=new Gson();
String json = gson.toJson(al);
System.out.println(json);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
This is my servlet where im getting data in json format.
<html>
<head>
<script type="text/javascript" src='js/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
alert("on document ready");
$('#video').click(function(event) {
alert("on click");
$.post("Controller?action=display",
function (data) {
alert("key"+data);
var json = data;
alert("value"+json);
$.each(json, function(key,value) {
alert("key1"+value);
var v ="<a href=${pageContext.request.contextPath}/videos/"+value.videoUrl+"target='blank'>"+value.videoUrl+"</a>";
$(v).appendTo($content);
});
});
});
});
</script>
</head>
<body>
<div id='content'>
<button id="video">Play</button>
</div>
</body></html>
This my sucess.jsp file from here control goes to servlet and get data in json format from database i have only save video name c.mp4,java.mp4 and cpp.mp4 in database also i have create a folder named videos in my webcontent folder in my project and save videos in that folder also.Response getting properly but after printing alert inside each their is nothing print on screen.my requirment is print that all names of video and onclick of link play video in iframe or in popup window.please help me i didnt know the tags which are used.Thanks in Advance.

Categories

Resources