Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

Sunday, 2 September 2018

How to create charts and dashboard for MongoDB in JSReport

How to create charts and dashboard for MongoDB in JSReport

We have various open source tools like Power BI, Pentaho, Tableau, Qlik sense etc available which provides platform to create charts but all these support some limited features to use on free version and need to pay for using full functionality so today I am going to introduce one open source JSReport which is purely based on java script and can create any kind of Reports and charts and can integrate with client application.

In this tutorial we will go through with following:

  • How we can create various reports and charts like Bar chart, Pie chart etc in JSReport. 
  • How JSReport create API of templates.
  • Ho we can call JSReport API from Ruby application.
  • Ho we can display chart in Angular page.


JSReport is an open source platform for designing and rendering various reports.

JSReport is a reporting server which lets developers define reports using javascript templating engines (like jsrender or handlebars). It supports various report output formats like html, pdf, excel and others. It also includes advanced reporting features like user management, REST API, scheduling, designer or sending emails.


You can find more information on the official project website https://jsreport.net

Prerequisite:

1. Node.js(>=8.9)
2. MongoDB
3. RestClient gem

Knowledge required:

1. Node.js
2. Mustache.js
3. MongoDB
4. Ruby
5. Angular JS
6. Handlebar template engine
7. Chart.js
8. API

Step 1: how to install and run JSReport server

Open Node.js command prompt and type as below:
How to create charts and dashboard for MongoDB in JSReport
Once JSReport start than you can reach on default port 5488. You can use URL like https://localhost:5488/ and this will look like below:
How to create charts and dashboard for MongoDB in JSReport

Step 2: how can connect with MongoDB.

Need to install MongoDB driver first as per below:

How to create charts and dashboard for MongoDB in JSReport

Next we need to create a custom node.js script accessing our mongodb and loading data what we need. The script creation and evaluation is handled by jsreport standard scripts extension and it can look like this:

How to create charts and dashboard for MongoDB in JSReport

Here, maindb is database name, people is collection and result stored in req.data.

How to create charts and dashboard for MongoDB in JSReport

Step 3: How can create chart using chart.js

Now we can use req.data in handlebar template engine for data but here I will use JSON for demonstration.

<html>
  <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js'></script>
  </head>
  <body>
    
    <canvas id='myChart' style="margin-top:30px"></canvas>
    
    <script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
        datasets: [{
          label: 'apples',
          data: [12, 19, 3, 17, 6, 3, 7],
          backgroundColor: "rgba(153,255,51,0.4)"
        }, {
          label: 'oranges',
          data: [2, 29, 5, 5, 2, 3, 10],
          backgroundColor: "rgba(255,153,0,0.4)"
        }]
      },
      options: {
            animation: {
                onComplete: function () {
                    // set the PDF printing trigger when the animation is done
                    // to have this working, the phantom-pdf menu in the left must
                    // have the wait for printing trigger option selected
                    window.JSREPORT_READY_TO_START = true
                }
            }
        }
    });
    </script>    
  </body>
</html>
when we will run report it would look like below:

How to create charts and dashboard for MongoDB in JSReport

Step 4: How can get JSReport API definition

How to create charts and dashboard for MongoDB in JSReport


How to create charts and dashboard for MongoDB in JSReport

Here we have POST URL : https://localhost:5488/api/report and unique template shortid for this report is ry6nmoEVQ.

Step 5: How can call this API from Ruby application.

def create_report(payload)
    url = 'https://localhost:5488/api/report'    payload = {template:{shortid:'ry6nmoEVQ'},data: payload}

    begin      result = RestClient::Request.execute(:method => :post,
                                           :url => url,
                                           :payload => payload,
                                           :user => 'admin',
                                           :password => "********",
                                           :headers => {"Content-Type" => 'application/json',"Accept" => 'application/json'})
      json = result.body.to_json

      json    rescue RestClient::Exception => e      puts "Error"      puts e.http_code
      puts e.http_body
    endend
Using RestClient gem we can call JSReport API and will pass same information which we got from JSReport. We can pass our custom data as payload in API definition.

We can get this payload value in JSReport beforeRender method using req.data.

Step 6: how can show API result in Angular page.

Above json will return whole HTML, we need to place script and HTML where you want to show in your application.
   

Sunday, 14 January 2018

Forwarding messages from one ActiveMQ to another in Ruby on Rails

How to Forward messages from one ActiveMQ to another


Apache ActiveMQ is an open source message broker written in Java together with a full Java Message Service (JMS) client. It provides "Enterprise Features" which in this case means fostering the communication from more than one client or server.

In the enterprise, ActiveMQ is celebrated for its flexibility in configuration, and its support for a relatively large number of transport protocols, including OpenWire, STOMPMQTTAMQP, REST, and WebSockets.

ActiveMQ uses transport connectors over which it communicates with message producers and consumers. However, in order to facilitate broker to broker communication, ActiveMQ uses network connectors

