Bar code scan and generate in xpages - javascript

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/.

Related

Native module FBAccessToken tried to override FBAccesTokenModule. Check the getPackages() method in MainApplication.Java

So I receive this error message while attempting to integrate Facebook login into my app but am overall unclear on how to address it as I can't seem to figure out what's wrong with my MainActivity.java file. I already installed Facebook SDK using "npm install --save react-native-fbsdk-next" and overall seem to have the necessary and correct dependencies.
The error message
The code in my MainActivity.Java file:
package com.socialapp2;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for
// example:
// packages.add(new MyReactNativePackage());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method
* with something like initializeFlipper(this,
* getReactNativeHost().getReactInstanceManager());
*
* #param context
* #param reactInstanceManager
*/
private static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
* We use reflection here to pick up the class that initializes Flipper, since
* Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.socialapp.ReactNativeFlipper");
aClass.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class).invoke(null, context,
reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
I solved the issue. See below for resolution:
Check your package.json file and make sure you do not have duplicate facebook sdk dependencies. In my case i had "react-native-fbsdk" and "react-native-fbsdk-next" as two separate dependencies which conflicted with each other.
Here are some general troubleshooting steps as well:
Make sure that the package name is identical in your MainActivity.java, MainApplication.java, and AndroidManifest.xml file.
Make sure that the applicatonId in your app/build.gradle file matches the package name specified in the previous bullet point.

Using d3.js via postgres

I'm currently studying java spring and d3.js. And found myself on a roadblock since i can't seem to find the right answer to my problem after countless trial and error plus research.
The code below is the one that is my controller:
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import dashboard.atmandcam.model.MyModel;
import dashboard.atmandcam.repo.MyRepo;
#RestController
public class MyController {
#Autowired
private MyRepo myRepo;
#GetMapping("/test")
public String sayHi() {
return "hi";
}
#GetMapping("/queries")
public List<MyModel> getResult(){
return myRepo.getQueryResult();
}
#GetMapping("/queries/{id}")
public List<MyModel> getSpecific(#PathVariable String id){
return myRepo.getSpecificResult(id);
}
}
Then this is my d3.js
var url = "/queries/31370100";
d3.json(url, function(data) {
console.log(data);
});
the result of my controller is w/ the URL (http://localhost:9090/queries/31370100):
I wanna know how can i use the JSON found on my url in d3.js so i can build my charts around my database.

Trouble running a background service in react native

This is my very first post here, so please don't blame me if I'm not as complete and clear as I have to be.
The issue
I am new to React native and I recently began to develop a react native app which could read my incoming SMS's aloud. I already achieved to retrieve the incoming messages and to read them aloud... But only if the app is the foreground.
So, could you please advise me some libraries or tutorials on the subject ?
I'm working on a Nokia 5 with Android 9.
I currently use the following libraries :
React-native-android-sms-listener to retrieve the incoming messages.
React-native-tts to read the content aloud.
What I already tried
I'm searching the Internet for more than a week now (includig Stack Overflow and this example question) and I can't find what I'm looking for. I already tried React-native-background-timer and React-native-background-job. But I couldn't never get a background timer working and React-native-background-job allows tasks to be executed every 15 minutes only (due to the Android limitations).
So I read many articles like this one explaining how to use Headless JS and other libraries until I found this codeburst tutorial today, explaining how to develop a background service to record audio calls. I tried to adapt it, but the background service never starts.
My code
I must tell you that I don't have any knowledge in Java, so the native code below may contain mistakes, even if it is based on tutorials and the React native documentation.
Currently, when the app is launched, the service IncomingSMSService is called. This service, developed following the Codeburst tutorial referenced above, relies on Headless JS and a JS function that listen to the incoming messages and then read them aloud thanks to React-native-tts.
Here is these two files :
IncomingSMSService.java
package com.ava.service;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
public class IncomingSMSService extends HeadlessJsTaskService {
#Override
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"HandleIncomingSMS",
Arguments.fromBundle(extras),
5000,
true
);
}
return null;
}
}
HandleIncomingSMS.js
import { AppRegistry } from 'react-native';
import SmsListener from 'react-native-android-sms-listener';
import Tts from 'react-native-tts';
const HandleIncomingSMS = async (taskData) => {
SmsListener.addListener(message => {
Tts.getInitStatus().then(() => {
Tts.speak(`New message from number ${message.originatingAddress} : ${message.body}`);
});
});
}
AppRegistry.registerHeadlessTask('HandleIncomingSMS', () => HandleIncomingSMS));
These pieces of code are called in a BroadcastReceiver here (IncomingSMSReceiver.java) :
package com.ava.receiver;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ava.service.IncomingSMSService;
import com.facebook.react.HeadlessJsTaskService;
import java.util.List;
public final class IncomingSMSReceiver extends BroadcastReceiver {
#Override
public final void onReceive(Context context, Intent intent) {
if (!isAppOnForeground((context))) {
Intent service = new Intent(context, IncomingSMSService.class);
context.startService(service);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses =
activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance ==
ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
I also requested the good permissions in my AndroidManifest file, and I registered the service like so :
<service
android:name="com.ava.service.IncomingSMSService"
android:enabled="true"
android:label="IncomingSMSService"
/>
<receiver android:name="com.ava.receiver.IncomingSMSReceiver">
<intent-filter android:priority="0">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
What am I doing wrong ? I don't even see service in the Running services tab of the Android Developer options... Any ideas ?
Thanks in advance for your help.
UPDATE (01/06/2019)
After reading or watching several tutorials like this one or this video, I managed to get my app working in the foreground. It now displays a persistent notification.
BUT, I don't know how I can "link" my service and my Broadcsat Receiver to this notification (for now, the service is called only if the app is in foreground).
Here is my updated code :
// IncomingSMSService
package com.ava.service;
import android.graphics.Color;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.ContextWrapper;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.facebook.react.HeadlessJsTaskService;
import com.ava.MainActivity;
import com.ava.R;
public class IncomingSMSService extends Service {
private NotificationManager notifManager;
private String CHANNEL_ID = "47";
private int SERVICE_NOTIFICATION_ID = 47;
private Handler handler = new Handler();
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
Context context = getApplicationContext();
Intent myIntent = new Intent(context, IncomingSMSEventService.class);
context.startService(myIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
handler.postDelayed(this, 2000);
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void createNotificationChannel() {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "General", notifManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(notificationChannel);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.handler.post(this.runnableCode);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Ava")
.setContentText("Listening for new messages...")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(contentIntent)
.setOngoing(true)
.build();
startForeground(SERVICE_NOTIFICATION_ID, notification);
return START_NOT_STICKY;
}
private NotificationManager getManager() {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return notifManager;
}
}
My headlessJS task :
// HandleIncomingSMS.js
import SmsListener from 'react-native-android-sms-listener';
import Tts from 'react-native-tts';
import Contacts from 'react-native-contacts';
import { text } from 'react-native-communications';
module.exports = async () => {
// To lower other applications' sounds
Tts.setDucking(true);
// Prevent the TTS engine from repeating messages multiple times
Tts.addEventListener('tts-finish', (event) => Tts.stop());
SmsListener.addListener(message => {
Contacts.getAll((err, contacts) => {
if (err) throw err;
const contactsLoop = () => {
contacts.forEach((contact, index, contacts) => {
// Search only for mobile numbers
if (contact.phoneNumbers[0].label === 'mobile') {
// Format the contact number to be compared with the message.oritignatingAddress variable
let contactNumber = contact.phoneNumbers[0].number.replace(/^00/, '+');
contactNumber = contactNumber.replace(/[\s-]/g, '');
// Phone numbers comparison
if (contactNumber === message.originatingAddress) {
if (contact.familyName !== null) {
Tts.speak(`Nouveau message de ${contact.givenName} ${contact.familyName} : ${message.body}`);
} else {
// If the contact doesn't have a known family name, just say his first name
Tts.speak(`Nouveau message de ${contact.givenName} : ${message.body}`);
}
} else if (contactNumber !== message.originatingAddress && index === contacts.length) {
// If the number isn't recognized and if the contacts have been all checked, just say the phone number
Tts.speak(`Nouveau message du numéro ${message.originatingAddress} : ${message.body}`);
}
}
});
}
contactsLoop();
// Redirect to the SMS app
text(message.originatingAddress, message = false);
});
});
}
I also added the good permissions in my AndroidManifest.xml file like the following :
...
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
...
I made some progress but I am still stuck, so if you have any idea, please share them ! Thank you !

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.

Use a json script from java, possible?

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

Categories

Resources