REST etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
REST etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

4 Mart 2015 Çarşamba

Node.js, Express ve MongoDB ile basit bir RESTful web servis yazma

Node yüklü değilse yükleyin.
C:\node klasörü açın.

Express yoksa yükleyin. Varsa update edin:
npm update -g express
npm update -g express-generator

Son olarak bir proje klasörü yaratın:
express nodetest2

oluşan package.json dosyasına ilave yapalım:
"jade": "*",
        "mongodb": "*",
        "mongoskin": "*"

proje klasörüne girelim. dependencyleri yükleyelim:
npm install

proje klasörü içine veritabanı için bir klasör açalım:
mkdir data

views klasöründe layout.jade açalım. İlave edelim:
script(src='http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')
        script(src='/javascripts/global.js')

/public/stylesheets/style.css üzerine şuradaki içeriği kopyalayalım:
http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/style.css

views klasöründe index.jade i açalım. Şöyle değiştirelim:
extends layout

block content
    h1= title
    p Welcome to our test

    // Wrapper
    #wrapper

        // USER LIST
        h2 User List
        #userList
            table
                thead
                    th UserName
                    th Email
                    th Delete?
                tbody
        // /USER LIST

    // /WRAPPER

Konsola dönüp node serveri başlatalım:
C:\node\nodetest2\> npm start

http://localhost:3000 açtığımızda basit bir sayfa görürüz.

Mongo daemonu çalıştıralım:
C:\mongo\> mongod --dbpath c:\node\nodetest2\data

Yeni bir konsol açıp Mongoya bağlanalım:
C:\mongo\>mongo

Mongo konsolundan yeni bir db yaratalım:
use nodetest2

Kullanıcı listesi ekleyelim:
db.userlist.insert({'username' : 'test1','email' : 'test1@test.com','fullname' : 'Bob Smith','age' : 27,'location' : 'San Francisco','gender' : 'Male'})

C:\node\nodetest2\app.js açalım. bodyParser ın hemen altına ekleyelim:
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/nodetest2", {native_parser:true});

Sonra app.use('/', routes); satırının hemen üzerine ekleyelim:
// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});

C:\node\nodetest2\routes\users.js açalım. 
/* GET users listing. */
router.get('/', function(req, res) {
  res.send('respond with a resource');
});
Bu kısmı silip yerine yazalım:
/*
 * GET userlist.
 */
router.get('/userlist', function(req, res) {
    var db = req.db;
    db.collection('userlist').find().toArray(function (err, items) {
        res.json(items);
    });
});

Node serveri yeniden başlatalım:
C:\node\nodetest2\> npm start

http://localhost:3000/users/userlist açalım. Tek bir kayıt görürüz.

/nodetest2/public/javascripts/global.js dosyası yaratalım ve içeriği yazalım:
// Userlist data array for filling in info box
var userListData = [];

// DOM Ready =============================================================
$(document).ready(function() {

    // Populate the user table on initial page load
    populateTable();

});

// Functions =============================================================

// Fill table with data
function populateTable() {

    // Empty content string
    var tableContent = '';

    // jQuery AJAX call for JSON
    $.getJSON( '/users/userlist', function( data ) {

        // For each item in our JSON, add a table row and cells to the content string
        $.each(data, function(){
            tableContent += '<tr>';
            tableContent += '<td><a href="#" class="linkshowuser" rel="' + this.username + '">' + this.username + '</a></td>';
            tableContent += '<td>' + this.email + '</td>';
            tableContent += '<td><a href="#" class="linkdeleteuser" rel="' + this._id + '">delete</a></td>';
            tableContent += '</tr>';
        });

        // Inject the whole content string into our existing HTML table
        $('#userList table tbody').html(tableContent);
    });
};

http://localhost:3000/ açalım ve tabloda kaydın çıktığını görelim.

