What is the purpose of the IBMBluemix.getLogger() API? - ibm-cloud

Looking at some of the sample code for hybrid mobile apps that speak to Node.js on BM (http://mbaas-gettingstarted.ng.bluemix.net/hybrid), you will see various examples that demonstrate how to use a logger on the client side:
var config = {
applicationId:'<applicationId>',
applicationRoute:'<applicationRoute>',
applicationSecret:'<applicationSecret>'
};
IBMBluemix.initialize(config).done(function(status){
// Initialize the Services
}).catch(function(err){
IBMBluemix.getLogger().error("Error intializing SDK");
});
I've confirmed this works fine in a Cordova app. My question is - why does this exist? As far as I can see, it does nothing more than wrap calls to console.log. It does not ever send logs to the Bluemix server app as far as I can tell.
There is documentation here, https://www.ng.bluemix.net/docs/starters/mobile/mobilecloud/nodejsmobile.html#log, that talks about the feature both server-side and client-side, but unless I'm missing it, there's no persistence for the client-side version.
If so - then what exactly is the point of this abstraction then? I have to imagine it was built for some reason, but I'm not seeing it.

this wrapper is used to "wrap" and to make "standard" the console log api, especially because this javascript API isn't available for all the browsers (especially old ones). By wrapping it the library could check the browser and its availability, in order to avoid an execution error
Another reasons is to wrap some configuration utilities, like providing different libraries to use (eg log4js) or other configuration, and so on.
Last but not least, probably it provide a singleton interface for performance optimization

Related

Public valid REST Api with wolkenkit.io

I am currently evaluating the framework "wolkenkit" [1] for using it in an application. Within this application I will have a user interface for tenant-based data management. Only authenticated users will have access to this application.
Additionally there should be a public REST API following common standards and being callable by public (tenant security done with submission of a tenant-based API Key within the request headers).
As far as I have found out, the wolkenkit REST API does not seem to fit these standards in forms of HTTP verbs.
But as wolkenkit at all appears to me as a really flexible and easy-to-use framework, I wonder how to basically implement such a public API.
May it be e.g. a valid approach to create an own web application which internally connects to the wolkenkit backend? What about the additional performance overhead then?
[1] https://www.wolkenkit.io/
In addition to the answer of mattwagl, I would like to point out a few things that you may be interested in.
First of all, since wolkenkit is based on CQRS, the application has a separate API for writing and reading. That means, that if you send a command (whose intent is to change state) this goes to the write API. If you subscribe for events or run a query, this goes to the read API.
This again means, that if you send a command, it's up to the write side to respond to it. As the write side is not meant to return application state, all it says is basically: "Thanks, I have received the command." To get the actual result you have to wait for the appropriate event, which means subscribing to the read API.
In the wolkenkit documentation there is a nice diagram which shows this in a clear way:
If you now add a separate REST API (which actually fulfills the requirements of REST), this means that you need to handle waiting for the result internally. In other words: Clients in wolkenkit are always meant to be asynchronous, REST is not. Hence it's your job to handle the asynchronous behavior of the wolkenkit APIs in your REST API. I think that this is the hardest part.
Once you have done this, you will have a synchronous REST API, and of course it will have some overhead. But I think that since its overhead is limited to passing through and translating network requests, it should be negligible.
Oh, and finally, there is another thing that you have to watch out for: Since REST as it was meant originally relies on the HTTP verbs to transport semantics, you need to map GET / POST / PUT / DELETE to the semantic commands of wolkenkit. As long as this can be done 1:1, everything's fine – problems start when there are multiple commands that (technically speaking) do an UPDATE.
PS: I'm also one of the developers of wolkenkit.
PPS: However you are going to solve this, I would be highly interested to hear from you! It would be very great if you could share your experiences with us, as you are most probably not the last one with this idea. If you want to contact us, the easiest way would be via Slack.
wolkenkit applications can be accessed using an HTTP- and a Websocket-API. These APIs are both provided by the tailwind module that wolkenkit uses under the hood. In the tailwind repo you can find a very simple documentation of the available HTTP routes.
You're right, the wolkenkit HTTP-API is not a classic REST-API. It's more RPC-style which in our experience is a good fit for applications. There are only 3 routes that your clients/tenants need to support: /v1/command (POST) is used for issuing commands. The commands you post should follow the command schema. /v1/events (POST) can be used for streaming events to clients. These events will follow the event schema. Finally you have /v1/read/:modelType/:modelName (POST) to read models. You can simply use HTTPie to test these routes.
Authentication of these APIs is currently done using OpenID-Connect. There's a very detailed article on how to setup authentication using Auth0. I'm not quite sure if this fits your use-case but you could basically use any Authentication Service that follows this standard or that is able to issue JWT tokens.
Finally you could also build your own JavaScript client-SDK that runs inside browsers by building a module that uses the wolkenkit-client-js under the hood. This SDK can just use the same API as any other client to connect to your application.
Hope this helps.
PS: Please note that I am one of the authors of wolkenkit.

play framework app authentication, user management

Following the Book App example in play 2 for scala, I now have a basic working app.
What I want now is to add some features like
User registration
User authenetication to access some pages
What is the best way to do it in play for scala? Should I manage it by my own? is there a plugin for that?
Note: I'm the maintainer of Silhouette.
I can suggest you Silhouette which is a core only fork of Secure Social with the intention to built a more customizable, non-blocking and well tested implementation.
For the first stable version there are only two open issues which must be resolved. And these issues are only future requests. There are no API changes planed. The documentation must be improved and a sample application is started. The unit tests are also a good starting point.
If you plan to follow the authentication flow as stated by Secure Social then stick with it. It exists since more than two years and it is well tested by many companies. Otherwise take a look at Silhouette.
You have two options:
Secure Social (http://securesocial.ws/)
But it has unusual registration flow, where the user have to enter your email first, and receive link to registration form.
However, there is a pull request that address this issue (https://github.com/jaliss/securesocial/pull/260)
Play Authenticate
It doesn't support Scala out of the box. But there is a workaround created by me here: https://github.com/joscha/play-authenticate/issues/92
Both of them requires you to write the interface layer to database. An important drawback in both of them, is that you won't be able to make use of reactive database drivers like Reactive Mongo. they assume that you will return the results immediately, not a Future of the result.
There is a securesocial plugin (http://securesocial.ws). Covers most common authentication methods, has registration stuff. I found it very usefull.
The drawback is it's documentation. If you want to do something a bit differ from the simplest scenarios - be prepared to read through the source code.

A good way to structure AngularJS client code with Play 2.1 as backend

I own a Play 2.1 application.
Initially, I used the default template mechanisms from Play 2.1 until I .. learned AngularJS.
Now, I clearly want my client side to be an AngularJS app.
However, while surfing the net, I find there are no clear way to achieve it:
Letting Play behave as a simple RESTful application (deleting the view folder) and making a totally distinct project to build the view (AngularJS app initialized by grunt.js).
Advantage: Likely to be less messy, and front and backend teams would work easily separately.
Drawback: Need another HTTP server for the AngularJS app.
Try to totally integrate AngularJS app with the traditional Play's workflow.
Drawback: With a pretty complex framework like AngularJS, it would lead to a confusion of templates managementfor instance : scala.html (for Play) / tpl.html (for Angular) ... => messy.
Making a custom folder within the play project but distinct from the initial folders created by the Play scaffolding. Let's call it myangularview instead of traditional view for instance. Then, publish static contents generated by grunt.js into the Play's public folder, in order to be reachable from browser through Play's routing.
Advantage: SRP between components is still fairly respected and no need to use another light HTTP server for the client-side like in 1.
I pointed out my own views of advantage and drawbacks.
What would be a great way to achieve the combination of Play with Angular?
Yes, I'm answering to my own question :)
I came across this way of doing:
http://jeff.konowit.ch/posts/yeoman-rails-angular/
Rails?? No matter the framework is, the need remains exactly same.
It advocates a real separation between APIs (backend side), and front-end side (in this case making AJAX calls to backend server).
Thus, what I've learned is:
During development phase, a developer would use two servers: localhost on two distinct ports.
During production phase, the front-end elements would be encompassed into the whole backend side (the article would deal with a kind public folder, aiming to serve static contents: HTML, angular templates (for instance), CSS etc... Advantage? => dealing with a one and unique serving server's APIs exposition as well as static assets for the UI.
With this organization, some tools like Yeoman would be able to bring some really awesome handy things to developers like for instance: the livereload feature. :):)
Of course, during development phase, we end up with two different domains, (localhost:3000 and localhost:9000 for instance) causing issues for traditional ajax requests. Then, as the article points out, a proxy may be really useful.
I really find this whole practice very elegant and pleasant to work with.
There was an interesting discussion on the play mailinglist a couple of days ago about frontend-stack/solution, could be something in it for you, quite some people using angular it seems: https://groups.google.com/forum/#!searchin/play-framework/frontend/play-framework/IKdOowvRH0s/tQsD9zp--5oJ

Adapter Proxy for Restful APIs

this is a general 'what technologies are available' question.
My company provides a web application with a RESTful API. However, it is too slow for my needs and some of the results are in an awkward format.
I want to wrap their restful server with a proxy/adapter server, so when you connect to the proxy you get the RESTful API I wish the real one provides.
So it needs to do a few things:
passthrough most requests
cache some requests
do some extra requests on the original server to detect if a request is cacheable
for instance: there is a request for a field in a record: GET /records/id/field which might be slow, but there is a fingerprint request GET /records/id/fingerprint which is always fast. If there exists a cache of GET /records/1/field2 for the fingerprint feedbeef, then I need to check the original server still has the fingerprint feed beef before serving the cached version.
fix headers for some responses - e.g. content-type, based upon the path
do stream processing on some large content, for instance
GET /records/id/attachments/1234
returns a 100Mb log file in text format
remove null characters from files
optionally recode the log to filter out irrelevant lines, reducing the load on the client
cache the filtered version for later requests.
While I could modify the client to achieve this functionality, such code would not be re-usable for other clients (different languages), and complicates the client logic.
I had a look at whether clojure/ring could do it, and while there is a nice little proxy middleware for it, it doesn't handle streaming content as far as I can tell - the whole 100Mb would have to be downloaded. Also it doesn't include any cache logic yet.
I took a look at whether squid could do it, but I'm not familiar with the technology, and it seems mostly concerned with passing through requests rather than modifying them on the fly.
I'm looking for hints where I might find the correct technology to implement this. I'm mostly language agnostic if learning a new language gets me access to a really simple way to do it.
I believe you should choose a platform that is easier for you to implement your custom business logic on. The following web application frameworks provide easy connectivity with REST APIs, and allow you to create a web application that could work as a REST proxy:
Play framework (Java + Scala)
express + Node.js (Javascript)
Sinatra (Ruby)
I'm more familiar with Play, of which I know it provides utilities for caching you could find useful, and is also extendable by a number of plugins.
If you are familiar with Scala, you could have a also have a look at Finagle. It is a framework build be Twitter's infrastructure team to provide protocol-agnostic connectivity. It might be an overkill for REST to REST proxy, but it provides abstractions you might find useful.
You could also look at some 3rd party services like Apitools, which allows to create a proxy programmatically (in lua). Apirise is a similar service (of which I'm a co-founder) that intends to do provide similar functionalities with a user-friendly UI.
Beeceptor does exactly what you want. It plugs in-between your web-app and original API to route requests.
For your use-case of caching a few responses, you can create a rule. That way it shall not hit the original endpoint.
The requests to original APIs can be mocked, and you can inspect response
You can simulate delays.
(Note: it is a shameless plug, I am the author of Beeceptor and thought it should help you and other developers.)
https://github.com/nodejitsu/node-http-proxy is looking useful - although I don't yet know if it can stream process for transcoding.

How to expose a RESTful Web Service using Meteor

How would you go about creating a restful web service using Meteor. I would like to create apps in Appcelerator that hook into the same backend.
Can Meteor solve this problem?
I did a full write-on on this in Meteorpedia:
http://www.meteorpedia.com/read/REST_API
The post reviews all 6 options for creating REST interfaces, from highest level (e.g. smart packages that handle everything for you) to lowest level (e.g. writing your own connectHandler).
Additionally the post covers when using a REST interface is the right or wrong thing to do in Meteor, references Meteor REST testing tools, and explains common pitfalls like CORS security issues.
I originally answered this question here, but to recap:
For adding RESTful methods on top of your data, look into the Collection API written for Meteor:
https://github.com/crazytoad/meteor-collectionapi
As for authentication for accessing the database, take a look at this project:
https://github.com/meteor/meteor/wiki/Getting-started-with-Auth
Both are definitely infantile in development, but you can create a RESTful API and integrate it with a mobile native client pretty easily.
I know this is an old thread, but in case anyone stumbles across it, I published a package for writing REST APIs in Meteor 0.9.0+:
https://github.com/kahmali/meteor-restivus
It was inspired by RestStop2 and built with Iron Router's server-side routing. In my not-so-humble opinion, it's a better solution than anything posted here thus far.
UPDATE: To clarify why I think it's a "better" solution than those mentioned, I'll just point out the differences between each:
CollectionAPI:
CollectionAPI is limited to exposing very basic CRUD operations on your collections. For my use, which is consuming the REST API in mobile apps, it can be extremely wasteful to send down entire documents, and most of the time I need to do some additional processing of data (for instance, sending a Google Cloud Message in a REST endpoint for adding a friend, but only if the friend is successfully added). CollectionAPI gives you a hook that runs before the endpoint is executed, but from what I understand there is nothing immediately before the response, so you have no way of modifying the data that is returned. For authentication, CollectionAPI allows you to define an authToken that must be passed with each request. This acts more like a traditional api key, as it appears to be hard-coded into your app, and would therefore be the same for every user.
Restivus, since it is not limited to automated work on collections, gives you complete control over your endpoints. It now provides all the functionality included in Collection API. It supports user authentication and role permissions as well, so you can identify the user making the request (and easily access that user from within authenticated endpoints). It provides a login and logout endpoint as well to assist with that. I will provide a code example for Restivus at the end.
HTTP.publish:
From what I understand, this is similar to CollectionAPI in that it is limited to exposing basic CRUD operations on collections. This one is more specifically tied to Meteor's publishing, and allows you use a publish function for handling GET requests. I'm confused by the documentation, but it may or may not have some basic authentication available. I haven't used this before, but I'm not a big fan of the API for it, which feels a bit clunky. Once I'm publishing more extensively I'll try to revisit it. The same team has another package called HTTP.methods which doesn't give you the access to the publish functions, but has a similar api to Restivus and, at the time, similar functionality.
Restivus is "better" because it doesn't limit you to using your publish functions, and therefore allows for a much finer-grained control over your endpoints. If you are just looking to expose your publish functions to an external API, I would recommend you stick with HTTP.publish. Restivus also has a simpler API and supports the HTTP PATCH method (which no other package seems to acknowledge exists). Their HTTP.methods package is pretty similar to Restivus, except it lacks PATCH support, and although it offers some basic authentication, I believe you only have the ability to make all endpoints authenticated, or none. Restivus will allow you to control that on a per-endpoint (not just per-route) level. Role permissions (e.g., user, admin) on endpoints are also available on Restivus, but I don't see anything about that for HTTP.methods.
Meteor Router:
This has been deprecated in favor of Iron Router, please see below.
Iron Router:
Iron Router is awesome, but it is not specifically designed for building REST APIs. Recently they added functions corresponding to the HTTP methods (GET, POST, etc.), but they don't support any form of authentication, and all you have access to is the lower-level Node request and response objects, so you'll be forced to learn how to work with those. Once you do, you'll find that there is some repetitive work to be done in each endpoint, like creating responses with the proper headers and response codes. You'll also have to worry about CORS compliance if your API is being consumed from the browser.
Restivus is actually built on top of Iron Router, and provides a layer of authentication on endpoints. It also abstracts away the need for direct interaction with the Node request and response objects, although they're still there in case we've missed anything. So it's using all the awesomeness of Iron Router with a higher-level API for your coding pleasure. Restivus is great if you're already using Iron Router, since it won't add any additional dependency.
RestStop2:
I was actually using RestStop2 in a project I'm working on when it was deprecated in favor of Iron Router. They had solid documentation, and an API I preferred above the others. Per their suggestion, I built a new package on top of Iron Router, which is very much inspired by RestStop2. Restivus is now being endorsed on the RestStop2 GitHub page, so I think they agree that it's a worthy replacement.
Here's a little code snippet from the Quick Start section of the Restivus docs:
if(Meteor.isServer) {
Meteor.startup(function () {
// Global configuration
Restivus.configure({
useAuth: true,
prettyJson: true
});
// Generates: GET, POST on /api/users and GET, DELETE /api/users/:id for
// Meteor.users collection
Restivus.addCollection(Meteor.users, {
excludedEndpoints: ['deleteAll', 'put'],
routeOptions: {
authRequired: true
},
endpoints: {
post: {
authRequired: false
},
delete: {
roleRequired: 'admin'
}
}
});
// Maps to: POST /api/articles/:id
Restivus.addRoute('articles/:id', {authRequired: true}, {
post: {
roleRequired: ['author', 'admin'],
action: function () {
var article = Articles.findOne(this.urlParams.id);
if (article) {
return {status: "success", data: article};
}
return {
statusCode: 400,
body: {status: "fail", message: "Unable to add article"}
};
}
}
});
});
}
Anyone stumbling across this now (2013+), checkout the Meteor Router smart package, which provides methods for server side routing useful in creating RESTful interfaces.
Meteor.Router.add('/404', [404, "There's nothing here!"]);
To assist you in future searches, be sure to take a look at https://atmosphere.meteor.com - a smart package repository. And Meteorite is a pretty handy CLI tool for version and package management.
The most elegant solution appears to be HTTP.publish. Rather than invent a new API like the others, it simply adds the HTTP protocol to the existing Meteor publish interface. This means, for example, that Meteor.allow and Meteor.deny work automatically for HTTP as well as DDP.
Example:
If handed a collection and a publish function the HTTP.publish will mount on the following URLs and methods:
GET - /api/list - all published data
POST - /api/list - insert a document into collection
GET - /api/list/:id - find one published document
PUT - /api/list/:id - update a document
DELETE - /api/list/:id - remove a document
myCollection = new Meteor.Collection('list');
// Add access points for `GET`, `POST`, `PUT`, `DELETE`
HTTP.publish(myCollection, function(data) {
// this.userId, this.query, this.params
return myCollection.find({});
});
It does not yet handle authentication completely.
I suppose you probably could create a RESTful service using Meteor, but it's not really what the framework is intended for -- one of the main benefits of Meteor is tight interaction between the client and the server, and a web service doesn't have a client side. I'd recommend looking into either writing a web service back end in node.js on its own or something like https://github.com/intridea/grape if you like Ruby.
Yes, you can expose REST endpoints with Meteor using the private API. The functionality will become public soon, but in the meantime, see Can I mount another route handler through ____meteor_bootstrap____.app?.
I know this is an old topic, but instead of using any external package, you can use the Meteor WebApp package:
https://docs.meteor.com/packages/webapp.html.
Hope it helps!
I thought I would update the conversation for 2014. I still haven’t found the perfect way to implement REST services in Meteor and I’m hoping someone can point me in another direction to investigate. I’ve tested 3 projects and each have their drawbacks:
meteor-router
I worked with meteor-router but the github page says it will only be fixing bugs going forward and to use Iron Router on all new projects. I’m still considering using this since if it works for me as-is then upgrades aren’t necessary except for some type of authentication.
iron-router
I have a simple example service built using Iron Router but it appears to support REST services even less than meteor-router and causes the server to crash if someone posts invalid json to rest endpoint.
meteor-collectionapi
Exposes a REST api for basic CRUD operations are support but it doesn’t appear to support queries other than by id.