Easy REST APIs with Jersey and RestyGWT (original) (raw)
More Related Content
Why Kotlin - Apalon Kotlin Sprint Part 1
Retrofit Technology Overview by Cumulations Technologies
Тестирование на Android с Dagger 2
Making the most of your gradle build - Gr8Conf 2017
Java libraries you can't afford to miss
What's hot
Making the most of your gradle build - Greach 2017
Testing Java Code Effectively
Testing Android apps based on Dagger and RxJava
Unit testing with mock libs
The Ring programming language version 1.9 book - Part 11 of 210
The uniform interface is 42
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
The Ring programming language version 1.5.3 book - Part 26 of 184
Intro to Retrofit 2 and RxJava2
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
Viewers also liked
GWT integration with Vaadin
RestFull Webservices with JAX-RS
JSR 339 - Java API for RESTful Web Services
Real world RESTful service development problems and solutions
Artsofte облегченная веб шина данных для организации дистанционных каналов пр...
figo at FinTech Startups MeetUp in Hamburg
JAX-RS 2.0: RESTful Web Services
Управление идентификационными данными и доступом
Необходимые условия качества данных: MDM, Шина, Хранилище данных
Интеграция данных и приложений: основа для единой ИТ-инфраструктуры
Open Source Integration with WSO2 Enterprise Service Bus
Oracle Service Bus vs. Oracle Enterprise Service Bus vs. BPEL
Enterprise service bus(esb)
Produktivität - 5 Tricks, um in weniger Zeit mehr zu erledigen
Microservices = Death of the Enterprise Service Bus (ESB)?
Become a Presentation Hero: 21 tips
Similar to Easy REST APIs with Jersey and RestyGWT
RESTful Web Services with Jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Rest with java (jax rs) and jersey and swagger
Developing RESTful WebServices using Jersey
Rest hello world_tutorial
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
Overview of RESTful web services
Exploring the JIRA 5 REST API - AtlasCamp 2011
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Engage 2023: Taking Domino Apps to the next level by providing a Rest API
soft-shake.ch - JAX-RS and Java EE 6
More from David Chandler
Taking Your GWT App to Tablets with GXT 4.0
StORM: a lightweight ORM for Android SQLite
Cómo trabajan los Googlers
Google App Engine Update 2012
Scalable Apps with Google App Engine
Develop and Deploy Scalable Apps with Google App Engine
The 90-Day Startup with Google AppEngine for Java
Securing JSF Applications Against the OWASP Top Ten
Recently uploaded
DSD-INT 2025 Stochastic flood event generation using wflow and a diffusion do...
Custom Software Development Company in Delhi
Cybersecurity_Enhanced_Visual theme_20Slides
Solved First Semester B.C.A. C Programming Question Paper – Jan/Feb 2025
Cyber_Security_and_Safety_for Class 9 Student
Latest Trends of ERP Software Solutions in India 2026
Why Partnering with a Devops Solutions Company Transforms Your IT Operations.pdf
How to Overcome 6 Common Oracle NetSuite Implementation Challenges
SNG460-CNG489_Week8_17-21Nov25_Chp8-OdtuClass.pptx
Introducing Langchain4J-CDI, a simplified approach to building AI agents the ...
C Unit-II: Input and Output, Operators, Control Structures/Statements
Code Assessment Tools .pptx
Privacy Preserving Detection of Sensitive Data Exposure (1).pptx
DSD-INT 2025 Managing low flows in the International Meuse Basin with Nature-...
Custom Software Development Services to Boost Your Business
Geographical Information System GIS Introduction CHAPTER-2.pptx
BCS-FACS Peter Landin Semantics Seminar - Formal Methods: Whence and Whither?
DSD-INT 2025 Hydrological Modelling in Society Assumptions, Impacts, and Appl...
TNG_Architecting Green Software - An Introduction_Nils-Oliver Linden&Alexande...
Adobe Marketo Engage Champion Deep Dive: Building Your AI-Ready Foundation: D...
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