How can I make an HTTP request from a Sling ESP page? Is there something like JQuery or Node's http module that I can use? Or do I have to fall back to Java code?
(Sling ESP Pages are server side JavaScript pages running in the Rhino JavaScript engine)
When sling implements a script language it provides a limited set of bindings to commonly used objects. These are defined here:
http://sling.apache.org/apidocs/sling5/org/apache/sling/api/scripting/SlingBindings.html
In addition, Rhino implements several features to provide integration with java. Such as the Packages variable which contains all the top level java packages, such as java and com.This provides you with a way to interact with java directly from the esp, an example being.
Packages.java.util.Calendar.getInstance()
The details of this java interaction can be found here:
https://developer.mozilla.org/en-US/docs/Rhino/Scripting_Java?redirectlocale=en-US&redirectslug=Scripting_Java
So to answer your question.
No, there isn't a supplied http module for you to use.
Your options are:
Forgo the esp and write a java servlet.
Use the Rhino/Java integration to write the HTTP call in the esp file using the relevant java objects.
Encode the HTTP code into a re-usable OSGi service and use the java integration to access the service
My recommendation would be option 3 as it provides the best code portability, and is the closest to what I would consider the "sling" way of doing things. To access the service you would just use:
var service = sling.getService(Packages.foo.bar.HttpClient.class);
There's no out-of-the box service that you can use to make HTTP requests from a Sling script, but if an HTTP client bundle (such as those from http://hc.apache.org/) makes its classes available you can use them in any Sling script.
As JE Bailey says, that wouldn't be the most convenient thing so you could write an OSGi wrapper service to make this easier. And maybe contribute that to Sling (hint, hint ;-)
If you want to make requests to Sling itself you can use the SlingRequestProcessor service which bypasses HTTP and makes internal requests to Sling directly.
Related
I'm thinking of switching from PHP to using Node.js for developing my website. However, after researching Node.js for a little while, I can't seem to find exactly how to write a webpage with Node. I see that you use response.write() in Node to write html to your webpage, but that seems like a tedious thing to do, having your entire webpage as a string literal in your node file. How does web development work in Node as opposed to PHP's method of embedding the script into the HTML file?
You don't necessarily need to use response.write for each line of the view, you can use template engines as well. Search for "node.js template engines". At first impression it could seem tedious, but a similar approach prevents you from writing bad code.
PHP is a scripting language, node is a platform built on javascript.
To start web development using node.js, at first you have to understand what makes node different. Node gives you a way to make async calls to your database (which is a very simplified explanation), which you can then wrap in nice html and send (route) it to the browser. Alternatively, you can use something like angular.js in the frontend and use node.js to make db requests and response which is picked up by angular.js which updates the front html. If you like the idea of Single page app with async calls to fetch data, use node with angular. The tutorial that I like is https://scotch.io/tutorials/creating-a-single-page-todo-app-with-node-and-angular Hope this helps!
As others have answered, there exist templating engines for Node. With the current trends in web development, most modern web frameworks encourage the separation of code from the view (or the HTML you deliver to the client). For instance, Ruby's ERB templates, Jinja2 in Python, Handlebars/Jade for Node, and now a lot of modern PHP frameworks support this as well (Zend/Slim).
Another main difference is in how they work and how the languages are designed. PHP is an object oriented language supporting classes, inheritance, member visibility, interfaces, etc. Node.js is Javascript, so using prototypical inheritance.
The communities and ecosystems are different as well. Modern PHP tends to embrace the use of the Composer package manager, and that came after PEAR. However, npm is the official node package manager and it is deeply integrated with the platform. It is trivial to search for new packages and then use them in your projects.
The main architectural difference is that Node is also asynchronous by design, meaning it runs in a single thread and can potentially handle much more connections than PHP on systems with limited memory. When a request comes in to a PHP application, all the services/controllers and everything you defined have to be reinstatiated, you define PHP files and let Apache/Nginx process them. In Node you have a node process which you can proxy outside requests to.
Node.js Provides so many modules to do these things there is framework called express for node.js http://expressjs.com/ You can use a templating engine and create views. some examples are like ejs or jade. It doesnt have to be a string.
PHP is very strongly orientated towards creating web pages from a template, while Node.js is lower-level and broader in scope. A very rough overview of the differences between PHP and Node.js:
In PHP, you'd start a web server (almost certainly Apache), and then put a PHP file in a directory where you want to serve something from. You might use some fancy .htaccess directives to make URLs nicer, etc.
In Node.js you create a script, in which you use the http module to start a web server, and then you supply a callback for whenever a request is made to your server. Deciding which page to respond to the request with, etc, is all your work to do.
In PHP, things like routing a request to a particular PHP file, compression, decoding POST and GET variables, are all done by using Apache - your PHP files are sort of just like templates which Apache runs whenever a request is received. In Node.js, everything, from starting the server to sending HTML, is all done within your Node.js script - you have to do everything.
HTML isn't the first class citizen in Node.js that it is PHP. Generally, in Node.js you are just sending strings to the client. There are plenty of third party templating tools for Node.js - but they will be dependencies, not builtin functions.
I've been coding JS for a few years, and am now learning more. Seeing a lot of employers asking for "knowledge of REST APIs" or "experience consuming RESTful services."
I know the basics of AJAX, both in native JS and jQuery. I've done a fair bit 'o goggling on REST, both on SO and the web. There seems to be a ton of info on how to build RESTful APIs server-side with JAVA, C#, etc, but little on how to access those services with JavaScript.
Here are questions:
Is "consuming RESTful services" another way of saying "getting data from a server with AJAX", or something else altogether?
If it is something else, where are some good tutorials on the subject?
Once I get the basics down, where can I find RESTful APIs on the web to consume?
Is "consuming RESTful services" another way of saying "getting data from a server with AJAX", or something else altogether?
No, not at all, but you certainly could consume your own REST API using AJAX. Ajax typically just means xmlHttpRequest, which is inherently a web browser concept. A RESTful API is more like a service interface. In many ways, it's a web service, but without the complexity of SOAP.
Essentially, REST is a way of expressing a transaction or query over HTTP by using verbs and nouns. For example, to get information, you use... wait for it... GET! To put information, you use PUT (or POST, the tutorials below will explain the difference). And to delete something, you use DELETE. It's rather neat. It almost reads like a sentence over HTTP:
GET /users/123
DELETE /users/123
You can guess what those would do.
Because these are just HTTP requests, they can often be consumed using AJAX, however, that is not necessary. In fact, I find REST API's more useful for exposing services or data to other applications, again, just like a web service.
If it is something else, where are some good tutorials on the subject?
It's hard to give a good tutorial on consuming RESTful services because of two reasons:
Each service is different.
It depends on what language / platform you are working in.
Bret's answer mentioned a few good tutorials.
Here is a SO answer which shows a way to consume REST directly in Java: How to consume REST in Java
Here is a reasonable tutorial on how to create a RESTful API using the JAX-RS API in Java and then shows how to consume it: http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/
I've also had good success with Jersey's REST client. Their REST (JAX-RS) server software is a royal pain (in my opinion), but their client is pretty slick.
I wrote a simple proof-of-concept todo list REST API last spring in Java and the integration tests show good use of the Jersey client to consume the API for testing purposes.
https://github.com/brandonramirez/todo-api/blob/master/src/test/java/com/brandonsramirez/todoApi/TaskResourceTest.java
I'm also a fan of the Unirest client, which is a REST client translated into several languages with a similar interface. They have an Objective-C version, a Java version, a JavaScript / node.js version, a .NET version, etc.
If an employer is looking for experience with consuming REST API's, they probably want five things:
Do you understand the basic semantics of exchanging data over HTTP using the various methods and the design patterns, naming conventions, etc. that go with it along with it?
Do you recognize the de facto standards for mapping CRUD operations onto HTTP requests (like using GET /resources to list all resources, POST /resources to create a new resource, PUT /resources/x to update resource X, etc.)?
Are you familiar with the various HTTP response codes and when/how they would be used? Like can you always assume that a successful response yields a 200 status code? If you create a new resource, is there another commonly used status code (yes, there is)?
Have you actually written any code to consume an existing service?
Can you test a service easily? For example, using curl to create issue an HTTP request very precisely.
And a bonus, but most people don't have a good grasp of this (I struggle to understand its usefulness personally), is hyper-media for versioning by twiddling with the Accepts header.
Once I get the basics down, where can I find RESTful APIs on the web to consume?
All over! Everybody has one! Twitter, Facebook, Twilio, Stripe, Google, Edmodo, Amazon. I could go on forever. In the IaaS world, Amazon Web Services and Rackspace Cloud both offer RESTful API's for managing your cloud infrastructure. For example, I can make an HTTP POST request to a URL that represents my set of servers, and boom, a new server (virtual machine) is provisioned to me.
https://stripe.com/docs/api
https://api.imgur.com/
There are so many that there are even hub services to help consumers find API's and providers to publish them, such as Mashape and Mashery, though the latter appears to be more focused on providers than consumers, judging from their web site.
The github project I posted earlier, with my proof-of-concept, accesses a REST API from Searchly and Twilio so that I can search for tasks, and when one is marked complete, send me a text message, again, all from HTTP requests. However, I used the client libraries from those providers rather than using direct HTTP libraries just to make the code leaner and more focused, without worrying about all of the HTTP plumbing.
For your purposes, hitting a restful API will be very similar to interacting with a server via regular AJAX. The difference is that this API will conform to the restful model, where various CRUD-like operations will conform to REST's particular pattern of using specific HTTP verbs [GET, PUT, POST, DELETE] and also its pathing model of referring to an entity.
Have a look:
http://www.restapitutorial.com/lessons/httpmethods.html
If you want to have a play with a restful API, there's a few frameworks out there where you can spin up your in a few minutes.
I'd probably use Sinatra for this; although there many options:
http://www.andrewhavens.com/posts/20/beginners-guide-to-creating-a-rest-api/
Just google "restful api example [your server-side language of choice]; there's a lot of material out there.
In short order you'll want to explore how cross server side scripting is done with a restful API, and how to use JSONP:
http://www.ibm.com/developerworks/library/wa-aj-jsonp1/
Am new to ExtJS Direct and DirectJNgine. The relation between them confuses me. I cannot get the overview picture.
What I know is:
ExtJS is a JavaScript framework focusing on UI design. It supplies plethora APIs for programmers. I can call these APIs without bitter.
From the official site:
Ext Direct is a platform and language agnostic technology to remote server-side methods to the client-side. Ext Direct allows for seamless communication between the client-side of an Ext JS application and all popular server platforms.
My think is: ExtJS Direct is also a subset of the APIs supplied the ExtJS team for us to use. These APIs can facilitate our work on calling server side method. But I want to dig into a little bit.
Server side method can be any language method, like JAVA C++ PHP etc. Direct APIs handle all possibilities to support different server side language methods?
From the official site:
DirectJNgine (or DJN, for short), is a Java based implementation of the Ext Direct API for ExtJs.
ExtJs is probably one of the most powerful and attractive UIs for web-based applications, as can be seen here, as well as in many other examples. DirectJNgine makes it much easier to use the full power of Java business classes with such a powerful front-end, making Java methods directly callable from the client.
Since ExtJS Direct is already implemented the APIs for seamless remote method invoking. Why DirectJNgine need to implement these ExtJS Direct APIs? What does "a java based implementation of the Ext Direct API for ExtJs" mean?
I'd add server-side to the definition DirectJNgine:
DirectJNgine is an Open Source library that provides a Java-based implementation of the server-side Ext Direct API.
Ext Direct is a javascript framework and resides on client and let's you call any server API. The call is made via HTTP - that's why it's not dependent on the server language. You formulate a HTTP request, not a Java/PHP/any other request.
Server API handles the HTTP request and can be implemented in Java, C++, PHP, .Net etc. One of the Java implementations is DirectJNgine. It runs on server and responses to Ext Direct calls.
In your project you can use both Ext Direct and DirectJNgine for communication between client and server. They don't overlap, they cooperate with each other on the opposite sides of the network.
And you'd use some framework for the presentation layer (ExtJS maybe) and some framework for server business/storage/other layers (to make use of DirectJNgine it would be a Java framework).
Extjs needs to know the URL, the methods and the parameter count for the possible actions and this is provided by for example DirectJNgine.
The API also takes care of messaging between ExtJS and JAVA , i.e. converting incoming JSON objects to JAVA methods (Json with method names and parameters is passed to JAVA methods, their can be multiple actions in one call). And passing back the result from the JAVA methods in JSON format.
I did a bit of digging into extdirectspring when I realised some strange stuff was going on and wanted to know why. Effectively what extdirect does is provide a description of the server side methods to the client in the form of json (+ possibly through other mediums).
On the client side you end up with objects built from this json that know how to call the server code. In the java (extdirectspring) implementation this creates a static variable in your program's namespace for each of the java classes decorated with the 'ExtDirectMethod' attribute. This variable seems to always be the class name with the first letter lowercased. I had a bit of a dig and this appears to be by coincidence - the name comes from the bean name in spring and is not defined by extdirectspring.
In extdirectspring the setup works through the ether (through the servlet + spring) (have yet to bottom out exactly how this works) and it is predefined to respond to requests for api.js (among other things). This then returns the configuration object which is assigned to a static variable in the ext namespace. By default this variable is called REMOTING_API.
To get the client side stuff to know about what the server has to offer you need to put in a call like:
Ext.direct.Manager.addProvider(Ext.app.REMOTING_API);
after extjs has fired up.
I've been using a couple RESTful APIs for server to server interactions recently and am now thinking about communicating directly with a RESTful API via javascript from within a web browser in my web application.
This would mean using ajax within a web page to talk to my web server using GET, POST, PUT and DELETE requests and the server responding with appropriate http status codes and non-html data (probably json)
Is this generally considered good practice for a web application and why?
It doesn't matter if you are consuming an RPC API or RESTful API from the ajax standpoint, but generally, you can think of a RESTful API as a well-organized, well-namespaced set of remote procedural calls.
Is this generally considered good practice for a web application and
why?
It is useful to do things this way because you don't need to duplicate code in order to have regular CRUD operations across multiple data objects.
Another thing to consider is that if you have a uniform naming convention of API calls that you can write AJAX functions to interact with, you will write and maintain much less code over time in your javascript side of the application, assuming you don't do anything weird in your code.
An example of when / how this would be a good practice would be if you had written a base method designed to automatically determine your AJAX url depending on what you're doing and where you are, and it automatically determines what POST method to use depending on the type of operation... then you literally write one ajax function, and apply it to things rather than write fully separate ajax methods per action item.
Is it possible to subscribe to a JMS, and receive messages from within a node.js app? Is there a node.js module that will allow this, like the amqp module for amqp messages?
Currently the messages are received by a Java app. However, I am trying to switch to javascript.
Thanks
Short answer:
No.
Longer answer:
JMS is nothing but an API interface specification in Java. You cannot really use JMS without Java. So, to use generic JMS (any vendor), you need to have some Java glue code (such as seam, or something more custom made) between the JMS implementation and your JavaScript (node.js) app.
AMQP, on the other hand, is more than an API. It's actually a standardized wire protocol, and could therefore be implemented in any language. JMS does not have this luxury.
That said, there might be options for you if you choose to go with specific vendors.
I know out of my head that Apache ActiveMQ has AJAX support, and the same goes (at least partially) for IBM WebSphere MQ as well as JBoss HornetQ (http://www.jboss.org/hornetq/rest.html).
Other options, other than REST/AJAX, is trying to implement or find implementations of the different Wire protcols different JMS vendors uses. For Apache QPid which supports AMQP, this would be easy. STOMP is another lightweight protocol supported by multiple JMS implementations, such as ActiveMQ and HornetQ that you can find node.js/java script libraries for around the Internet.
A more time consuming option would be to write an extension to node.js using a specific implementation C/C++ API (if there is any..) and connect using that. It would (probably) be more reliable than the REST/AJAX approach but also way more time consuming