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.

Monday 5 June 2017

Create a java web application using embedded tomcat

Create a java web application using embedded tomcat


"Embedded" means that your program ships with the server within it as opposed to a web application being deployed to external server.
With embedded server your application is packaged with the server of choice and responsible for server start-up and management. You can run your web program like a regular java program. You can create war or executable jar file to execute your web program.
From the user standpoint the difference is:
  • Application with embedded server looks like a regular java program. You just launch it and that's it.
  • Regular web application is usually a war archive which needs to be deployed to some server but in this case server resides within program.

Steps to create java web application using embedded tomcat.


Create a java web application using embedded tomcat


Step 1: Create a maven project EmbeddedTomcatExample.

Step 2: Add below dependency in pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.embedtomcat</groupId>
  <artifactId>EmbeddedTomcatExample</artifactId>
  <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <tomcat.version>9.0.0.M6</tomcat.version>
    </properties>
    
    <dependencies>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>         
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-logging-juli</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper-el</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <version>${tomcat.version}</version>
        </dependency>        
        
    </dependencies>    
    
    <build>
    
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId>
                <version>1.1.1</version>
                <configuration>
                    <assembleDirectory>target</assembleDirectory>
                    <programs>
                        <program>
                            <mainClass>com.embedtomcat.embedded.EmbeddedTomcatExample</mainClass>
                            <name>webapp</name>
                        </program>
                    </programs>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>    
    </build>
    <name>EmbeddedTomcatExample</name>
</project>

This pom.xml defines the dependencies that you’ll need to run Tomcat in an embedded mode.

The last 3 entries are only required for applications that use JSP files. If you use this technique for an application that doesn’t use JSPs then you can just include the first 3 dependencies.

There is also a single plugin defined. The appassembler plugin generates a launch script that automatically sets up your classpath and calls your main method (created below) to launch your application. 
Step 3: Create JSP file.

We will display content of this JSP file on browser. For example, I created index.jsp file inside webapp folder. You need to create webapp folder in parallel of java folder. 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>JSP file</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <p>
            This is a simple JSP file to test EmbeddedTomcat.            
        </p>
    </body>
</html>
Step 4: Create main method.

Add a launcher class EmbeddedTomcatExample which have main method, which is responsible to add webapp in tomcat container and start tomcat server.
import java.io.File;

import javax.servlet.ServletException;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

public class EmbeddedTomcatExample {

 public static void main(String[] args) throws LifecycleException, InterruptedException, ServletException {

  String docBase = "src/main/webapp/";

  Tomcat tomcat = new Tomcat();
  String webPort = System.getenv("PORT");
        if(webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }
        tomcat.setPort(Integer.valueOf(webPort));

  tomcat.addWebapp("/", new File(docBase).getAbsolutePath());
   System.out.println("configuring app with basedir: " + new File("./" + docBase).getAbsolutePath());

  tomcat.start();
  tomcat.getServer().await();
 }

}

Step 5: Run application.

We can run this program directly from eclipse for testing purpose or create runnable jar and execute this command (java -jar EmbeddedTomcatExample.jar) in command editor.


Create a java web application using embedded tomcat

When we choose option for program to run as Java application, below logs print on console.
Jun 05, 2017 1:11:03 PM org.apache.catalina.core.StandardContext setPath
WARNING: A context path must either be an empty string or start with a '/' and do not end with a '/'. The path [/] does not meet these criteria and has been changed to []
configuring app with basedir: C:\EmbeddedTomcat\EmbeddedTomcatExample\.\src\main\webapp
Jun 05, 2017 1:11:04 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jun 05, 2017 1:11:04 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 05, 2017 1:11:04 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Jun 05, 2017 1:11:04 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/9.0.0.M6
Jun 05, 2017 1:11:05 PM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
INFO: No global web.xml found
Jun 05, 2017 1:11:06 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 05, 2017 1:11:07 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [449] milliseconds.
Jun 05, 2017 1:11:07 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler [http-nio-8080]

When you see this info log (INFO: Starting ProtocolHandler [http-nio-8080]) in console, you can hit below URL on browser. If your system is already use 8080 port, you can change with other port like 9090.

http://localhost:8080/

Create a java web application using embedded tomcat

This example you can download.

Sunday 21 May 2017

Hibernate one to many mapping example using set

Hibernate one to many mapping example using set


In this tutorial we are going to understand how to use XML to map a one-to-many association between Java objects and database tables using Hibernate framework. We will create a sample Hibernate-based application to manage the following entity relationship:



  1. Creating sample database and tables
  2. Required Jars for project
  3. Coding Hibernate Model Classes
  4. Creating Hibernate Mapping Files
  5. Writing Hibernate Configuration File
  6. Coding a Test Program
  1.  Creating sample database and tables
   Execute the following script in MySQL Workbench’s SQL Editor to create a database                     
   called cartdb with two tables named cart and items:

create database cartdb;
use cartdb;
 
CREATE TABLE `cart` (
  `cart_id` int(11) NOT NULL AUTO_INCREMENT,
  `total` int(11) NOT NULL,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`cart_id`)
);
 
