Easy REST APIs with Jersey and RestyGWT (original) (raw)
More Related Content
Retrofit Technology Overview by Cumulations Technologies
Why Kotlin - Apalon Kotlin Sprint Part 1
Making the most of your gradle build - Gr8Conf 2017
Java libraries you can't afford to miss
Тестирование на Android с Dagger 2
What's hot
Intro to Retrofit 2 and RxJava2
Testing Android apps based on Dagger and RxJava
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Testing Java Code Effectively
The uniform interface is 42
Unit testing with mock libs
Making the most of your gradle build - Greach 2017
The Ring programming language version 1.9 book - Part 11 of 210
The Ring programming language version 1.5.3 book - Part 26 of 184
Viewers also liked
JSR 339 - Java API for RESTful Web Services
RestFull Webservices with JAX-RS
Oracle Service Bus vs. Oracle Enterprise Service Bus vs. BPEL
Enterprise service bus(esb)
JAX-RS 2.0: RESTful Web Services
Open Source Integration with WSO2 Enterprise Service Bus
Produktivität - 5 Tricks, um in weniger Zeit mehr zu erledigen
Become a Presentation Hero: 21 tips
Microservices = Death of the Enterprise Service Bus (ESB)?
Интеграция данных и приложений: основа для единой ИТ-инфраструктуры
figo at FinTech Startups MeetUp in Hamburg
GWT integration with Vaadin
Real world RESTful service development problems and solutions
Artsofte облегченная веб шина данных для организации дистанционных каналов пр...
Необходимые условия качества данных: MDM, Шина, Хранилище данных
Управление идентификационными данными и доступом
Similar to Easy REST APIs with Jersey and RestyGWT
RESTful Web Services with Jersey
Engage 2023: Taking Domino Apps to the next level by providing a Rest API
Rest with java (jax rs) and jersey and swagger
Overview of RESTful web services
Developing RESTful WebServices using Jersey
soft-shake.ch - JAX-RS and Java EE 6
Rest hello world_tutorial
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
Exploring the JIRA 5 REST API - AtlasCamp 2011
More from David Chandler
Taking Your GWT App to Tablets with GXT 4.0
Securing JSF Applications Against the OWASP Top Ten
Google App Engine Update 2012
Cómo trabajan los Googlers
StORM: a lightweight ORM for Android SQLite
The 90-Day Startup with Google AppEngine for Java
Develop and Deploy Scalable Apps with Google App Engine
Scalable Apps with Google App Engine
Recently uploaded
UNIT-I Introduction to Database(DBMS) BCA SEM-III
Fast-tracking quality for hundreds applications with automated testing layers
Python-Functions-A-Comprehensive-Overview.pptx
Adobe Marketo Engage Champion Deep Dive: Building Your AI-Ready Foundation: D...
Revolutionising-SQL-Data-Modelling-with-SqlDBM.pdf
How Modern Custom Software is Revolutionizing Mortgage Lending Processes -Ma...
Constraints First - Why Our On-Prem Ticketing System Starts With Limits, Not ...
Coding Assessment Tools .pdf
Week 7 Introduction to HTML PowerPoint Notes.pptx
DSD-INT 2025 Introduction to Hydrology Suite - Slootjes
Custom Software Development Services to Boost Your Business
C UNIT-I :Unit-I: Problem solving with a Computer
AI Agent Overview - Why we need AI Agent
DSD-INT 2025 Stochastic flood event generation using wflow and a diffusion do...
Custom chat gpt integration services.pptx
DSD-INT 2025 Hydrological Modelling in Society Assumptions, Impacts, and Appl...
Computer_Virus_Presentation_With_Slide7.pptx
DSD-INT 2025 Hydrological response of the Puget Sound area to a changing clim...
Membershipanywhere - Digital Membership Card - USA , Canada, Australia.pptx
Cyber_Security_and_Safety_for Class 9 Student
Easy REST APIs with Jersey and RestyGWT
- 1.
Easy REST APIswith Jersey and RestyGWT David Chandler turbomanage.wordpress.com - 2.
why RestyGWT? Ease ofGWT-RPC Power of Command pattern Less boilerplate Easier testing - 3.
- 4.
map JSON public classYqlResponse { public YqlQuery query; public static class YqlQuery { public YqlResults results; public static class YqlResults { public List quote; } } } no annotations needed - 5.
create a serviceAPI @Path("http://query.yahooapis.com/v1/public") public interface QuoteService extends RestService { @GET @Path("yql") public void get( @QueryParam("q") String query, @QueryParam("env") String env, @QueryParam("format") String format, MethodCallback callback); } - 6.
invoke the service privatestatic final QuoteService svc = GWT.create(QuoteService.class); @Override public void load(LoaderDemo.QuoteRequest input, final Callback<ListLoadResult, Throwable> callback) { svc.get(input.getYql(), ENV, FORMAT, new MethodCallback() { @Override public void onFailure(Method method, Throwable throwable) { Info.display("QuoteProxy", "failure"); callback.onFailure(throwable); } @Override public void onSuccess(Method method, YqlResponse yqlResponse) { List quotes = yqlResponse.query.results.quote; Info.display("QuoteProxy", "success"); callback.onSuccess(new ListLoadResultBean(quotes)); } }); } - 7.
simple CRUD API publicinterface RestApi extends RestService { @GET @Path("get") public void get(@QueryParam("id")Long id, MethodCallback callback); @GET @Path("all") public void listAll(MethodCallback<ListResponse> callback); @POST @Path("save") public void save(T obj, MethodCallback callback); @POST @Path("saveMany") public void saveMany(List obj, MethodCallback callback); @POST @Path("delete") public void delete(Long id, MethodCallback callback); } - 8.
not much here! minimalboilerplate @Path("/api/note") public interface NoteItemRestService extends RestApi { } private static final NoteItemRestService service = GWT.create(NoteItemRestService.class); public void addNote(Display display, long listId, Note item) { NoteList noteList = App.getNoteListService().getNoteList(listId); // All are 0-based for consistency with GWT constants item.listId = listId; service.save(item, new AppCallback(display) { @Override public void handleSuccess(Note result) { App.getAppModel().getAllNotes().add(0, result); App.getEventBus().fireEvent(new ShowMessageEvent("Note saved.")); App.getEventBus().fireEvent(new NotesLoadedEvent(App.getAppModel().getAllNotes())); App.getEventBus().fireEvent(new NoteAddedEvent(result)); } }); } - 9.
public class ProjectEntryPointimplements EntryPoint { private static DispatcherFactory dispatcherFactory = new DispatcherFactory(); private static FilterawareDispatcher dispatcher = dispatcherFactory.cachingDispatcher(); @Override public void onModuleLoad() { // Configure RestyGWT dispatcher.addFilter(new CORSFilter()); Defaults.setDispatcher(dispatcher); LoaderDemo loaderDemo = new LoaderDemo(); RootPanel.get().add(loaderDemo); } } ListAllNotesAction, ListAllNotesResult, AddNoteAction, AddNoteResult, … Command pattern - 10.
server side @Path("api/note") public classNoteDao extends RestServiceDao { private static final Logger LOG = Logger.getLogger(NoteDao.class.getName()); @Override @Path("all") @GET public ListWrapper findAll() { User user = AuthFilter.getUser(); List notes = this.listByOwner(user); return new ListWrapper(notes); } . . . } - 11.
Objectify + Jersey @Produces(MediaType.APPLICATION_JSON) publicclass RestServiceDao extends ObjectifyDao { public T getForOwner() { User user = AuthFilter.getUser(); T obj = null; try { obj = this.getByOwner(user); return obj; } catch (TooManyResultsException e) { throw new WebApplicationException(e); } } public ListWrapper findAll() { User user = AuthFilter.getUser(); List userAll = this.listByOwner(user); return new ListWrapper(userAll); } . . . } - 12.
getting Jersey pom.xml org.glassfish.jersey.containers <!-- ifyour container implements Servlet API older than 3.0, use "jersey-container-servlet-core" --> jersey-container-servlet-core 2.7 org.glassfish.hk2 hk2-api 2.3.0-b09 com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider 2.3.2 - 13.
- 14.
what about auth? AuthFilter.java //if an API call, return JSON response if (path.startsWith("/listmaker/api")) { ((HttpServletResponse) resp).setStatus(401); resp.setContentType(MediaType.TEXT_PLAIN); resp.getWriter().write("User must log in"); } else { // otherwise redirect httpRes.sendRedirect(LOGIN_FORM); } AuthFilter com.turbomanage.gwt.server.servlet.AuthFilter AuthFilter /listmaker/* - 15.
exception handling @Override public voidonFailure(Method method, Throwable throwable) { String url = method.builder.getUrl(); App.getLogger().log(Level.SEVERE, "Error calling service " + url, throwable); try { // Decode the exception if (throwable instanceof FailedStatusCodeException) { FailedStatusCodeException sce = (FailedStatusCodeException) throwable; App.getLogger().log(Level.SEVERE, "Service returned " + sce.getStatusCode() + sce.getMessage()); if (401 == sce.getStatusCode()) { Window.Location.replace(LOGIN_FORM); } else if (500 == sce.getStatusCode()) { if ("UserNotRegisteredException".equals(sce.getMessage())) { Window.Location.replace(SIGNUP_URL); } } } handleFailure(throwable); } finally { reset(null); } } - 16.
application error handling service.save(item,new AppCallback(display) { @Override public void handleSuccess(Note result) { . . . } }); public abstract class AppCallback implements MethodCallback { private final Display display; public AppCallback() { this.display = null; } public AppCallback(Display display) { this.display = display; display.startProcessing(); } . . . } - 17.
finer points Text, JSON,XML via direct API — res.get()… CachingRetryingDispatcher ModelChangeEvent Objects with final fields (@JsonCreator) Polymorphism (@JsonSubTypes) - 18.
same obj onclient / server? older versions of RestyGWT used Jackson 1.7 RestyGWT 2.0 uses Jackson 2.3 so you can now use the same annotations on client and server and therefore the same POJOs (yeah)! use @JsonIgnore for server-only fields (like Ref) - 19.
Please rate thissession at gwtcreate.com/agenda src github.com/turbomanage/listmaker David Chandler turbomanage.wordpress.com resty-gwt.github.io