Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
Clear All
new posts

    #16
    sorry, didn't check this forum for a bit.

    here is the 'full code' for a minimal servlet (plus a fair bit of extra printlns)

    Code:
    package com.sample.server;
    
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    public class RestDataSourceServlet extends HttpServlet {
    
    	private Gson gson;
    
    	@Override
    	public void init() throws ServletException {
    		gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    				.create();
    	}
    
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		System.out.println("doGet " + req.getRequestURI());
    		for (Object key : req.getParameterMap().keySet()) {
    			System.out.println(key + " = "
    					+ Arrays.toString(req.getParameterValues((String) key)));
    		}
    		try {
    			List<?> list = processRequest(req);
    			String string = gson
    					.toJson(new ResponseWrapper(new Response(list)));
    			// String string = gson.toJson(list);
    			System.out.println(string);
    			resp.getOutputStream().print(string);
    		} catch (Exception e) {
    			e.printStackTrace();
    e.getMessage());
    		}
    	}
    
    	private List<?> processRequest(HttpServletRequest req) {
    		String operationType = req.getParameter("_operationType");
    		String dataSource = req.getParameter("_dataSource");
    
    		//YOUR CODE TO PERFORM THE REQUEST GOES HERE               
    
    		return <-- A LIST OF RESULTS -->
    	}
    }

    the other thing you need to do is configure web.xml (the servlet configuration)

    Code:
    	<servlet>
    		<servlet-name>RESTapi</servlet-name>
    		<servlet-class>com.sample.server.RestDataSourceServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>RESTapi</servlet-name>
    		<url-pattern>/myrestyapi/*</url-pattern>
    	</servlet-mapping>

    with the above web.xml declaration you then say RestDataSource.setDataURL("/myrestyapi/");

    Comment


      #17
      Perfect. Thanks for your help!

      Comment


        #18
        Hey
        I have been stuck at this for a while. I have a smartgwt widget listgrid tied to a restdatasource. I have mapped its urls to my spring services. However i cannot figure out how to retrieve the json dsrequest on spring server side. Even my dispatcher servlet does not contain the params.

        my restdatasource is as follows
        Code:
        RestDataSource myDS = new RestDataSource() {
        @Override
        protected Object transformRequest(DSRequest dsRequest) { dsRequest.setContentType("application/json"); JavaScriptObject jso = dsRequest.getData(); String s1 = JSON.encode(jso); return s1; // return super.transformRequest(dsRequest);
        }
        @Override
        protected void transformResponse(DSResponse response, DSRequest request, Object data) {
        super.transformResponse(response, request, data);
        }
        };
        then on this datasource set the operations as follows
        Code:
        // set the operation on the datasource
        OperationBinding fetch = new OperationBinding();
        fetch.setOperationType(DSOperationType.FETCH);
        fetch.setDataProtocol(DSProtocol.POSTMESSAGE);
        OperationBinding add = new OperationBinding();
        add.setOperationType(DSOperationType.ADD);
        add.setDataProtocol(DSProtocol.POSTMESSAGE);
        OperationBinding update = new OperationBinding();
        update.setOperationType(DSOperationType.UPDATE);
        update.setDataProtocol(DSProtocol.POSTPARAMS);
        OperationBinding remove = new OperationBinding();
        remove.setOperationType(DSOperationType.REMOVE);
        remove.setDataProtocol(DSProtocol.POSTMESSAGE);
        myDS.setOperationBindings(fetch, add, update, remove); myDS.setDataFormat(DSDataFormat.JSON); // myDS.setDataProtocol(DSProtocol.POSTMESSAGE);
        set some fields in the datasource
        Code:
        // set the values for the datasource
         DataSourceTextField Id = new DataSourceTextField("Id", "Id"); 
        Id .setPrimaryKey(true);
        Id.setCanEdit(false);
        
        DataSourceTextField name= new DataSourceTextField("name", "Name"); name.setCanEdit(false);
        DataSourceTextField employeeType= new DataSourceTextField("employeeType", "employeeType"); employeeType.setCanEdit(true); 
        employeeType.setValueMap("Manager", "Associate", "Contractor");
        set these fields to the datasource
        Code:
        myDS.setFields(Id, name,employeeType);
        myDS.setFetchDataURL("/rest/myservice/fetch");
        myDS.setAddDataURL("/rest/myservice/add");
        myDS.setUpdateDataURL("/rest/myservice/update");
        myDS.setRemoveDataURL("/rest/myservice/remove");
        so in the case that the user changes the employeeType (because its a dropdown) an update request is sent . i send the json string to the server configured as below
        Code:
        @Controller @RequestMapping("/myservice") public class MyService { ...fetch ...update @RequestMapping(value="/update", method=RequestMethod.POST) @ResponseBody public String update() { }
        I am a failure to understand how to retrieve the (json )dsrequest because even my DispatcherServlet does not have the parameters (even if i use POSTPARAMS). The developer console shows the request made correctly but i dont receive anything on the server side. My spring servlet is configured as below in web.xml

        Code:
        	<servlet>
        		<servlet-name>spring</servlet-name>
        		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        		<load-on-startup>1</load-on-startup>
        	</servlet>
        
        
        <servlet-mapping>     <servlet-name>spring</servlet-name>     <url-pattern>/rest/*</url-pattern> </servlet-mapping>
        I think i am missing something obvious but i cant locate it. do i use @PathVariable or @RequestBody ..? If i use @RequestBody String ... i get a wierd string like 0=%7B&1=%0D&2=%20&3=%20&4=%20&5=%20&6=%22&7=f&8=i&9=l&10=e&11=I&12=d&13=%22&14=%3A&15=%22&16=0&17=%22&18=%2C
        Last edited by anshuman; 16 May 2011, 21:15.

        Comment


          #19
          Okay i just changed it back to default @overide transformRequest

          Code:
          update.setDataProtocol(DSProtocol.POSTPARAMS);
           to 
          update.setDataProtocol(DSProtocol.POSTMESSAGE);
          Code:
          @Override
          protected Object transformRequest(DSRequest dsRequest) {
           JavaScriptObject jso = dsRequest.getData(); 
           String s1 = JSON.encode(jso); 
          return s1; 
          }
          Code:
           @RequestMapping(value="/update", method=RequestMethod.POST) 
            @ResponseBody public String update(@RequestBody String json) { }


          now i have a json string i can work with. probably map it an object.
          Originally posted by anshuman
          @RequestBody ..? If i use @RequestBody String ... i get a wierd string like 0=%7B&1=%0D&2=%20&3=%20&4=%20&5=%20&6=%22&7=f&8=i&9=l&10=e&11=I&12=d&13=%22&14=%3A&15=%22&16=0&17=%22&18=%2C
          Last edited by anshuman; 16 May 2011, 21:57.

          Comment


            #20
            Why are you back on RestDataSource? As explained in the QuickStart Guide - if you are evaluating SmartGWT and considering the commercial product, use the commercial product for evaluation. Otherwise you will throw away all the work you are doing right now if you switch to the commercial product.

            Comment


              #21
              Was curious !
              besides i am trying to integrate with google visualization and gmaps and others.
              not much work though considering my backend services already exist, i just needed to expose them.

              Originally posted by Isomorphic
              Why are you back on RestDataSource? As explained in the QuickStart Guide - if you are evaluating SmartGWT and considering the commercial product, use the commercial product for evaluation. Otherwise you will throw away all the work you are doing right now if you switch to the commercial product.

              Comment


                #22
                Integration with Google Visualization or GMaps is independent of RestDataSource vs SmartGWT Server framework based DataSource.

                Nor is this "not much work". By focusing on RestDataSource you put yourself on a path to eventually re-implement everything that comes with Pro+ - now and in the future.

                Comment


                  #23
                  True. However i just wanted to familiarize myself with the json integration so that (probably)google visualization and gcharts can use them to display data.

                  Originally posted by Isomorphic
                  Integration with Google Visualization or GMaps is independent of RestDataSource vs SmartGWT Server framework based DataSource.

                  Comment


                    #24
                    The right way to drive those components would be to feed them data within the browser to avoid additional server roundtrips.

                    But even if you have some component that wants to consume a REST interface and cannot be provided data in-browser, there's a better way to do that too :) Once you've got a DataSource based on the server framework, it automatically exposes a REST interface via the RestHandler servlet. Same formats as RestDataSource. See "Queuing, RestHandler and SOAs" in the QuickStart Guide (and the JavaDoc it links to).

                    Comment


                      #25
                      I posted a full project for my Rest server attempt. There is also a link to Ron Lawrence's effort from this page. https://bitbucket.org/carchrae/open-...rver/wiki/Home - if you are building on AppEngine, I seriously suggest you use something like the Objectify code from my project (using DMI datasources or your own server code).

                      My solution in the end is to use the Pro version with DMI data sources that point to my own persistence logic. I could spend more time to build up my own code, but really, $800 is about a day of developer, so screw that. With the DMI data source binding I have the source code to most of my server and I don't worry about the plumbing between SmartClient and the server.

                      Other things worth looking into, if you're so inclined, are RequestFactory and Autobeans (the documentation was so awful for Autobeans) and RestyGWT (which looked cool, but bombed quickly when I gave it a Long key; had I not been weary of experiments, I might have continued).

                      Comment

                      Working...
                      X