CREATE TABLE `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
   `cart_id` int(11) NOT NULL,
  `item_id` int(11) NOT NULL,
  `item_total` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  
  PRIMARY KEY (`id`),
  KEY `fk_cart` (`cart_id`),
  CONSTRAINT `fk_cart` FOREIGN KEY (`cart_id`) REFERENCES `cart` (`cart_id`)
);


2. Required Jars for project

   
hibernate-core-4.2.2.Final.jar
hibernate-commons-annotations-4.0.2.Final.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
jboss-logging-3.1.0.GA.jar
antlr-2.7.7.jar
dom4j-1.6.1.jar
javassist-3.15.0-GA.jar

3. Coding hibernate model classes

Create two JavaBean-style classes Cart.java and Items.java to model the two tables cart and items, respectively.

File net\engineeernitesh\hibernate\Cart.java:

package net.engineeernitesh.hibernate;
 
import java.util.Set;
 
public class Cart {
 
    private long id;
    private long total;
    private String name;
 
    private Set<Items> items;
 
    public Category() {
    }
 
    public Category(Long total,String name) {
     this.total = total;
        this.name = name;
    }
 
    // getters and setters...
 
}


File net\engineeernitesh\hibernate\Items.java:

package net.engineeernitesh.hibernate;
 
public class Items {
    private long id;
    private Cart cart;
    private long item_id;
    private long item_total;
    private long quantity;
     
    public Items() {
    }
 
    public Items(Cart cart,Long item_id,Long item_total,Long quantity) {
        this.cart = cart;
        this.item_id = item_id;
        this.item_total = item_total;
        this.quantity = quantity;
    }
 
 
    // getters and setters...
 
}

4. Creating hibernate mapping files

Create two XML files Cart.hbm.xml and Items.hbm.xml to tell Hibernate how to map the JavaBean classes above with the database tables.

File net\engineeernitesh\hibernate\Cart.hbm.xml:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="net.engineeernitesh.hibernate">
    <class name="Cart" table="CART">
        <id name="id" column="CART_ID">
            <generator class="native"/>
        </id>
  <property name="total" column="TOTAL" />
        <property name="name" column="NAME" />
 
        <set name="items" inverse="true" cascade="all">
            <key column="CART_ID" not-null="true" />
            <one-to-many class="Items"/>
        </set>
    </class> 
</hibernate-mapping>


File net\engineeernitesh\hibernate\Items.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="net.engineeernitesh.hibernate">
    <class name="Items" table="ITEMS">
        <id name="id" column="ID">
            <generator class="native"/>
        </id>
  <many-to-one name="cart" class="Cart"
            column="CART_ID" not-null="true"/>
        <property name="item_id" column="ITEM_ID" />
        <property name="item_total" column="ITEM_TOTAL" />
        <property name="quantity" column="QUANTITY" />
                
    </class> 
</hibernate-mapping>

5. Writing Hibernate Configuration File

Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type, connection details and the mapping files:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>       
  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/cartdb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">secret</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
     
    <mapping resource="net/codejava/hibernate/Cart.hbm.xml"/>
    <mapping resource="net/codejava/hibernate/Items.hbm.xml"/>
       
  </session-factory>
</hibernate-configuration>


6. Coding a Test Program

Following is code of the test program that persists some sample data:

package net.engineeernitesh.hibernate;
 
import java.util.HashSet;
import java.util.Set;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
 
/**
 *
 * This program demonstrates using Hibernate framework to manage a
 * bidirectional one-to-many association.
 * @author www.engineeernitesh.blogspot
 *
 */
public class CartManager {
 
    public static void main(String[] args) {
        // loads configuration and mappings
        Configuration configuration = new Configuration().configure();
        ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
        registry.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
         
        // builds a session factory from the service registry
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
         
        // obtains the session
        Session session = sessionFactory.openSession();
        session.beginTransaction();
         
        Cart cart = new Cart(2,"Shopping");
         
        Items bag = new Items(cart,1,2,5);
  
        Items book = new Items(cart,2,4,5);
         
             
        Set<Items> items = new HashSet<Items>();
        items.add(bag);
        items.add(book);
                 
        cart.setItems(items);
         
        session.save(cart);
         
        session.getTransaction().commit();
        session.close();       
    }
}


Related Topics:



Saturday 20 May 2017

How to use subquery in hibernate criteria

How to use subquery in hibernate criteria


For example, think of a Cart system where we have another table for Items. A cart can have multiple items, so here we have one to many mapping. From below example we will find all Cart which have Items quantity 5.


SQL Query : select * from Cart where Cart.cart_id in (
    select Items.cart_id from Items where Items.quantity = 5)

We can get same result by using DetachedCriteria in Criteria.

DetachedCriteria userSubquery = DetachedCriteria.forClass(Items.class, "items")
    // Filter the Subquery
    .add(Restrictions.eq(Items.quantity, 5))
    // SELECT the Cart Id  
    .setProjection(Projections.property("items.cart_id") );
And the main query:

Criteria query = session.createCriteria(Cart.class, "cart")
    .add(Subqueries.propertyIn("cart.cart_id", userSubquery) );

Tuesday 25 April 2017

IBM Websphere mq error code list