A network connector is a bridge between two brokers which allows on-demand message forwarding. 

In other words, if Broker B1 initiates a network connector to Broker B2 then the messages on a channel (queue/topic) on B1 get forwarded to B2 if there is at least one consumer on B2 for the same channel. If the network connector was configured to be duplex, the messages get forwarded from B2 to B1 on demand. 

Prerequisites

  1. ActiveMQ 5.15.2 – To create broker instances (download from here)
The following diagram shows how a network connector functions. It bridges two brokers and is used to forward messages from Broker-1 to Broker-2 on demand if established by Broker-1 to Broker-2.


Setup network connector between broker-1 and broker-2


Step 1: Create bridge-demo folder under downloaded apache-activemq-5.15.2 folder and create two broker instances, say broker 1 and broker 2 folder inside bridge-demo folder.



Step 2: Copy everything from downloaded apache-activemq-5.15.2 folder and put in broker 1 and broker 2 folder.



Step 3: Since we will be running both brokers on the same machine, let's configure broker-2 such that there are no port conflicts. 

Edit \apache-activemq-5.15.2\bridge-demo\broker-2\conf\activemq.xml as below.

  • Add brokerName as broker-2. <broker xmlns="http://activemq.apache.org/schema/core" brokerName="broker-2" dataDirectory="${activemq.data}">
  • Edit transportConnectors tag as

<transportConnectors>
            <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61626?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="amqp" uri="amqp://0.0.0.0:6672?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://0.0.0.0:61623?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
</transportConnectors>
Edit \apache-activemq-5.15.2\bridge-demo\broker-2\conf\jetty.xml as below.

<bean id="jettyPort" class="org.apache.activemq.web.WebConsolePort" init-method="start">
             <!-- the default port number for the web console -->
        <property name="host" value="0.0.0.0"/>
        <property name="port" value="9161"/>
</bean>
Step 4: Configure Network Connector from broker-1 to broker-2 Add the following XML snippet to \apache-activemq-5.15.2\bridge-demo\broker-1\conf\activemq.xml

<networkConnectors>
         <networkConnector 
            name="Q:broker1->broker2" 
   uri="static:(tcp://localhost:61626)" 
   userName="admin"
            password="admin"
            duplex="false" 
            decreaseNetworkConsumerPriority="true" 
            networkTTL="3">
            <staticallyIncludedDestinations>
              <queue physicalName="test"/>
            </staticallyIncludedDestinations>
         </networkConnector>
</networkConnectors>
Step 5: Based on your system configuration go to win32 or win64 folder of broker-2 and click on activemq.bat


                               webconsole for broker-2 available on http://localhost:9161/


Step 6: Go to broker-1 folder of win32 or win64 and click on activemq.bat


                                   webconsole for broker-1 available on http://localhost:8161/


You can check network connectors on Connectios and Network tab on web console of broker-1. Username and password would be admin.




You can check connector openwire on Connectios tab on web console of broker-2. Username and password would be admin.


Step 7: Add gem stomp in Gemfile. gem 'stomp'

Step 8: Create publisher.rb file and add below code.

require 'rubygems'require 'stomp'
client = Stomp::Client.new("admin","admin","localhost",61613,true)

client.publish "/queue/test", "Hello world", { :persistent => true }
client.close
Step 9: Run publisher.rb


Step 10: Create consumer.rb file and add below code.

require 'rubygems'require 'stomp'
client = Stomp::Client.new("admin","admin","localhost",61623,true)

client.subscribe("/queue/test") do | message |
  puts messageendclient.join
Step 9: Run consumer.rb








Thursday, 21 September 2017

Stepwise setup rails 5 with Mongoid gem

Stepwise setup rails 5 with Mongoid gem

In this tutorial we will discuss about how to setting up Rails 5 with MongoDB and MongoID.

Prerequisite: MongoDB must install in your local system.
To check installation of MongoDB, type http://localhost:27017/ on your browser, if you receive below message than you are good to go. 

Stepwise setup rails 5 with Mongoid gem


Step 1: Create your Rails app with the '--skip-active-record' switch.

rails new mongopoc --skip-active-record
Stepwise setup rails 5 with Mongoid gem



You will get directory structure.

The --skip-active-record is important because it doesn't include ActiveRecord in the app that is generated.

Step 2: Edit the gemfile  and add below gem to include mongodb.
gem 'mongo','~>2.4.1'
gem 'mongoid','~>6.1.1'

Stepwise setup rails 5 with Mongoid gem

Step 3: Run a command bundle install --local to install the gem in your app.

Go to your rails project path using cmd and run bundle install --local

bundle install --local
Stepwise setup rails 5 with Mongoid gem
 

Run command gem list and check mongo and mongoid in list.

gem list
Stepwise setup rails 5 with Mongoid gem
Step 4: Configure your app to support mongo db