C:\node\nodetest2\public\javascripts\global.js dosyasını açalım.
// jQuery AJAX call for JSON
    $.getJSON( '/users/userlist', function( data ) {
Satırının hemen altına ekleyelim:
  // Stick our user data array into a userlist variable in the global object
    userListData = data;

 Yine global.js in en sonuna ekleyelim:
// Show User Info
function showUserInfo(event) {

    // Prevent Link from Firing
    event.preventDefault();

    // Retrieve username from link rel attribute
    var thisUserName = $(this).attr('rel');

    // Get Index of object based on id value
    var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);

// Get our User Object
    var thisUserObject = userListData[arrayPosition];

    //Populate Info Box
    $('#userInfoName').text(thisUserObject.fullname);
    $('#userInfoAge').text(thisUserObject.age);
    $('#userInfoGender').text(thisUserObject.gender);
    $('#userInfoLocation').text(thisUserObject.location);

};

Aynı dosyada DOM Ready kısmında tabloyu doldurmadan hemen öncesine ekleyelim:
// Username link click
    $('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);

C:\node\nodetest2\views\index.jade açalım. 
#wrapper satırından hemen sonra ekleyelim:
 // USER INFO
        #userInfo
            h2 User Info
            p
                strong Name:
                |  <span id='userInfoName'></span>
                br
                strong Age:
                |  <span id='userInfoAge'></span>
                br
                strong Gender:
                |  <span id='userInfoGender'></span>
                br
                strong Location:
                |  <span id='userInfoLocation'></span>
        // /USER INFO


http://localhost:3000 açalım. 
kullanıcı adına tıklayınca sol taraftaki kutuda bilgilerinin geldiğini görebiliriz.

/views/index.jade açalım. user list in hemen altına ekleyelim:
// ADD USER
        h2 Add User
        #addUser
            fieldset
                input#inputUserName(type='text', placeholder='Username')
                input#inputUserEmail(type='text', placeholder='Email')
                br
                input#inputUserFullname(type='text', placeholder='Full Name')
                input#inputUserAge(type='text', placeholder='Age')
                br
                input#inputUserLocation(type='text', placeholder='Location')
                input#inputUserGender(type='text', placeholder='gender')
                br
                button#btnAddUser Add User
        // /ADD USER

Artık index.jade son halini şu şekilde almış olmalı:
extends layout

block content
    h1= title
    p Welcome to our test

    // Wrapper
    #wrapper

        // USER INFO
        #userInfo
            h2 User Info
            p
                strong Name:
                |  <span id='userInfoName'></span>
                br
                strong Age:
                |  <span id='userInfoAge'></span>
                br
                strong Gender:
                |  <span id='userInfoGender'></span>
                br
                strong Location:
                |  <span id='userInfoLocation'></span>
        // /USER INFO

        // USER LIST
        h2 User List
        #userList
            table
                thead
                    th UserName
                    th Email
                    th Delete?
                tbody
        // /USER LIST

        // ADD USER
        h2 Add User
        #addUser
            fieldset
                input#inputUserName(type='text', placeholder='Username')
                input#inputUserEmail(type='text', placeholder='Email')
                br
                input#inputUserFullname(type='text', placeholder='Full Name')
                input#inputUserAge(type='text', placeholder='Age')
                br
                input#inputUserLocation(type='text', placeholder='Location')
                input#inputUserGender(type='text', placeholder='gender')
                br
                button#btnAddUser Add User
        // /ADD USER

    // /WRAPPER

C:\node\nodetest2\routes\users.js açalım.
module.exports tan hemen önce ekleyelim:
/*
 * POST to adduser.
 */
router.post('/adduser', function(req, res) {
    var db = req.db;
    db.collection('userlist').insert(req.body, function(err, result){
        res.send(
            (err === null) ? { msg: '' } : { msg: err }
        );
    });
});

C:\node\nodetest2\public\javascripts\global.js açalım.
DOM Ready kısmında user list name click in hemen altına ekleyelim:
// Add User button click
    $('#btnAddUser').on('click', addUser);

global.js in sonuna ekleyelim:
// Add User
function addUser(event) {
    event.preventDefault();

    // Super basic validation - increase errorCount variable if any fields are blank
    var errorCount = 0;
    $('#addUser input').each(function(index, val) {
        if($(this).val() === '') { errorCount++; }
    });

    // Check and make sure errorCount's still at zero
    if(errorCount === 0) {

        // If it is, compile all user info into one object
        var newUser = {
            'username': $('#addUser fieldset input#inputUserName').val(),
            'email': $('#addUser fieldset input#inputUserEmail').val(),
            'fullname': $('#addUser fieldset input#inputUserFullname').val(),
            'age': $('#addUser fieldset input#inputUserAge').val(),
            'location': $('#addUser fieldset input#inputUserLocation').val(),
            'gender': $('#addUser fieldset input#inputUserGender').val()
        }

        // Use AJAX to post the object to our adduser service
        $.ajax({
            type: 'POST',
            data: newUser,
            url: '/users/adduser',
            dataType: 'JSON'
        }).done(function( response ) {

            // Check for successful (blank) response
            if (response.msg === '') {

                // Clear the form inputs
                $('#addUser fieldset input').val('');

                // Update the table
                populateTable();

            }
            else {

                // If something goes wrong, alert the error message that our service returned
                alert('Error: ' + response.msg);

            }
        });
    }
    else {
        // If errorCount is more than 0, error out
        alert('Please fill in all fields');
        return false;
    }
};

Node serveri yeniden başlatalım.
http://localhost:3000 açtığımızda artık form çalışıyor olacaktır.
Yeni kullanıcılar ekleyip bilgilerini görebiliriz.

/routes/users.js açıp en altta module.exports tan hemen önce ekleyelim:
 /*
 * DELETE to deleteuser.
 */
router.delete('/deleteuser/:id', function(req, res) {
    var db = req.db;
    var userToDelete = req.params.id;
    db.collection('userlist').removeById(userToDelete, function(err, result) {
        res.send((result === 1) ? { msg: '' } : { msg:'error: ' + err });
    });
});

global.js de DOM Ready kısmına ekleyelim:
// Delete User link click
    $('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);


global.js en sonuna ekleyelim:
// Delete User
function deleteUser(event) {

    event.preventDefault();

    // Pop up a confirmation dialog
    var confirmation = confirm('Are you sure you want to delete this user?');

    // Check and make sure the user confirmed
    if (confirmation === true) {

        // If they did, do our delete
        $.ajax({
            type: 'DELETE',
            url: '/users/deleteuser/' + $(this).attr('rel')
        }).done(function( response ) {

            // Check for a successful (blank) response
            if (response.msg === '') {
            }
            else {
                alert('Error: ' + response.msg);
            }

            // Update the table
            populateTable();

        });

    }
    else {

        // If they said no to the confirm, do nothing
        return false;

    }

};

Node serveri yeniden başlatalım.
http://localhost:3000 açtığımızda artık kayıtları silme işlemi de yapabiliyoruz.

 
(Kaynak: http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/)


Spring ile RESTful web client yazmak

Spring'in RestTemplate ini kullanarak Facebook Graph API den bir şirketin sayfasını sorgulayalım.

1. REST resource almak için bir adrese gidelim : http://graph.facebook.com/pivotalsoftware

Gelen cevap aşağıdaki gibi bir JSON olacak:

{
  • id"161112704050757",
  • about"Pivotal is enabling the creation of modern software applications that leverage big & fast data – on a single, cloud independent platform.",
  • awards"CTO Award: Innovation Battle Hack Morgan Stanley Leadership Award: Global Commerce Bossie Awards 2013: The best open source data center and cloud software 2013 Technology Innovator of the Year CTO Award for Innovation: Greenplum DatabaseColorado’s 5 best tech companies for new developers ",
  • can_postfalse,
  • category"Internet/software",
  • category_list:
    [
    • {
      • id"108472109230615",
      • name"Computer Services"
      }
    ],
  • checkins90,

...

2.  JSON içinden sadece işimize yarayan bilgileri (isim, hakkında, telefon, web adresi) çekmek için bir Page.java yazıyoruz:

package hello;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Page {

    private String name;
    private String about;
    private String phone;
    private String website;

    public String getName() {
        return name;
    }

    public String getAbout() {
        return about;
    }

    public String getPhone() {
        return phone;
    }

    public String getWebsite() {
        return website;
    }

}


3. Executable yaratabilmek için içinde bir main() metodu olan bir Application.java yazıyoruz:

package hello;



import org.springframework.web.client.RestTemplate;



public class Application {



    public static void main(String args[]) {

        RestTemplate restTemplate = new RestTemplate();

        Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);

        System.out.println("Name:    " + page.getName());

        System.out.println("About:   " + page.getAbout());

        System.out.println("Phone:   " + page.getPhone());

        System.out.println("Website: " + page.getWebsite());

    }



}



4. RestTemplate Jackson JSON kütüphanesini kullanarak JSON datayı bir Page nesnesine çeviriyor.
Daha sonra oluşan Page nesnesi ekrana yazdırılıyor.
Projeyi build ve run edelim:
Gradle : ./gradlew bootRun
Maven : mvn spring-boot:run

Şu çıktıyı görüyoruz:

Name:    Pivotal
About:   At Pivotal, our mission is to enable customers to build a new class of applications, leveraging big and fast data, and do all of this with the power of cloud independence.
Phone:   650-286-8012
Website: http://www.gopivotal.com

Böylece Spring ile basit bir REST client yazmış olduk.

Spring ile RESTful web servis yazmak


Spring ile RESTful web servis yazmak (15 dk):
(Kaynak: https://spring.io/guides/gs/rest-service/)


Aşağıdaki adreste HTTP GET requestlerini kabul edecek bir web servis yazalım:
http://localhost:8080/greeting

Bu servis bir json ile response versin:
{"id":1,"content":"Hello, World!"}

Requeste isim parametresi de girilebilsin:
http://localhost:8080/greeting?name=User

Bu requeste response olarak şu verilsin:
{"id":1,"content":"Hello, User!"}

1. Bir pojo yaratıyoruz

package hello;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

2. Bir resource controller yaratıyoruz:

package hello;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

3. Application.java yazıyoruz:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4. Build ve run ediyoruz:

Gradle için: ./gradlew bootRun
Maven için: mvn spring-boot:run

5. Servisi test ediyoruz:

http://localhost:8080/greeting adresine gittiğimizde şunu görüyoruz:
{"id":1,"content":"Hello, World!"}

İsim parametresi verdiğimizde ise:
http://localhost:8080/greeting?name=GHopper
Şunu görüyoruz:
{"id":2,"content":"Hello, GHopper!"}


Böylece Spring ile bir RESTful web servis yazmış olduk.