I'm brand new to Nashorn and trying to load my first js file as follow:
public static void main(String[] args) {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("nashorn");
try {
engine.eval("load('https://cdn.jsdelivr.net/sockjs/1.0.3/sockjs.min.js')");
}catch(final ScriptException e) {
System.err.println(e);
}
}
I get the following Exception:
javax.script.ScriptException: TypeError: Cannot read property "prototype" from undefined in http://cdn.jsdelivr.net/sockjs/1.0.3/sockjs.min.js at line number 3
in addition, when I try to evaluate the following:
engine.eval("load('https://code.jquery.com/jquery-1.11.3.min.js')");
the eval() method doesn't return at all - it just stuck on debug (Using Eclipse).
Any idea why prototype isn't defined, any why I cannot evaluate jquery js file?
Thanks!
Nashorn is a ECMAScript5 compatible JavaScript engine. WebSocket API is not a part of ECMAScript 5 but browser API. That's because you get exception.
Related
I am working with the IBM Watson service and imported the library through a maven dependency.
I assumed everything went fine, as all the classes are shown in the external library section:
Instantiating classes works fine, but if I try to use methods from those classes Intellij says "cannot resolve symbol 'methodname'".
public class Watson
{
ConversationService service = new ConversationService("2017-07-02");
service.setUsernameAndPassword("username", "password");
NaturalLanguageClassifier n = new NaturalLanguageClassifier();
n.createClassifier()
}
I have already tried the invalidate caches action and tried other tricks I could find on the internet, but nothing worked... What do I do wrong? Is there any option I have to tick so that Intellij finds the methods?
You have to put the 4 lines within a method. For simplification, I put it in main.
public class Watson
{
public static void main(String[] args)
{
ConversationService service = new ConversationService("2017-07-02");
service.setUsernameAndPassword("sss", "ttt");
NaturalLanguageClassifier n = new NaturalLanguageClassifier();
n.createClassifier("name", "en", new File("/tmp/data"));
}
}
I'm new to Spark Java framework and I'm trying to render my html file using Freemarker template engine. But I'm not able to render my css and js files.
My project structure is as follows:
./pom.xml
./src/main/java/Spark.java
./src/main/resources/css/bootstrap.css
./src/main/resources/js/bootstrap.min.js
./src/main/resources/js/app.js
./src/main/resources/templates/search.ftl
The main method is as follows:
public static void main(String[] args) {
BasicConfigurator.configure();
staticFileLocation("/css");
staticFileLocation("/Content/Images");
staticFileLocation("/fonts");
staticFileLocation("/js");
final Configuration configuration = new Configuration();
configuration.setClassForTemplateLoading(Spark.class, "/");
get("/searchview", (request, response) -> {
StringWriter writer = new StringWriter();
try {
Template searchTemplate = configuration.getTemplate("templates/search.ftl");
searchTemplate.process(null, writer);
} catch (Exception e) {
halt(500);
}
return writer;
});
}
And now when I enter url: localhost:4567/searchview, my HTML page gets rendered but the css and js is not.
In my console it says: INFO spark.http.matching.MatcherFilter - The requested route [/css/bootstrap.min.css] has not been mapped in Spark
What am I missing?
Your subsequent staticFileLocation calls will override your previously set static file locations. Create a folder called public under your src/main/resources and then place your css, fonts, js and any other static folders under there. Finally set your static file location by staticFileLocation("/public").
I just started using IronRuby. This is my test class:
class Program
{
static void Main(string[] args)
{
var path = #"C:\Users\frays\Desktop\test.rb";
var engine = Ruby.CreateEngine();
var scope = engine.Runtime.CreateScope();
scope.SetVariable("sendNext", new Action<string>(SendNext));
engine.ExecuteFile(path, scope);
Console.Read();
}
private static void SendNext(string text)
{
Console.WriteLine(text);
}
}
And this is my test script:
sendNext 'heyyy'
However, when trying to run the program it throws an exception saying wrong number of arguments (1 for 0), even though the method definitely takes a string as an argument.
This says that it is not possible Calling IronRuby from C# with a delegate but you can just call the invoke method.
sendNext.Invoke( 'heyyy')
Hi i am trying to write down a simple example of using Spring Profiles her is the code .
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles("kindergarten");
ctx.load("classpath:profile/*-config.xml");
ctx.refresh();
FoodProviderService foodProviderService =
ctx.getBean("foodProviderService", FoodProviderService.class);
List<Food> lunchSet = foodProviderService.provideLunchSet();
for (Food food: lunchSet) {
System.out.println("Food: " + food.getName());
}
}
But strange thing happens it GenericXmlApplicationContext dose not have getEnviroment() method in it's API so the third line
ctx.getEnvironment().setActiveProfiles("kindergarten");
dose not work.My STS refuses to run the main because he think this is a sintax error he gives me this message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getEnvironment() is undefined for the type GenericXmlApplicationContext
any ideas ?
thanks.
Found the answer it seems i had 3.0.6.RELEASE Spring version but Profiles where added from 3.1.0 version so all i needed to do is go to my pom.xml and change this.
<spring.framework.version>3.0.6.RELEASE</spring.framework.version>
To this
<spring.framework.version>3.1.0.RELEASE</spring.framework.version>
I'm developing a small tool based on jersey and freemarker, which will enable designers to test there freemarker templates, locally, using some mok-objects.
I'm sorry to write here, but I cant find any documentation about it except some code and javadocs.
To do that I did the following:
1 Dependencies:
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-freemarker</artifactId>
<version>1.9</version>
</dependency>
2 Starting grizzly, telling where to find freemarker templates:
protected static HttpServer startServer() throws IOException {
System.out.println("Starting grizzly...");
Map<String, Object> params = new HashMap<String, Object>();
params.put("com.sun.jersey.freemarker.templateBasePath", "/");
ResourceConfig rc = new PackagesResourceConfig("resource.package");
rc.setPropertiesAndFeatures(params);
HttpServer server = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
server.getServerConfiguration().addHttpHandler(
new StaticHttpHandler("/libs"), "/libs");
return server;
}
3 Creates the root resource and binds freemarker files:
#Context ResourceConfig resourceConfig;
#Path("{path: ([^\\s]+(\\.(?i)(ftl))$)}")
public Viewable renderFtl (#PathParam("path") String path) throws IOException {
Viewable view = new Viewable("/"+path);
return view;
}
Everything works fine, except that freemarker files are not rendered. I have an empty white page, but file exists and debugger enter inside renderFtl method right.
Do you know how can I do that?
I read a lot of articles here and around the web, but old posts only or articles talking about spring integration and I don't want to integrate it because I don't need it.
I really like Jersey, I think is one of the most complete and power framework on java world, but anytime I try to find documentation on specific features or contribs libraries, I'm lost... There no escape from groups forums :)
Where can I find a complete documentation about it?
Tanks a lot David
Updates:
Trying to solve I understood I cannot use built-in jersey support, because it needs to use files placed in resources tree. So What I did is to build freemarker configuration, in test for now, directly #runtime and returns a StreamingOutput object:
#Path("{path: ([^\\s]+(\\.(?i)(ftl))$)}")
public StreamingOutput renderFtl (#PathParam("path") String path) throws Exception {
Configuration cfg = new Configuration();
// Specify the data source where the template files come from.
// Here I set a file directory for it:
cfg.setDirectoryForTemplateLoading(new File("."));
// Create the root hash
Map<String, Object> root = new HashMap<String, Object>();
Template temp = cfg.getTemplate(path);
return new FTLOutput(root, temp);
}
FTLOutput is here:
This is not a good code, but is for test only...
class FTLOutput implements StreamingOutput {
private Object root;
private Template t;
public FTLOutput(Object root, Template t) {
this.root = root;
this.t = t;
}
#Override
public void write(OutputStream output) throws IOException {
Writer writer = new OutputStreamWriter(output);
try {
t.process(root, writer);
writer.flush();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have no errors evidence on debug and freemarker tells me that template is found and rendered, but jersey still no give me a result...
I really don't know why!
Why are you using Jersey 1.9? 1.11 is already out, you should update if you can
Have you seen "freemarker" sample from Jersey? It demonstrates simple usecase of using freemarker with jersey.
Where are your resources?
Templates are being found by calling [LastMatchedResourceClass].getResources(...), so if your templates are not accessible as resources, they can't be rendered correctly. you can checkout Jersey source and place some breakpoints into FreemarkerViewProcessor, it should tell you where exactly the problem is..