Thursday, October 27, 2016

Storing and Viewing Image file in MongoDb

package com.test.siddhu;

import java.io.File;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

public class MongoDBImage {

public static void main( String args[] ) {

try{

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("siddhudb");


//DBCollection table = db.getCollection("user");

String newFileName = "siddhu-new-image-name";
File imageFile = new File("C:\\workspace-mongodb\\MongoDbProject\\src\\com\\test\\siddhu\\image\\siddhu.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();

//String newFileName = "mkyong-java-image";
//GridFS gfsPhoto = new GridFS(db, "photo");
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
System.out.println(imageForOutput);

}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}

}

Note: You can also use MongoDB IDE for the same. As we are using sqldeveloper/TOAD etc for oracle and mysql DB.

http://www.mongobooster.com/downloads

MongoDB CRUD Operation using JAVA

1:- Insert Data inside MongoDb:
package com.test.siddhu;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoDBConnectionClass {

public static void main( String args[] ) {

try{

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("siddhudb");
DBCollection table = db.getCollection("user");
BasicDBObject document = new BasicDBObject();
document.put("name", "Siddharatha Dhumale");
document.put("age", 37);
document.put("createdDate", new Date());
table.insert(document);

}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
image5

2:- Update Data inside MongoDb
package com.test.siddhu;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoDBConnectionClass {
public static void main( String args[] ) {
try{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("siddhudb");
DBCollection table = db.getCollection("user");
BasicDBObject query = new BasicDBObject();
query.put("name", "Siddharatha Dhumale");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "Siddharatha Dhumale changed");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
image6
3:- Delete Data inside Mongodb
package com.test.siddhu;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoDBConnectionClass {
public static void main( String args[] ) {
try{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("siddhudb");

DBCollection table = db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "Siddharatha Dhumale changed");
table.remove(searchQuery);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

image7
Note :- Same can also be done using MongDb shell
https://docs.mongodb.com/getting-started/shell/

Installation of Mongo DB and accessing it using JAVA

Note: We are using Window O/S hence using msi for installation. Please chose version as per your O/S.
Step 1:- Install Mongo by downloading it from below url
https://www.mongodb.com/download-center#community
image1

This will create MongoDb Server in your machine at below given position
C:\Program Files\MongoDB\Server\3.2\bin
Step 2: Make entry of C:\Program Files\MongoDB\Server\3.2\bin in System and Env Variable. So that we can access it from cmd prompt.
Step 3:- Create a folder \data\db inside c: folder
i.e. C:\data\db
Step 4:- Run mongod command in side this folder
C:\data\db>mongod
server will be started with below line
2016-10-27T13:11:17.862+0530 I NETWORK [initandlisten] waiting for connections on port 27017

Step 4:- Run mongo command from another cmd prompt and you will see mongo is able to connect
image2
Step 5:- Create your own Database first using following belwo comman
use siddhudb
Step 6:- to see numbers of db we can use show dbs commands i.e. show dbs. Same way if you want to see current working database just enter db command i.e. db and it will show below output
image3
Step 7:- Your Created database (siddhudb) is not present in list when we type show dbs command. Reason is to display database we need to insert at least one document into it.
db.user.insert({"name":"siddhartha dhumale"})
You will see one data is inserted.
> db.user.insert({"name":"siddhartha dhumale"})
WriteResult({ "nInserted" : 1 })
>
Now when you enter show dbs command it will show you our created db.
> show dbs
local 0.000GB
siddhudb 0.000GB
>

Step 8:- Lets try to connect this db using java class. First you need to download required driver for the same. Use below given link. Make sure we had following in our class path
mongodb-driver-3.0.1.jar :- http://mongodb.github.io/mongo-java-driver/?_ga=1.55182892.626961242.1477037916
mongodb-driver-core-3.0.1.jar:-https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver-core/3.3.0/
bson-3.3.0.jar :- https://oss.sonatype.org/content/repositories/releases/org/mongodb/bson/3.3.0/
Step 9:- We are using eclipse IDE. Use below given programe to test connection to Mongo using java code. This will display output as name of db we had in our Mongo.
package com.test.siddhu;
import java.util.List;
import com.mongodb.DB;
import com.mongodb.MongoClient;
public class MongoDBConnectionClass {

public static void main( String args[] ) {

try{

// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

List dbs = mongoClient.getDatabaseNames();
for(String dbase : dbs){
System.out.println(dbase);
}

}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
image4

Tuesday, October 25, 2016

Calling Web Service using Angular JS


Step 1:- Create a web dynamic Project and convert the same to AngulrJS using belwo option
Right Click Project --> Configure --> Convert to AngularJS Project
Step 2:- Create a simple html file
WebContent folder ->New ->HTML
and add following code
<!–script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js”>&lt;!–/script> –>
<!–script src=”lib/angular.min.js”><!–/script>
<!–script src=”js/angularwebservicedemo.js”><!–/script>
<!–article ng-app=”booksInventoryApp”>
<!–section ng-controller=”booksCtrl”>
<!–h2 ng-repeat=”book in data.books”>{{book.name}}<!–/h2> 
<!–/section>
<!–/article>
Step 2:- Create a js folder inside webcontent folder and create a js file inside it with below code\
/**
*
*/
var app = angular.module('booksInventoryApp', []);
app.controller('booksCtrl', function($scope, $http) {
$http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks")
.then(function(response) {
$scope.data = response.data;
});
});
image7
Note: You can also get the same code from below
http://stackoverflow.com/questions/30625002/getting-data-from-a-web-service-with-angular-js

Angular JS Project using Eclipse

Step :-1 Install Eclipse
Step 2:- Go to market place of Eclispe and search for Angular JS and install that package in your Eclipse
image1
Step 3:- Create a web dynamic Project and convert the same to AngulrJS using belwo option
Right Click Project --> Configure --> Convert to AngularJS Project
image2
Step 3:- Create a simple html file
WebContent folder ->New ->HTML
and add following code
 <!--!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <!--html ng-app="siddhudemoApp">
 <!--head>
 <!--meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <!--title>Siddhu AngularJs Demo<!--/title>
 <!--script src="lib/angular.min.js"><!--/script>
 <!--script src="js/angulardemo.js"><!--/script>
 <!--/head>
 <!--body>
  <!--div ng-controller="siddhudemoCtrl">
   <!--table border="1">
    <!--tr>
     <!--td>Display the name<!--/td>
     <!--td ng-bind="name"><!--/td>
    <!--/tr>
    <!--tr>
     <!--td>Display the surname<!--/td>
     <!--td ng-bind="surname"><!--/td>
    <!--/tr>
   <!--/table>
  <!--/div>
 <!--/body>
<!--/html>
Step 4:- Create a js folder inside webcontent folder and create a js file inside it with below code\
/**

*/
var app = angular.module("siddhudemoApp", []);
app.controller("siddhudemoCtrl", function($scope) {
$scope.name = "Siddhartha";
$scope.surname = "Dhumale";
});

Step 5:- Create a lib folder inside webcontent folder and put angular.min.js inside it.
You can download the same from
Image3.png
Step 6:- Excute the same on Server i.e. Tomcat and see the output
image4

image5

Monday, October 24, 2016

Calling REST W/S using NodeJS


Follwing code given belwo can be used to call REST W/S using NodeJS
/**
* New node file
*/
var Client = require('node-rest-client').Client;

var client = new Client();

// direct way 
client.get("http://services.groupkt.com/country/get/iso2code/IN", function (data, response) {
// parsed response body as js object 
console.log(data);
// raw response 
console.log(response);
});

// registering remote methods 
client.registerMethod("getIndiaCountryName", "http://services.groupkt.com/country/get/iso2code/IN", "GET");

client.methods.getIndiaCountryName(function (data, response) {
// parsed response body as js object 
console.log("Data----------"+data);
// raw response 
console.log("response----------"+response);
});
//
/*
* console.log(data); will give you belwo output.
{ RestResponse: 
{ messages: 
[ 'More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm',
'Country found matching code [IN].' ],
result: { name: 'India', alpha2_code: 'IN', alpha3_code: 'IND' } } }
*/
Note: Make sure to install node-rest-client module in your application. Command to install the same
npm install node-rest-client

How to call SOAP Web service using NODEJS

Use below code to call SOAP Web service using Nodejs
var soap = require('soap');
var url = 'http://localhost:8181/ScrumProjectWebService/services/ExposeWebService?wsdl';

var args = {sprintId: '1'};
soap.createClient(url, function(err, client) {
//To find what would be the below line to call method of webservice use the url of SOAPUI Tool
client.ExposeWebService.ExposeWebServiceHttpSoap12Endpoint.getKPI(args, function(err, result) {
console.log(result);
});
});
image6


image7
Note: Make sure you have soap module installed in yout Project else install it using below command
npm install soap

MYSQL CRUD Operation using NodeJS

Step -1 Create Server.js file

var http = require('http'),
util = require('util'),
fs = require('fs'),
url = require('url'),
qs = require('querystring');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'siddhu',
password : 'siddhu',
database : 'vscrum'
});
var server = http.createServer(function (req,res){
var url_parts = url.parse(req.url,true);
//console.log(url_parts);
var body = '';
if(req.method === 'POST'){
// res.end('post');
console.log('Request found with POST method');
req.on('data', function (data) {
body += data;
console.log('got data:'+data);
});
req.on('end', function () {
var POST = qs.parse(body);
// use POST
res.end("Sent data are id:"+POST.id+" name:"+POST.name);
});

} else {
console.log('Request found with GET method');
req.on('data',function(data){ res.end(' data event: '+data);});
if(url_parts.pathname == '/')
fs.readFile('./form.html',function(error,data){
console.log('Serving the page form.html');
res.end(data);
});
else if(url_parts.pathname == '/getData'){
console.log('Serving the Got Data.');
getData(res,url_parts);
}
//update
else if(url_parts.pathname == '/getDataForUpdate'){
console.log('Updating the Got Data.');
getDataForUpdate(res,url_parts);
}
//Delete
else if(url_parts.pathname == '/getDataforDelete'){
console.log('Deleting the Got Data.');
getDataforDelete(res,url_parts);
}
}
});
server.listen(1234);
console.log('Server listenning at localhost:1234');
function getData(res,url_parts){
console.log("Data submitted by the user id:"+url_parts.query.id+" and name:"+url_parts.query.name);
res.end("Data submitted by the user id:"+url_parts.query.id+" and name:"+url_parts.query.name);
connection.connect();
//insert into vscrum.nodejstable values ('1','sid')
//connection.query('SELECT * FROM vscrum.kpi', function(err, results)
var posts = {
id: url_parts.query.id,
name: url_parts.query.name
};
connection.query('INSERT INTO vscrum.nodejstable SET ?',posts, function(err, results)
{
if (err)
{
console.error(err);
}
else
{
console.log('First row of department table : ', results[0]);
}
});
connection.end();
}
//Update
function getDataForUpdate(res,url_parts){
console.log("Data submitted for Update by the user id:"+url_parts.query.id+" and name:"+url_parts.query.name);
res.end("Data submitted for Update by the user id:"+url_parts.query.id+" and name:"+url_parts.query.name);
connection.connect();
//update vscrum.nodejstable set name='siddharatha' where id = '1'
//connection.query('SELECT * FROM vscrum.kpi', function(err, results)
var posts = {
id: url_parts.query.id,
name: url_parts.query.name
};
//connection.query('UPDATE users SET Name = ? WHERE UserID = ?', [name, userId])
connection.query('UPDATE vscrum.nodejstable SET name=? where id=?',[url_parts.query.name,url_parts.query.id], function(err, results)
{
if (err)
{
console.error(err);
}
else
{
console.log('Row updated: ', results[0]);
}
});
connection.end();
}

//Delete
function getDataforDelete(res,url_parts){
console.log("Data submitted for Delete by the user id:"+url_parts.query.id+" and name:"+url_parts.query.name);
res.end("Data submitted for Delete by the user id:"+url_parts.query.id+" and name:"+url_parts.query.name);
connection.connect();
//delete from vscrum.nodejstable where id='2'
//connection.query('SELECT * FROM vscrum.kpi', function(err, results)
var posts = {
id: url_parts.query.id,
name: url_parts.query.name
};
connection.query('DELETE FROM vscrum.nodejstable where id=?', [url_parts.query.id], function(err, results)
{
if (err)
{
console.error(err);
}
else
{
console.log('Row deleted: ', results[0]);
}
});
connection.end();
}

Step -2 Create Form.html as given below
'-
'-
'-
'- Untitled Document
'-
'-
'-
'-

'-
'-
'-

'-
'-
'-

'-
'-
'-

'-

'-
'-


image5image4

Thursday, October 20, 2016

NodeJS Http GET Example

var http = require('http');
http.get("http://www.google.com", function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});

Result :- Got response: 302

NodeJS HTTP Example to fetch value from Form/Screen

var http = require('http');
var uhtml = 
'Post Example' +
'' +
'Fetching Values from Form/Screen using Node JS
'+

'
' +

'Name :
' +

'Surname :
' +

'' +
'
' +
'';
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log('Posted Data: ' + body);
res.writeHead(200);
res.end(uhtml);
});
}).listen(1234);

image3

MySQL Connection using NodeJS and How to resolve Error: Cannot find module 'mysql'

var mysql = require('mysql'); 
var connection = mysql.createConnection({ 
host : 'localhost', 
user : 'siddhu', 
password : 'siddhu', 
database : 'vscrum' 
}); 
connection.connect(); 
connection.query('SELECT * FROM vscrum.kpi', function(err, results) 

if (err) 

console.error(err); 

else 

console.log('First row of department table : ', results[0]); 

}); 
connection.end();
Note: How to resolve Error: Cannot find module 'mysql'
Above statement says that your project did not get mysql module to execute.
If you are working on window or linux resolutions is same. As i am using Window and my project TestSiddhuNodeJs is in C:\workspace-nodejs\ use follwing below command to execute
Step 1:- Go to C:\workspace-nodejs\TestSiddhuNodeJs
Step 2:- Execute npm install mysq
C:\workspace-nodejs\TestSiddhuNodeJs
`-- mysql@2.11.1
+-- bignumber.js@2.3.0
+-- readable-stream@1.1.14
| +-- core-util-is@1.0.2
| +-- inherits@2.0.3
| +-- isarray@0.0.1
| `-- string_decoder@0.10.31
`-- sqlstring@2.0.1
npm WARN enoent ENOENT: no such file or directory, open 'C:\workspace-nodejs\TestSiddhuNodeJs\package.json'
npm WARN TestSiddhuNodeJs No description
npm WARN TestSiddhuNodeJs No repository field.
npm WARN TestSiddhuNodeJs No README data
npm WARN TestSiddhuNodeJs No license field.
Step 3:- Execute your programe and see the result.

Wednesday, October 19, 2016

Executing Simple Node Js program using Syns, Async and CallBacks


1- Sync method
//Simple way to Read File Sync Way
var fs = require('fs');
var content = fs.readFileSync("SiddhuReadMe.txt", "utf8");
console.log(content);
console.log('Reading file text from JS file...');

2- Async Method
In below example we are calling the txt files Async i.e. we are not waiting for function readFile() to complete then execute console.log('Reading file text from JS file...'). We execute console.log and then we display output of readFile once we get the values
//Simple way to Read File ASync Way
var fs = require('fs');
fs.readFile("SiddhuReadMe.txt", "utf8", function(err, content) {
if (err) {
return console.log(err);
}
console.log(content);
});
console.log('Reading file text from JS file...');
3- Callbacks
Call back stands for calling one function from anther. Here in below example we are calling or passing function name as argument i.e. SiddhuMycontent function() from readingfile().
In below example all out code get executed and then we get the reply from our txt files that state that we are not waiting for callback function to execute.
Best scenario to use callback approach is when user want to download the big files and we don;t want our application to stop executing. i.e. we want our application to run parallel while file is downloading.
//Simple way to Read File Callback way i.e. calling function from another function
var fs = require('fs');
var fcontent ;
function readingfile(callback){
fs.readFile("SiddhuReadMe.txt", "utf8", function(err, content) {
fcontent=content;
if (err)
{
return console.error(err.stack);
}
callback(content);
})
};
function SiddhuMycontent() {
console.log(fcontent);
}
readingfile(SiddhuMycontent);
console.log('Reading file text from JS files....');

image2

Nodejs Installation and Configuration with Eclispe

- Download Nodeclipse from below given location
http://www.nodeclipse.org/
or You can also try belwo given URL to drag drop in your Eclipse. We had used Mars version of Eclipse.
https://marketplace.eclipse.org/content/nodeclipse
- Download latest version of Node.js from
https://nodejs.org/en/
- Window, Linux and MAc version are available
https://nodejs.org/en/download/
- Window :- https://nodejs.org/dist/v6.9.1/node-v6.9.1-x64.msi
For window Once you installed Nodejs it will create nodejs inside Program Files folder of C:\
C:\Program Files\nodejs
Make sure you had node.exe and npm.cmd inside this folder.
- Add this in your PATH to make Nodejs available on cmd prompt by adding following line your system path.
C:\Program Files\nodejs\
- Check availability of Node js using following command on command prompt
node --version
- This will display the version of installed NodeJs.
- Open your above nodeclipse and bydefault it will come with inbuild Node js. If you want to use latest Node js use configure your Eclipse using below screen.
Window --> Preference --> NodeEclipse

nodejs