rails g mongoid:config
Stepwise setup rails 5 with Mongoid gem

Check your 'application.rb' file and make sure that inside the 'class Application' there is the line " Mongoid.load! './config/mongoid.yml' ". It's sometimes not included when the config is generated, but it's needed to use Mongoid.

Step 5: Create a new model with attributes.

rails g scaffold employee name:String age:Integer
Stepwise setup rails 5 with Mongoid gem

Step 6: Delete //= require_tree from application.js 

Stepwise setup rails 5 with Mongoid gem


Step 7: Start server and insert values

rails sever 

Stepwise setup rails 5 with Mongoid gem

**Make sure your mongoDB is up and running. You can check URL in routes.rb. In our case it is employees so we will hit http://localhost:3000/employees and insert some values.

Stepwise setup rails 5 with Mongoid gem
Step 8: Check database for the inserted values.

show dbs;
Stepwise setup rails 5 with Mongoid gem

use mongopoc_development;
Stepwise setup rails 5 with Mongoid gem

show collections;
Stepwise setup rails 5 with Mongoid gem

db.employees.find();
Stepwise setup rails 5 with Mongoid gem



Related Post:

Step by step tutorial installing Ruby on Rails 5 on Windows

Step by step tutorial installing Ruby on Rails 5 on Windows


This tutorial will walk you through installing this on a development environment on Windows.

1. Install Ruby on local system.

Most of the stuff you will do from the command line, to get the command line in windows, go to start menu/run and type “cmd”. You will also need to have an Internet connection during the installation as most stuff is getting updated via the Internet.

Latest ruby version you can download from here 

If you are going to install 2.4.X than no need to install Development KIT. It’s very easy to install. When installing, click check boxes that ask you to associate Ruby with .rb files and add Ruby to the PATH. Do remember where you installed Ruby, it will come in handy later. Once installed, from the command line type.

ruby -v
Step by step tutorial installing Ruby on Rails 5 on Windows

and you should see something like this: ruby 2.4.1p111 (2017-03-22 revision 58053) [x64-mingw32]. If you see “Command not found”, make sure that you reload the command (close & open new) window after the install.

You can run a Ruby statement at the command prompt by using -e option by typing …

ruby -e "puts 'This is ruby test'"
Step by step tutorial installing Ruby on Rails 5 on Windows


2. Update Gems: A gem is a Ruby package.  And RubyGems is like a package manager/installer.
To make sure that you have the latest version of Ruby Gems you can update it by …

gem update --system
It could take 2-3 mins to update. Once updated, from the command line type.

gem -v
Step by step tutorial installing Ruby on Rails 5 on Windows

3. Install Rails: Simply type in cmd: 

gem install rails
Step by step tutorial installing Ruby on Rails 5 on Windows

When our installation completed, we had new gems installed.   Run “gem list” again and see a whole bunch of new gems were installed.  It includes the Rails gem as well as gems like actionpack and activerecord and others that are part of Rails.

Once installation completed, run below command in cmd:

rails -v
Step by step tutorial installing Ruby on Rails 5 on Windows

4. Create your first Rails project:

Make a new directory, let's creates Demo. In your cmd type “cd path/to/your Demo folder”

We are now going to generate a new Rails application. At the command prompt, navigate to the Demo folder.  It is best to generate your Rails app here.We’ll call our Rails app "rubypoc", so we type …
rails new rubypoc
Step by step tutorial installing Ruby on Rails 5 on Windows


By default this will create the rubypoc Rails application set to use the sqlite database.  If you wanted it to use MySQL or other database, then you type …

rails new rubypoc -d mysql
The “-d mysql” tells Rails that we intend to use MySQL database for this app.  If we had left it out, it would have defaulted to using SQLite for the database.

See that it had created the "rubypoc" folder in “Demo”.  This is your rails application.  If you ever want to delete this Rails application, delete the "rubypoc" folder.

Step by step tutorial installing Ruby on Rails 5 on Windows


Inside the rails application is a “public” folder.  This is the Rails public folder that will be exposed to the public via the webserver.

5. Run WebServer:

Rails comes with its own web server, so no need to set up apache. The default web server is Puma.
Now goto rubypoc folder using cd rubypoc in cmd and run below command.

rails server
Step by step tutorial installing Ruby on Rails 5 on Windows

You might get a Windows Security Alert, we choose to select the options as shown below and allow access.

Step by step tutorial installing Ruby on Rails 5 on Windows



From the Puma console, we see that Puma webserver started on port 3000.  It also tells us to use Ctrl-C to stop server.

6. Run application in browser: 

we can point our browser to http://localhost:3000 to see our first Rails web application.  localhost is same as 127.0.0.1 which is the IP address to refer to own local development machine. 

You should see the Rails page.

Step by step tutorial installing Ruby on Rails 5 on Windows



Bingoooo...you are up for rails project.

In next tutorial, I will discuss on how MongoDB will configure with Rails project.