Server tomonidan murakkab REST chaqiruvini qanday mazax qilish kerak?

REST xizmatlaridan keng foydalanadigan JavaScript bilan ishlashda - GET, PUT, POST, DELETES va hk. Men server tomonini masxara qilishni qiyin deb topdim, shuning uchun oldingi rivojlanish mustaqil ravishda (orqa tomondan) davom etishi mumkin.

Ba'zan ko'p bosqichli ma'lumotlarni qo'lga kiritish foydali bo'ladi, shuning uchun ham butun REST zanjirini (yoki bu zanjirlardan olingan oldingi uchburchak bilan bog'liq xatolar)

REST chaqiruvlarini, xususan, halol bo'lganlarni masxara qilish uchun qanday vositalarni qo'llashim mumkin? (ya'ni, ba'zi bir resursda PUT qilsam, keyingi GETni qanday qilib o'zgartirishni kutmoqdaman)

SOAPUI 4.0.1 ni sinab ko'rdim va bu RESTni masxara qilish umidsizlik. Bundan tashqari, mening ehtiyojim mantiqiy holatda emas. (Har bir kishi statik .json fayl bilan ishlashi mumkin). Men davlatning o'tish davriga xos tipidagi narsalarni qilishim kerak; Content-Range sarlavhalari bilan ishlash yaxshi bo'lardi.

Har kim?

7

2 javoblar

Bu erda yana bir boshpana topilgan dam olish maskani: https://github.com/mkotsur/restito .

3
qo'shib qo'ydi

Aslida, o'zimning Java REST Mock Engineni yaratishim bilan yakun topdim va asosan har qanday javobni masxara qila oladi. Barcha http-javobni simulyatsiya qiladigan matnli faylni ishlating yoki kesib qo'yishingiz mumkin ekan, siz o'zingizni xizmatni masxara qilishingiz mumkin.

Mana servlet:

package com.mockrest.debug;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class MockGridData
 */
public class MockRest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MockRest() {
        super();
       //TODO Auto-generated constructor stub
    }

    @Override
    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException {
        sub:{
            HttpServletRequest request = (HttpServletRequest)req;
            HttpServletResponse response = (HttpServletResponse)res;
            String setdata = request.getParameter("__setdata");
            if (setdata!=null && setdata.length()>0){
                System.err.println("Setting Data...");
                HttpSession sess = request.getSession(true);
                String data = "/"+request.getParameter("__setdata");
                sess.setAttribute("data", data);
                try{
                    InputStream is = getServletContext().getResourceAsStream(data);
                    if (is!=null){
                        is.close();
                        response.getWriter().write("Successfully pointed next REST call to:"+data);
                    }
                    else{
                        response.sendError(500, "Cannot find resource:"+data);
                    }
                }
                catch (IOException ioe){
                    response.sendError(500, Arrays.deepToString(ioe.getStackTrace()));
                }

            }
            else{
                System.err.println("Fetching Data...");
                HttpSession sess = request.getSession(false);
                if (sess==null || sess.getAttribute("data")==null){
                    response.sendError(500,"Session invalid or no Previous Data Set!");
                }
                String rsrc = (String)sess.getAttribute("data");
                System.err.println("Resource Being used:"+rsrc);
                InputStream is = getServletContext().getResourceAsStream(rsrc);
                if (is!=null){
                    String statusline = readLine(is);
                    Pattern statusPat = Pattern.compile("^HTTP/1.1 ([0-9]+) (.*)$");
                    Matcher m = statusPat.matcher(statusline);
                    if (m!=null && m.matches()){
                        int status = Integer.valueOf(m.group(1));
                        response.setStatus(status, m.group(2));
                    }
                    else{
                        throw new ServletException("Bad input file: status line parsing failed, got this as status line:"+statusline);
                    }
                    String line;
                    Pattern httpHeaderPat = Pattern.compile("^([^:]+): (.*)$");
                    while ((line=readLine(is))!=null){
                        if (line.length()==0){
                           //end of headers
                            break;
                        }
                        Matcher m2 = httpHeaderPat.matcher(line);
                        if (m2!=null && m2.matches()){
                            response.setHeader(m2.group(1), m2.group(2));
                        }
                    }
                    OutputStream os = response.getOutputStream();
                    byte[] buf = new byte[1024];
                    int size;
                    while ((size=is.read(buf))>0){
                        os.write(buf, 0, size);
                    }
                    os.flush();
                }
            }
        }
    }

    private String readLine(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        char c;
        while ((c=(char)is.read())!='\n'){
            sb.append(c);
        }
        if (sb.charAt(sb.length()-1) == '\r'){
            sb.deleteCharAt(sb.length()-1);
        }
        return sb.toString();
    }

}

