Cross reference from DSL to EMF Ecore model not working in LSP setup - eclipse-plugin

I have a DSL language where we need to cross-refer EAttribute that are defined in a separate file.
This works fine in the eclipse plugin setup but it is not working in the LSP setup based on Vscode/Theia client.
Grammar Snippet -
Atomic returns Expression:
{IntConstant} value=INT |
{StringConstant} value=STRING |
{BoolConstant} value=('true' | 'false') |
{VariableRef} variable=[ecore::EAttribute|QualifiedName];
Example -
DSL file - test.mexpression
iota=1
iota is a variable which is defined in a separate file - variables.ecore
<?xml version="1.0" encoding="UTF-8"?>
<ecore:EPackage xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="vari" nsURI="vvvv" nsPrefix="var">
<eClassifiers xsi:type="ecore:EClass" name="Variables">
<eStructuralFeatures xsi:type="ecore:EAttribute" name="iota" eType="ecore:EDataType
http://www.eclipse.org/emf/2002/Ecore#//EBoolean"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="Cars" eType="ecore:EDataType
http://www.eclipse.org/emf/2002/Ecore#//EString"
defaultValueLiteral=""/>
</eClassifiers>
<eClassifiers xsi:type="ecore:EClass" name="Car">
<eStructuralFeatures xsi:type="ecore:EAttribute" name="Model" eType="ecore:EDataType
http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eClassifiers>
</ecore:EPackage>
Language client Snippet -
export function activate(context: ExtensionContext) {
// The server is a started as a separate app and listens on port 5007
let connectionInfo = {
port: 5008
};
let serverOptions = () => {
// Connect to language server via socket
let socket = net.connect(connectionInfo);
let result: StreamInfo = {
writer: socket,
reader: socket
};
return Promise.resolve(result);
};
let clientOptions: LanguageClientOptions = {
documentSelector: ['mexpression','ecore'],
synchronize: {
fileEvents: workspace.createFileSystemWatcher('**/*.*')
}
};
// Create the language client and start the client.
let lc = new LanguageClient('Xtext Server', serverOptions, clientOptions);
Am I missing something here ? or We have to create a standalone setup for variable file & register it via service providers to make it work in LSP environment.

Related

Karate - Polyglot Exception using js callSingle()

In the code presented below, I am trying to interact with a database through the use of a js function within the karate framework. The query used to get some data works as expected, likewise auxiliary information is accessible. The same function within the js file can be ran through groovy just fine but seems to explode when ran within karate.
JS Function to be ran in karate through a callSingle():
function() { let dbUser = Java.type('dev.dao.dbUser') return dbUser.getId(karate.properties['username'])
dbUser:
class dbUser {
static Integer getId(String email) {
db.sql.firstRow("select user_id from table.db_user where email = ?", [email]).userId
}
}
Karate-config.js
function fn() {
let config = {
project: karate.properties['vs.project'],
environment: karate.properties['vs.environment'],
baseUrl: karate.properties['vs.baseUrl'],
timeZoneId: karate.properties['vs.timeZoneId'],
env: karate.properties['vs.env'],
proxy: {
...
]
},
demoUserId: 1,
userId: karate.callSingle('classpath:proj/dev/js/dao/getDbUserId.js'),
createDBuid: karate.read('classpath:proj/dev/js/createDBuid.js'),
DBuid: karate.callonce('classpath:proj/dev/js/createDBuid.js')
}
}
Error returned calling the getDbUserId.js:
PolyglotError
<<<<
org.graalvm.polyglot.PolyglotException
com.intuit.karate.core.ScenarioBridge.callSingle(ScenarioBridge.java:243)
com.intuit.karate.core.ScenarioBridge.callSingle(ScenarioBridge.java:187)
.fn(Unnamed:18)

What are cloudflare KV preview_ids and how to get one?

I have a following wrangler.toml. When I would like to use dev or preview (e.g. npx wrangler dev or npx wrangler preview) wrangler asks to add a preview_id to the KV namespaces. Is this an identifier to an existing KV namespace?
I see there is a ticket in Cloudflare Workers GH at https://github.com/cloudflare/wrangler/issues/1458 that tells this ought to be clarified but the ticket is closed with adding an error message
In order to preview a worker with KV namespaces, you must designate a preview_id in your configuration file for each KV namespace you'd like to preview."
which is the reason I'm here. :)
As for larger context I would be really glad if someone could clarify: I see that if I give a value of an existing namespace, I can preview and I see a KV namespace of type __some-worker-dev-1234-workers_sites_assets_preview is generated in Cloudflare. This has a different identifier than the KV namespace pointed by the identifier used in the preview_id and the KV namespace pointed by the identifier I used in preview_id is empty. Why does giving an identifier of an existing KV namespace remove the error message, deploys the assets and allow for previwing but the actual KV namespace is empty and a new one is created?
How do does kv-asset-handler know to look into this generated namespace to retrieve the assets?
I'm currently testing with the default generated Cloudare Worker to my site and I wonder if I have misunderstood something or if there is some mechanics that bundles during preview/publish the site namespace to the scipt.
If there is some random mechanics with automatic mapping, can this be then so that every developer can have their own private preview KV namespace?
type = "javascript"
name = "some-worker-dev-1234"
account_id = "<id>"
workers_dev = true
kv_namespaces = [
{ binding = "site_data", id = "<test-site-id>" }
]
[site]
# The location for the site.
bucket = "./dist"
# The entry directory for the package.json that contains
# main field for the file name of the compiled worker file in "main" field.
entry-point = ""
[env.production]
name = "some-worker-1234"
zone_id = "<zone-id>"
routes = [
"http://<site>/*",
"https://www.<site>/*"
]
# kv_namespaces = [
# { binding = "site_data", id = "<production-site-id>" }
# ]
import { getAssetFromKV, mapRequestToAsset } from '#cloudflare/kv-asset-handler'
/**
* The DEBUG flag will do two things that help during development:
* 1. we will skip caching on the edge, which makes it easier to
* debug.
* 2. we will return an error message on exception in your Response rather
* than the default 404.html page.
*/
const DEBUG = false
addEventListener('fetch', event => {
try {
event.respondWith(handleEvent(event))
} catch (e) {
if (DEBUG) {
return event.respondWith(
new Response(e.message || e.toString(), {
status: 500,
}),
)
}
event.respondWith(new Response('Internal Error', { status: 500 }))
}
})
async function handleEvent(event) {
const url = new URL(event.request.url)
let options = {}
/**
* You can add custom logic to how we fetch your assets
* by configuring the function `mapRequestToAsset`
*/
// options.mapRequestToAsset = handlePrefix(/^\/docs/)
try {
if (DEBUG) {
// customize caching
options.cacheControl = {
bypassCache: true,
}
}
const page = await getAssetFromKV(event, options)
// allow headers to be altered
const response = new Response(page.body, page)
response.headers.set('X-XSS-Protection', '1; mode=block')
response.headers.set('X-Content-Type-Options', 'nosniff')
response.headers.set('X-Frame-Options', 'DENY')
response.headers.set('Referrer-Policy', 'unsafe-url')
response.headers.set('Feature-Policy', 'none')
return response
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
if (!DEBUG) {
try {
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
})
return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
} catch (e) {}
}
return new Response(e.message || e.toString(), { status: 500 })
}
}
/**
* Here's one example of how to modify a request to
* remove a specific prefix, in this case `/docs` from
* the url. This can be useful if you are deploying to a
* route on a zone, or if you only want your static content
* to exist at a specific path.
*/
function handlePrefix(prefix) {
return request => {
// compute the default (e.g. / -> index.html)
let defaultAssetKey = mapRequestToAsset(request)
let url = new URL(defaultAssetKey.url)
// strip the prefix from the path for lookup
url.pathname = url.pathname.replace(prefix, '/')
// inherit all other props from the default request
return new Request(url.toString(), defaultAssetKey)
}
}
In case the format is not obvious (it wasn't to me) here is a sample config block from the docs with the preview_id specified for a couple of KV Namespaces:
kv_namespaces = [
{ binding = "FOO", id = "0f2ac74b498b48028cb68387c421e279", preview_id = "6a1ddb03f3ec250963f0a1e46820076f" },
{ binding = "BAR", id = "068c101e168d03c65bddf4ba75150fb0", preview_id = "fb69528dbc7336525313f2e8c3b17db0" }
]
You can generate a new namespace ID in the Workers KV section of the dashboard or with the Wrangler CLI:
wrangler kv:namespace create "SOME_NAMESPACE" --preview
This answer applies to versions of Wrangler >= 1.10.0
wrangler asks to add a preview_id to the KV namespaces. Is this an identifier to an existing KV namespace?
Yes! The reason there is a different identifier for preview namespaces is so that when developing with wrangler dev or wrangler preview you don't accidentally write changes to your existing production data with possibly buggy or incompatible code. You can add a --preview flag to most wrangler kv commands to interact with your preview namespaces.
For your situation here there are actually a few things going on.
You are using Workers Sites
You have a KV namespace defined in wrangler.toml
Workers Sites will automatically configure a production namespace for each environment you run wrangler publish on, and a preview namespace for each environment you run wrangler dev or wrangler preview on. If all you need is Workers Sites, then there is no need at all to specify a kv-namepsaces table in your manifest. That table is for additional KV namespaces that you may want to read data from or write data to. If that is what you need, you'll need to configure your own namespace and add id to wrangler.toml if you want to use wrangler publish, and preview_id (which should be different) if you want to use wrangler dev or wrangler preview.

WL.Logger.Send() its Not callback the WLClientLogReceiver adapter

I have enabled the nativeOptions: {capture: true} in initOptions.js
logger : {enabled: true, level: 'debug', stringify: true, pretty: false,
tag: {level: false, pkg: true}, whitelist: [], blacklist: [], nativeOptions: {capture: true}}
In my main js file i have the following code.
function wlCommonInit(){
// Common initialization code goes here
WL.Logger.setNativeOptions({'capture': true});
var logger = WL.Logger.create({pkg: 'mypackage'});
logger.debug('Hello world - debug');
//[mypackage] Hello world
logger.log('Hello world - log');
//[mypackage] Hello world
logger.info('Hello world - info');
//[mypackage] Hello world
logger.warn('Hello world - warn');
//[mypackage] Hello world
logger.error('Hello world - error');
//[mypackage] Hello world
WL.Logger.send(); }
WL.Logger.send() suppose to call my adapter "WLClientLogReceiver". But i am not getting any call for this adapter.
Please let me know, i need to enable any other settings to upload my client side captured log to server.
function log(deviceInfo, logMessages) {
return true;}
<procedure name="log" securityTest="wl_unprotected" audit="true" />
logger : {enabled: true, level: 'debug', stringify: true, pretty: false, tag: {level: false, pkg: true}, whitelist: [], blacklist: [], nativeOptions: {capture: true}}
You have enabled the native capture as true in initOptions.js so no need to set it again.
You can log using your package that will help you in filtering the messages based on the package in your WLClientLogReceiver adapter.
var myloggerObject = WL.Logger.create({pkg: 'mypackage'});
myloggerObject.debug("Hello world");
you can specify your level in your js file to be logged in client device.
In the adapter you will get the log messages as an json array.
function log(deviceInfo, logMessages) {
/* The adapter can choose to process the parameters,
for example to forward them to a backend server for
safekeeping and further analysis.
The deviceInfo object may look like this:
{
"appName": "wlapp",
"appVersion": "1.0",
"deviceId": "66eed0c9-ecf7-355f-914a-3cedac70ebcc",
"model": "Galaxy Nexus - 4.2.2 - API 17 - 720x1280",
"systemName": "Android",
"systemVersion": "4.2.2",
"os.arch": "i686", // Android only
"os.version": "3.4.0-qemu+" // Android only
}
The logMessages parameter is a JSON array
that contains JSON object elements, and might look like this:
[{
"timestamp" : "17-02-2013 13:54:23:745", // "dd-MM-yyyy hh:mm:ss:S"
"level" : "ERROR", // ERROR||WARN||INFO||LOG|| DEBUG
"package" : "your_tag", // typically a class name
"msg" : "the message", // a helpful log message
"threadid" : 42, // (Android only)the current thread
"metadata" : { "$src" : "js" } // metadata placed on the log call
}]
*/
//sample log and filtering method
var logs= [{
"timestamp" : "17-02-2013 13:54:23:745", // "dd-MM-yyyy hh:mm:ss:S"
"level" : "ERROR", // ERROR||WARN||INFO||LOG|| DEBUG
"package" : "your_tag", // typically a class name
"msg" : "the message", // a helpful log message
"threadid" : 42, // (Android only)the current thread
"metadata" : { "$src" : "js" } // metadata placed on the log call
},
{
"timestamp" : "17-02-2013 13:54:23:745", // "dd-MM-yyyy hh:mm:ss:S"
"level" : "ERROR", // ERROR||WARN||INFO||LOG|| DEBUG
"package" : "mypackage", // typically a class name
"msg" : "my package message", // a helpful log message
"threadid" : 42, // (Android only)the current thread
"metadata" : { "$src" : "js" } // metadata placed on the log call
}
];
var filteredLogs = logs.filter(function(log){
if(log.package == mypackage) //comparing the package and returns the object
{ return log; }
});
WL.Logger.error(filteredLogs);// This is send only the filtered array to your server
}
If you log using metadata such as filename along with the debug message you will get those in the array in metadata attribute.
It is suggested to stringify and parse the object to avoid errors before parsing the device logs in the adapter.
var logs = JSON.stringify(JSON.parse(logs));
var filteredLogs = logs.filter ...
Hope this will work for you.
Make sure you test it using the device.
The send function is not attached to the LogInstance prototype, which is what you're using when you use a logger instance created with WL.Logger.create(). Please call
WL.Logger.send();
instead.
(Above was posted prior to OP's edit.)
Since setNativeOptions is an asynchronous call (it calls down through a Cordova plugin), it is possible it has not successfully turned capture on prior to completion of the subsequent logger calls. So at the time of the call to WL.Logger.send(); nothing has been collected yet.
Do this:
function wlCommonInit() {
// Common initialization code goes here
WL.Logger.setNativeOptions({'capture': true})
.then(function() {
var logger = WL.Logger.create({pkg: 'mypackage'});
logger.debug('Hello world - debug');
//[mypackage] Hello world
logger.log('Hello world - log');
//[mypackage] Hello world
logger.info('Hello world - info');
//[mypackage] Hello world
logger.warn('Hello world - warn');
//[mypackage] Hello world
logger.error('Hello world - error');
//[mypackage] Hello world
WL.Logger.send();
});
}
Be sure to check the server-side logs. The audit="true" in the adapter's descriptor file will print the parameters passed to the adapter inline in the server logs (messages.log on WebSphere Liberty).

How to consume WCF soap web service in node.js

I tried lot of examples available in the net using node module wcf.js. But could not get any appropriate result. I'm using the below url
https://webservice.kareo.com/services/soap/2.1/KareoServices.svc?wsdl
Any one who can explain me with the help of code will be really helpful. I want to know how to access the wsdl in node.js
Thanks.
Please have a look at wcf.js
In short you can follow these steps:
npm install wcf.js
Write your code like this:
code
var Proxy = require('wcf.js').Proxy;
var BasicHttpBinding = require('wcf.js').BasicHttpBinding;
var binding = new BasicHttpBinding();
//Ensure the proxy variable created below has a working wsdl link that actually loads wsdl
var proxy = new Proxy(binding, "http://YourHost/YourService.svc?wsdl");
/*Ensure your message below looks like a valid working SOAP UI request*/
var message = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:sil='http://YourNamespace'>" +
"<soapenv:Header/>" +
"<soapenv:Body>" +
"<sil:YourMethod>" +
"<sil:YourParameter1>83015348-b9dc-41e5-afe2-85e19d3703f9</sil:YourParameter1>" +
"<sil:YourParameter2>IMUT</sil:YourParameter2>" +
"</sil:YourMethod>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
/*The message that you created above, ensure it works properly in SOAP UI rather copy a working request from SOAP UI*/
/*proxy.send's second argument is the soap action; you can find the soap action in your wsdl*/
proxy.send(message, "http://YourNamespace/IYourService/YourMethod", function (response, ctx) {
console.log(response);
/*Your response is in xml and which can either be used as it is of you can parse it to JSON etc.....*/
});
You don't have that many options.
You'll probably want to use one of:
node-soap
douche
soapjs
i tried node-soap to get INR USD rate with following code.
app.get('/getcurr', function(req, res) {
var soap = require('soap');
var args = {FromCurrency: 'USD', ToCurrency: 'INR'};
var url = "http://www.webservicex.net/CurrencyConvertor.asmx?WSDL";
soap.createClient(url, function(err, client) {
client.ConversionRate(args, function(err, result) {
console.log(result);
});
});
});
Code Project has got a neat sample which uses wcf.js for which api's are wcf like so no need to learn new paradigm.
I think that an alternative would be to:
use a tool such as SoapUI to record input and output xml messages
use node request to form input xml message to send (POST) the request to the web service (note that standard javascript templating mechanisms such as ejs or mustache could help you here) and finally
use an XML parser to deserialize response data to JavaScript objects
Yes, this is a rather dirty and low level approach but it should work without problems
You'll probably want to use one of:
node-soap
douche
soapjs
Aslo, there's an existing question.
In my case, I used https://www.npmjs.com/package/soap. By default forceSoap12Headers option was set to false which prevented node-soap to generate correct soap message according to SOAP 1.2. Check for more details: I am confused about SOAP namespaces. After I set it to true, I was able to make a call to .NET WCF service. Here is a TypeScript code snipper that worked for me.
import * as soap from 'soap';
import { IOptions } from 'soap';
// ...
const url = 'https://www.your-domain.com/stock.svc?wsdl';
const opt: IOptions = {
forceSoap12Headers: true,
};
soap.createClient(url, opt, (err, client: soap.Client) => {
if (err) {
throw err;
}
const wsSecurityOptions = {
hasTimeStamp: false,
};
const wsSecurity = new soap.WSSecurity('username', 'password', wsSecurityOptions);
client.setSecurity(wsSecurity);
client.addSoapHeader({ Action: 'http://tempuri.org/API/GetStockDetail' }, undefined, 'wsa', 'http://www.w3.org/2005/08/addressing');
client.addSoapHeader({ To: 'https://www.your-domain.com/stock.svc' }, undefined, 'wsa', 'http://www.w3.org/2005/08/addressing');
const args = {
symbol: 'GOOG',
};
client.GetStockDetail(
args,
(requestErr, result) => {
if (requestErr) {
throw requestErr;
}
console.log(result);
},
);
});
Here couple links to the documentation of node-soap usage:
https://github.com/vpulim/node-soap/tree/master/test
https://github.com/vpulim/node-soap

WinJS.xhr local network error

I am trying to make a simple windows 8 app but I have a problem.
When I try to make a xhr request to a local webserver it fails with the error code: 0x2efd
Sample code:
WinJS.xhr({ url: "http://192.168.0.30" }).then(
function completed(response) {
//var json = JSON.parse(response.responseText);
//var list = new WinJS.Binding.List(json.results);
console.log(response.responseText);
},
function error(error) { console.log(error) },
function progress(progress) { }
);
But when I try a remote IP for instance google.com it works.
What is going wrong?
Did you declare the "private network" capability in your project's application manifest? Double click your application manifest file - It is located under the capabilities tab.