Uni jihozlash uchun WebContent papkasida oldindan tayyorlangan javob fayllarini joylashtiring. Odatda bu fayllarni .http kengaytmalari bilan yakunlayman.

Misol init.http fayli quyida. Ushbu faylni WebContent ichida data </​​code> deb atalgan jildga joylashtirdik.

HTTP/1.1 200 OK
Date: Wed, 26 Oct 2011 18:31:45 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
Content-Range: items 0-1/2
Content-Length: 385
Cache-Control: private
Content-Type: application/json

[
  {
    "id": "249F0",
    "field1": " Global",
    "displaystartdate": "2007-10-20",
    "displayenddate": "2012-10-20",
    "status": "Major Delay",
    "children": true
  },
  {
    "id": "962581",
    "field2": "Europe",
    "displaystartdate": "2007-10-20",
    "displayenddate": "2012-10-20",
    "status": "Major Delay",
    "children": true
  }
]

ustunlar bo'sh satr bilan tanasi bilan ajratilishi kerak (bo'shliqlar, nada). Http bilan tanish bo'lgan odamlar bu toza http javob ekanligini sezasiz. Bu maqsadga qaratilgan.

Ushbu vositadan javobni xohlagan istalgan http-sarlavhasini simulyatsiya qilish uchun foydalanishingiz mumkin; shu bilan birga hozirgacha turli serverlar bilan ishlashga kirishish uchun (mening misolimda, IIS 6.0 deb nomlanuvchi javobni simulyatsiya qildim); yoki boshqa HTTP statusi kodi va boshqalar.

Uni brauzeringiz/javascriptingizdan chaqirish uchun; birinchi navbatda:

http://yourserver/yourweb/MockGridData?__setdata=data/init.http

Keyin JavaScript yoki REST AJAX qo'ng'iroqda, agar u ketsa

http://yourserver/yourweb/MockGridData

har qanday usul yoki parametr bilan; siz ilgari tayyorlangan http javobini oladi; hatto Content-Range-ga; Kesh sarlavhalari; va hokazo. Agar boshqa biror narsani qaytarish uchun keyingi AJAX chaqiruviga kerak bo'lsa, yana __ setdata </​​code> bilan qo'ng'iroq qiling. Veb-ilovangizdagi aniq holatni o'zgartirish uchun bir nechta tugmalar o'rnatishingizni tavsiya qilaman.

Har bir narsani nazarda tutgan holda, simulyatsiya qilingan REST zanjiri uchun ishlab chiquvchi mumkin:

  1. invoke

    http://yourserver/yourweb/MockGridData?__setdata=data/init.http
    
  2. run a JavaScript module that will result in calling (say, with GET)

    http://yourserver/yourweb/MockGridData
    
  3. click a button that then does:

    http://yourserver/yourweb/MockGridData?__setdata=data/step1.http
    
  4. run another JavaScript step that will result in calling (say, with PUT)

    http://yourserver/yourweb/MockGridData
    
  5. click another button that then does:

    http://yourserver/yourweb/MockGridData?__setdata=data/step2.http
    
  6. run another JavaScript step that will result in calling (say, with GET)

    http://yourserver/yourweb/MockGridData
    

    but this time expecting different result than #4.

Bu hatto ikkilik va gzipped javoblar bilan ishlashi kerak, lekin men buni sinab ko'rmadim.

2
qo'shib qo'ydi
Yechimni tabriklayman. Agar qodir bo'lsang, iltimos, javobingizni "qabul qilingan" deb belgilab qo'ying, boshqalar sizdan muvaffaqiyat qozonishi uchun. Cheers ~
qo'shib qo'ydi muallif Andrew Kozak, manba