Вы находитесь на странице: 1из 97

Links:TableofContents|SingleHTML

Jersey2.3.1UserGuide
TableofContents Preface 1.GettingStarted 1.1.CreatingaNewProjectfromMavenArchetype 1.2.ExploringtheNewlyCreatedProject 1.3.RunningtheProject 1.4.CreatingaJavaEEWebApplication 1.5.ExploringOtherJerseyExamples 2.Modulesanddependencies 2.1.JavaSECompatibility 2.2.IntroductiontoJerseydependencies 2.3.CommonJerseyUseCases 2.3.1.ServletbasedapplicationonGlassfish 2.3.2.Servletbasedserversideapplication 2.3.3.ClientapplicationonJDK 2.3.4.Serversideapplicationonsupportedcontainers 2.4.Listofmodules 3.JAXRSApplication,ResourcesandSubResources 3.1.RootResourceClasses 3.1.1.@Path 3.1.2.@GET,@PUT,@POST,@DELETE,...(HTTPMethods) 3.1.3.@Produces 3.1.4.@Consumes 3.2.ParameterAnnotations(@*Param) 3.3.Subresources 3.4.LifecycleofRootResourceClasses 3.5.RulesofInjection 3.6.Useof@Context 3.7.Programmaticresourcemodel 4.DeployingaRESTfulWebService 4.1.AutoDiscoverableFeatures 4.1.1.ConfiguringtheFeatureAutodiscoverymechanism 4.2.Turnoffclasspathscanning 5.ClientAPI 5.1.UniformInterfaceConstraint 5.2.EaseofuseandreusingJAXRSartifacts 5.3.OverviewoftheClientAPI 5.3.1.GettingstartedwiththeclientAPI 5.3.2.CreatingandconfiguringaClientinstance 5.3.3.Targetingawebresource 5.3.4.IdentifyingresourceonWebTarget 5.3.5.InvokingaHTTPrequest 5.3.6.Examplesummary 5.4.Javainstancesandtypesforrepresentations 5.4.1.Addingsupportfornewrepresentations 5.5.ClientTransportConnectors 5.6.Usingclientrequestandresponsefilters 5.7.Closingconnections 5.8.SecuringaClient 5.8.1.HTTPBasicAuthenticationSupport 5.8.2.HTTPDigestAuthenticationSupport 6.RepresentationsandResponses 6.1.RepresentationsandJavaTypes 6.2.BuildingResponses 6.3.WebApplicationExceptionandMappingExceptionstoResponses 6.4.ConditionalGETsandReturning304(NotModified)Responses 7.JAXRSEntityProviders 7.1.Introduction 7.2.HowtoWriteCustomEntityProviders 7.2.1.MessageBodyWriter 7.2.2.MessageBodyReader 7.3.EntityProviderSelection 7.4.JerseyM e s s a g e B o d y W o r k e r s API 7.5.DefaultJerseyEntityProviders 8.SupportforCommonMediaTypeRepresentations 8.1.JSON 8.1.1.ApproachestoJSONSupport 8.1.2.MOXy 8.1.3.JavaAPIforJSONProcessing(JSONP) 8.1.4.Jackson 8.1.5.Jettison 8.1.6.@ J S O N P JSONwithPaddingSupport 8.2.XML 8.2.1.LowlevelXMLsupport 8.2.2.GettingstartedwithJAXB 8.2.3.POJOs 8.2.4.UsingcustomJAXBContext 8.2.5.MOXy 8.3.Multipart 8.3.1.Overview 8.3.2.Client 8.3.3.Server 9.FiltersandInterceptors

9.1.Introduction 9.2.Filters 9.2.1.Serverfilters 9.2.2.Clientfillers 9.3.Interceptors 9.4.Filterandinterceptorexecutionorder 9.5.Namebinding 9.6.Dynamicbinding 9.7.Priorities 10.AsynchronousServicesandClients 10.1.AsynchronousServerAPI 10.1.1.AsynchronousServersideCallbacks 10.1.2.ChunkedOutput 10.2.ClientAPI 10.2.1.AsynchronousClientCallbacks 10.2.2.Chunkedinput 11.URIsandLinks 11.1.BuildingURIs 11.2.ResolveandRelativize 11.3.Link 12.ProgrammaticAPIforBuildingResources 12.1.Introduction 12.2.ProgrammaticHelloWorldexample 12.2.1.Deploymentofprogrammaticresources 12.3.Additionalexamples 12.4.Modelprocessors 13.ServerSentEvents(SSE)Support 13.1.WhatareServerSentEvents 13.2.WhentouseServerSentEvents 13.3.JerseyServerSentEventsAPI 13.4.ImplementingSSEsupportinaJAXRSresource 13.4.1.SimpleSSEresourcemethod 13.4.2.BroadcastingwithJerseySSE 13.5.ConsumingSSEeventswithJerseyclients 13.5.1.ReadingSSEeventswithE v e n t I n p u t 13.5.2.AsynchronousSSEprocessingwithE v e n t S o u r c e 14.Security 14.1.Securingserver 14.1.1.SecurityContext 14.1.2.Authorizationsecuringresources 14.2.ClientSecurity 14.3.OAuth 15.WADLSupport 15.1.WADLintroduction 15.2.Configuration 15.3.ExtendedWADLsupport 16.BeanValidationSupport 16.1.BeanValidationDependencies 16.2.EnablingBeanValidationinJersey 16.3.ConfiguringBeanValidationSupport 16.4.ValidatingJAXRSresourcesandmethods 16.4.1.ConstraintAnnotations 16.4.2.AnnotationconstraintsandValidators 16.4.3.EntityValidation 16.4.4.AnnotationInheritance 16.5.@ValidateOnExecution 16.6.Injecting 16.7.ErrorReporting 16.7.1.ValidationError 16.8.Example 17.EntityDataFiltering 17.1.EnablingandconfiguringEntityFilteringinyourapplication 17.2.ComponentsusedtodescribeEntityFilteringconcepts 17.3.Usingcustomannotationstofilterentities 17.3.1.ServersideEntityFiltering 17.3.2.ClientsideEntityFiltering 17.4.RolebasedEntityFilteringusing(j a v a x . a n n o t a t i o n . s e c u r i t y )annotations 17.5.Definingcustomhandlingforentityfilteringannotations 17.6.SupportingEntityDataFilteringincustomentityprovidersorframeworks 17.7.ModuleswithsupportforEntityDataFiltering 17.8.Examples 18.MVCTemplates 18.1.Dependencies 18.2.RegistrationandConfiguration 18.3.Explicitvs.ImplicitViewTemplates 18.3.1.V i e w a b l e ExplicitViewTemplates 18.3.2.@ T e m p l a t e ImplicitViewTemplates 18.4.JSP 18.5.CustomTemplatingEngines 18.6.OtherExamples 19.Monitoringanddiagnostics 19.1.Introduction 19.2.EventListeners 19.2.1.GuidelinesforimplementingJerseyeventlisteners 19.2.2.MonitoringStatistics 19.2.3.MonitoringStatisticsasMBeans 20.SpringDI 20.1.Dependencies 20.2.RegistrationandConfiguration

20.3.Example 21.JerseyTestFramework 21.1.Basics 21.2.SupportedContainers 21.3.Advancedfeatures 21.3.1.J e r s e y T e s t Features 21.3.2.Externalcontainer 21.3.3.TestClientconfiguration 21.3.4.Accessingtheloggedtestrecordsprogrammatically 22.BuildingandTestingJersey 22.1.CheckingOuttheSource 22.2.BuildingtheSource 22.3.Testing 22.4.UsingNetBeans 23.MigrationGuide 23.1.MigratingfromJersey2.0,2.1or2.2to2.3 23.2.MigratingfromJersey1.xto2.0 23.2.1.ServerAPI 23.2.2.MigratingJerseyClientAPI A.ConfigurationProperties A.1.Common(client/server)configurationproperties A.2.Serverconfigurationproperties A.3.Clientconfigurationproperties ListofTables 2.1.JerseyCore 2.2.JerseyContainers 2.3.JerseyConnectors 2.4.JerseyMedia 2.5.JerseyExtensions 2.6.JerseyTestFramework 2.7.JerseyGlassfishBundles 2.8.JerseyExamples 2.9.JerseyExamplesWebApps 3.1.Resourcescopes 3.2.Overviewofinjectiontypes 8.1.DefaultpropertyvaluesforMOXyMessageBodyReader<T>/MessageBodyWriter<T> 23.1.MappingofJersey1.xtoJAXRS2.0clientclasses A.1.Listofcommonconfigurationproperties A.2.Listofserverconfigurationproperties A.3.Listofclientconfigurationproperties ListofExamples 3.1.Simplehelloworldrootresourceclass 3.2.SpecifyingURIpathparameter 3.3.PUTmethod 3.4.SpecifyingoutputMIMEtype 3.5.UsingmultipleoutputMIMEtypes 3.6.Serversidecontentnegotiation 3.7.SpecifyinginputMIMEtype 3.8.Queryparameters 3.9.CustomJavatypeforconsumingrequestparameters 3.10.ProcessingPOSTedHTMLform 3.11.ObtaininggeneralmapofURIpathand/orqueryparameters 3.12.Obtaininggeneralmapofheaderparameters 3.13.Obtaininggeneralmapofformparameters 3.14.Exampleofthebeanwhichwillbeusedas@BeanParam 3.15.InjectionofMyBeanParamasamethodparameter: 3.16.Injectionofmorebeansintooneresourcemethods: 3.17.Subresourcemethods 3.18.Subresourcelocators 3.19.Subresourcelocatorswithemptypath 3.20.Subresourcelocatorsreturningsubtype 3.21.Subresourcelocatorscreatedfromclasses 3.22.Subresourcelocatorsreturningresourcemodel 3.23.Injection 3.24.Wronginjectionintoasingletonscope 3.25.Injectionofproxiesintosingleton 3.26.Exampleofpossibleinjections 4.1.Deploymentagnosticapplicationmodel 4.2.ReusingJerseyimplementationinyourcustomapplicationmodel 4.3.DeploymentofaJAXRSapplicationusing@ A p p l i c a t i o n P a t h withServlet3.0 4.4.Configurationofmavenwarplugininp o m . x m l withServlet3.0 4.5.DeploymentofaJAXRSapplicationusingw e b . x m l withServlet3.0 4.6.DeploymentofyourapplicationusingJerseyspecificservlet 4.7.UsingJerseyspecificservletwithoutanapplicationmodelinstance 4.8.RegisteringSPIimplementationsusingResourceConfig 5.1.POSTrequestwithformparameters 5.2.UsingJAXRSClientAPI 5.3.UsingJAXRSClientAPIfluently 5.4.Closingconnections 6.1.UsingF i l e withaspecificmediatypetoproducearesponse 6.2.Returning201statuscodeandaddingL o c a t i o n headerinresponsetoPOSTrequest 6.3.Addinganentitybodytoacustomresponse 6.4.Throwingexceptionstocontrolresponse 6.5.Applicationspecificexceptionimplementation 6.6.Mappinggenericexceptionstoresponses 6.7.ConditionalGETsupport 7.1.Exampleresourceclass 7.2.MyBeanentityclass 7.3.MessageBodyWriterexample 7.4.Exampleofassignmentofannotationstoaresponseentity 7.5.ClientcodetestingMyBeanMessageBodyWriter 7.6.ResultofMyBeanMessageBodyWritertest 7.7.MessageBodyReaderexample

7.8.TestingMyBeanMessageBodyReader 7.9.ResultoftestingMyBeanMessageBodyReader 7.10.MessageBodyReaderregisteredonaJAXRSclient 7.11.Resultofclientcodeexecution 7.12.UsageofMessageBodyWorkersinterface 8.1.SimpleJAXBbeanimplementation 8.2.JAXBbeanusedtogenerateJSONrepresentation 8.3.TweakingJSONformatusingJAXB 8.4.JAXBbeancreation 8.5.ConstructingaJ s o n O b j e c t (JSONProcessing) 8.6.ConstructingaJ S O N O b j e c t (Jettison) 8.7.MoxyJsonConfigSettingproperties. 8.8.C o n t e x t R e s o l v e r < M o x y J s o n C o n f i g > 8.9.SettingpropertiesforMOXyprovidersintoConfigurable 8.10.BuildingclientwithMOXyJSONfeatureenabled. 8.11.CreatingJAXRSapplicationwithMOXyJSONfeatureenabled. 8.12.BuildingclientwithJSONProcessingJSONfeatureenabled. 8.13.CreatingJAXRSapplicationwithJSONProcessingJSONfeatureenabled. 8.14.C o n t e x t R e s o l v e r < O b j e c t M a p p e r > 8.15.BuildingclientwithJacksonJSONfeatureenabled. 8.16.CreatingJAXRSapplicationwithJacksonJSONfeatureenabled. 8.17.JAXBbeansforJSONsupportednotationsdescription,simpleaddressbean 8.18.JAXBbeansforJSONsupportednotationsdescription,contactbean 8.19.JAXBbeansforJSONsupportednotationsdescription,initialization 8.20.XMLnamespacetoJSONmappingconfigurationforJettisonbasedm a p p e d notation 8.21.JSONexpressionwithXMLnamespacesmappedintoJSON 8.22.JSONArrayconfigurationforJettisonbasedm a p p e d notation 8.23.JSONexpressionwithJSONarraysexplicitlyconfiguredviaJersey 8.24.JSONexpressionproducedusingb a d g e r f i s h notation 8.25.C o n t e x t R e s o l v e r < O b j e c t M a p p e r > 8.26.BuildingclientwithJettisonJSONfeatureenabled. 8.27.CreatingJAXRSapplicationwithJettisonJSONfeatureenabled. 8.28.Simplestcaseofusing@ J S O N P 8.29.JaxbBeanfor@JSONPexample 8.30.Exampleof@ J S O N P withconfiguredparameters. 8.31.LowlevelXMLtestmethodsaddedtoH e l l o W o r l d R e s o u r c e . j a v a 8.32.Planetclass 8.33.Resourceclass 8.34.MethodforconsumingPlanet 8.35.ResourceclassJAXBElement 8.36.ClientsideJAXBElement 8.37.PlanetJAXBContextProvider 8.38.UsingProviderwithJAXRSclient 8.39.Addj e r s e y m e d i a m o x y dependency. 8.40.RegistertheM o x y X m l F e a t u r e class. 8.41.ConfigureandregisteranM o x y X m l F e a t u r e instance. 8.42.BuildingclientwithMultiPartfeatureenabled. 8.43.CreatingJAXRSapplicationwithMultiPartfeatureenabled. 8.44.M u l t i P a r t entity 8.45.M u l t i P a r t entityinHTTPmessage. 8.46.F o r m D a t a M u l t i P a r t entity 8.47.F o r m D a t a M u l t i P a r t entityinHTTPmessage. 8.48.Multipartsendingfiles. 8.49.ResourcemethodusingM u l t i P a r t asinputparameter/returnvalue. 8.50.Useof@ F o r m D a t a P a r a m annotation 9.1.Containerresponsefilter 9.2.Containerrequestfilter 9.3.Prematchingrequestfilter 9.4.Clientrequestfilter 9.5.GZIPwriterinterceptor 9.6.GZIPreaderinterceptor 9.7.@ N a m e B i n d i n g example 9.8.Dynamicbindingexample 9.9.Prioritiesexample 10.1.Simpleasyncresource 10.2.Simpleasyncmethodwithtimeout 10.3.CompletionCallbackexample 10.4.ChunkedOutputexample 10.5.Simpleclientasyncinvocation 10.6.Simpleclientfluentasyncinvocation 10.7.Clientasynccallback 10.8.Clientasynccallbackforspecificentity 10.9.ChunkedInputexample 11.1.URIbuilding 11.2.BuildingURIsusingqueryparameters 12.1.Astandardresourceclass 12.2.Aprogrammaticresource 12.3.Aprogrammaticresource 12.4.Aprogrammaticresource 12.5.Aprogrammaticresource 12.6.Aprogrammaticresource 13.1.SimpleSSEresourcemethod 13.2.BroadcastingSSEmessages 13.3.RegisteringE v e n t L i s t e n e r withE v e n t S o u r c e 13.4.OverridingE v e n t S o u r c e . o n E v e n t ( I n b o u n d E v e n t ) method 14.1.AccessingS e c u r i t y C o n t e x t 14.2.InjectingS e c u r i t y C o n t e x t intoasingletonresource 14.3.Securingresourcesusingw e b . x m l 14.4.RegisteringRolesAllowedDynamicFeatureusingResourceConfig 14.5.InjectingS e c u r i t y C o n t e x t intosingletons 15.1.AsimpleWADLexampleJAXRSresourcedefinition 15.2.AsimpleWADLexampleWADLcontent 15.3.OPTIONSmethodreturningWADL 15.4.MorecomplexWADLexampleJAXRSresourcedefinition 15.5.MorecomplexWADLexampleWADLcontent 16.1.ConfiguringJerseyspecificpropertiesforBeanValidation. 16.2.UsingV a l i d a t i o n C o n f i g toconfigureV a l i d a t o r . 16.3.Constraintannotationsoninputparameters

16.4.Constraintannotationsonfields 16.5.Constraintannotationsonclass 16.6.Definitionofaconstraintannotation 16.7.Validatorimplementation. 16.8.Entityvalidation 16.9.Entityvalidation2 16.10.Responseentityvalidation 16.11.Validategetteronexecution 16.12.InjectingUriInfointoaConstraintValidator 16.13.SupportforinjectingJersey'sresources/providersviaConstraintValidatorFactory. 16.14.V a l i d a t i o n E r r o r tot e x t / p l a i n 16.15.V a l i d a t i o n E r r o r tot e x t / h t m l 16.16.V a l i d a t i o n E r r o r toa p p l i c a t i o n / x m l 16.17.V a l i d a t i o n E r r o r toa p p l i c a t i o n / j s o n 17.1.Registeringandconfiguringentityfilteringfeatureonserver. 17.2.Registeringandconfiguringentityfilteringfeaturewithsecurityannotationsonserver. 17.3.Registeringandconfiguringentityfilteringfeatureonclient. 17.4.Project 17.5.User 17.6.Task 17.7.ProjectsResource 17.8.ProjectDetailedView 17.9.AnnotatedProject 17.10.AnnotatedUser 17.11.AnnotatedTask 17.12.ProjectsResourceResponseentityfilteringannotations 17.13.ProjectsResourceEntityfilteringannotationsonmethods 17.14.ClientRequestentityfilteringannotations 17.15.ClientRequestentityfilteringannotations 17.16.Entityfilteringannotationwithcustommeaning 17.17.EntityDataFilteringsupportinMOXyJSONbindingprovider 18.1.RegisteringM v c F e a t u r e 18.2.RegisteringJ s p M v c F e a t u r e 18.3.SettingM v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H valueinR e s o u r c e C o n f i g 18.4.SettingF r e e m a r k e r M v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H valueinw e b . x m l 18.5.UsingV i e w a b l e inaresourceclass 18.6.UsingabsolutepathtotemplateinV i e w a b l e 18.7.Using@ T e m p l a t e onaresourceclass 18.8.CustomTemplateProcessor 18.9.RegisteringcustomTemplateProcessor 19.1.Applicationeventlistener 19.2.Requesteventlistener 19.3.Eventlistenertestresource 19.4.InjectingMonitoringStatistics 23.1.Jersey1reloaderimplementation 23.2.Jersey1reloaderregistration 23.3.Jersey2reloaderimplementation 23.4.Jersey2reloaderregistration

Preface
ThisisuserguideforJersey2.3.1.Wearetryingtokeepituptodateasweaddnewfeatures.Whenreadingtheuserguide,pleaseconsultalsoourJersey APIdocumentationasanadditionalsourceofinformationaboutJerseyfeaturesandAPI. Ifyouwouldliketocontributetotheguideorhavequestionsonthingsnotcoveredinourdocs,pleasecontactusatusers@jersey.java.net.Similarly,incase youspotanyerrorsintheJerseydocumentation,pleasereportthembyfilinganewissueinourJerseyJIRAIssueTrackerunderd o c s component.Please makesuretospecifytheversionoftheJerseyUserGuidewheretheerrorhasbeenspottedbyselectingthepropervaluefortheA f f e c t e d V e r s i o n field.

Textformattingconventions
FirstmentionofanyJerseyandJAXRSAPIcomponentinasectionlinkstotheAPIdocumentationofthereferencedcomponent.Anysubsequentmentions ofthecomponentinthesamechapterarerenderedusingam o n o s p a c e font. Emphasisedfontisusedtoacallattentiontoanewlyintroduceconcept,whenitfirstoccursinthetext. Insomeofthecodelistings,certainlinesaretoolongtobedisplayedononelinefortheavailablepagewidth.Insuchcase,thelinesthatexceedtheavailable pagewidtharebrokenupintomultiplelinesusinga' \ ' attheendofeachlinetoindicatethatabreakhasbeenintroducedtofitthelineinthepage.For example:
T h i s i s a n o v e r l y l o n g l i n e t h a t \ m i g h t n o t f i t t h e a v a i l a b l e p a g e \ w i d t h a n d h a d t o b e b r o k e n i n t o \ m u l t i p l e l i n e s . T h i s l i n e f i t s t h e p a g e w i d t h .

Shouldreadas:
T h i s i s a n o v e r l y l o n g l i n e t h a t m i g h t n o t f i t t h e a v a i l a b l e p a g e w i d t h a n d h a d t o b e b r o k e n i n t o m u l t i p l e l i n e s . T h i s l i n e f i t s t h e p a g e w i d t h .

Chapter1.GettingStarted
TableofContents 1.1.CreatingaNewProjectfromMavenArchetype 1.2.ExploringtheNewlyCreatedProject 1.3.RunningtheProject 1.4.CreatingaJavaEEWebApplication 1.5.ExploringOtherJerseyExamples ThischapterprovidesaquickintroductiononhowtogetstartedbuildingRESTfulservicesusingJersey.Theexampledescribedhereusesthelightweight GrizzlyHTTPserver.AttheendofthischapteryouwillseehowtoimplementequivalentfunctionalityasaJavaEEwebapplicationyoucandeployonany servletcontainersupportingServlet2.5andhigher.

1.1.CreatingaNewProjectfromMavenArchetype
JerseyprojectisbuildusingApacheMavensoftwareprojectbuildandmanagementtool.AllmodulesproducedaspartofJerseyprojectbuildarepushedto theCentralMavenRepository.ThereforeitisveryconvenienttoworkwithJerseyforanyMavenbasedprojectasallthereleased(nonSNAPSHOT)Jersey dependenciesarereadilyavailablewithoutaneedtoconfigureaspecialmavenrepositorytoconsumetheJerseymodules.

Note
IncaseyouwanttodependonthelatestSNAPSHOTversionsofJerseymodules,thefollowingrepositoryconfigurationneedstobeaddedto yourMavenprojectpom:
< r e p o s i t o r y > < i d > s n a p s h o t r e p o s i t o r y . j a v a . n e t < / i d > < n a m e > J a v a . n e t S n a p s h o t R e p o s i t o r y f o r M a v e n < / n a m e > < u r l > h t t p s : / / m a v e n . j a v a . n e t / c o n t e n t / r e p o s i t o r i e s / s n a p s h o t s / < / u r l > < l a y o u t > d e f a u l t < / l a y o u t > < / r e p o s i t o r y >

SincestartingfromaMavenprojectisthemostconvenientwayforworkingwithJersey,let'snowhavealookatthisapproach.Wewillnowcreateanew JerseyprojectthatrunsontopofaGrizzlycontainer.WewilluseaJerseyprovidedmavenarchetype.Tocreatetheproject,executethefollowingMaven commandinthedirectorywherethenewprojectshouldreside:


m v n a r c h e t y p e : g e n e r a t e D a r c h e t y p e A r t i f a c t I d = j e r s e y q u i c k s t a r t g r i z z l y 2 \ D a r c h e t y p e G r o u p I d = o r g . g l a s s f i s h . j e r s e y . a r c h e t y p e s D i n t e r a c t i v e M o d e = f a l s e \ D g r o u p I d = c o m . e x a m p l e D a r t i f a c t I d = s i m p l e s e r v i c e D p a c k a g e = c o m . e x a m p l e \ D a r c h e t y p e V e r s i o n = 2 . 3 . 1

Feelfreetoadjusttheg r o u p I d ,p a c k a g e and/ora r t i f a c t I d ofyournewproject.Alternatively,youcanchangeitbyupdatingthenewprojectpom.xmlonce itgetsgenerated.

1.2.ExploringtheNewlyCreatedProject
OncetheprojectgenerationfromaJerseymavenarchetypeissuccessfullyfinished,youshouldseethenews i m p l e s e r v i c e projectdirectorycreatedin yourcurrentlocation.ThedirectorycontainsastandardMavenprojectstructure:
Projectbuildandmanagementconfigurationisdescribedinthep o m . x m l locatedintheprojectrootdirectory. Projectsourcesarelocatedunders r c / m a i n / j a v a . Projecttestsourcesarelocatedunders r c / t e s t / j a v a .

Thereare2classesintheprojectsourcedirectoryinthec o m . e x a m p l e package.TheM a i n classisresponsibleforbootstrappingtheGrizzlycontaineraswell asconfiguringanddeployingtheproject'sJAXRSapplicationtothecontainer.AnotherclassinthesamepackageisM y R e s o u r c e class,thatcontains implementationofasimpleJAXRSresource.Itlookslikethis:


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 p a c k a g e c o m . e x a m p l e i m p o r t j a v a x . w s . r s . G E T i m p o r t j a v a x . w s . r s . P a t h i m p o r t j a v a x . w s . r s . P r o d u c e s i m p o r t j a v a x . w s . r s . c o r e . M e d i a T y p e / * * * R o o t r e s o u r c e ( e x p o s e d a t " m y r e s o u r c e " p a t h ) * / @ P a t h ( " m y r e s o u r c e " ) p u b l i c c l a s s M y R e s o u r c e { / * * * M e t h o d h a n d l i n g H T T P G E T r e q u e s t s . T h e r e t u r n e d o b j e c t w i l l b e s e n t * t o t h e c l i e n t a s " t e x t / p l a i n " m e d i a t y p e . * * @ r e t u r n S t r i n g t h a t w i l l b e r e t u r n e d a s a t e x t / p l a i n r e s p o n s e . * / @ G E T @ P r o d u c e s ( M e d i a T y p e . T E X T _ P L A I N ) p u b l i c S t r i n g g e t I t ( ) { r e t u r n " G o t i t ! " } }

AJAXRSresourceisanannotatedPOJOthatprovidessocalledresourcemethodsthatareabletohandleHTTPrequestsforURIpathsthattheresourceis boundto.SeeChapter3,JAXRSApplication,ResourcesandSubResourcesforacompleteguidetoJAXRSresources.Inourcase,theresourceexposesa singleresourcemethodthatisabletohandleHTTPG E T requests,isboundto/ m y r e s o u r c e URIpathandcanproduceresponseswithresponsemessage contentrepresentedin" t e x t / p l a i n " mediatype.Inthisversion,theresourcereturnsthesame" G o t i t ! " responsetoallclientrequests. ThelastpieceofcodethathasbeengeneratedinthisskeletonprojectisaM y R e s o u r c e T e s t unittestclassthatislocatedinthesamec o m . e x a m p l e package astheM y R e s o u r c e class,however,thisunittestclassisplacedintothemavenprojecttestsourcedirectorys r c / t e s t / j a v a (certaincodecommentsand JUnitimportshavebeenexcludedforbrevity):
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 p a c k a g e c o m . e x a m p l e i m p o r t j a v a x . w s . r s . c l i e n t . C l i e n t i m p o r t j a v a x . w s . r s . c l i e n t . C l i e n t B u i l d e r i m p o r t j a v a x . w s . r s . c l i e n t . W e b T a r g e t i m p o r t o r g . g l a s s f i s h . g r i z z l y . h t t p . s e r v e r . H t t p S e r v e r . . . p u b l i c c l a s s M y R e s o u r c e T e s t { p r i v a t e H t t p S e r v e r s e r v e r p r i v a t e W e b T a r g e t t a r g e t @ B e f o r e p u b l i c v o i d s e t U p ( ) t h r o w s E x c e p t i o n { s e r v e r = M a i n . s t a r t S e r v e r ( ) C l i e n t c = C l i e n t B u i l d e r . n e w C l i e n t ( ) t a r g e t = c . t a r g e t ( M a i n . B A S E _ U R I ) } @ A f t e r p u b l i c v o i d t e a r D o w n ( ) t h r o w s E x c e p t i o n { s e r v e r . s t o p ( ) }

2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7

/ * * * T e s t t o s e e t h a t t h e m e s s a g e " G o t i t ! " i s s e n t i n t h e r e s p o n s e . * / @ T e s t p u b l i c v o i d t e s t G e t I t ( ) { S t r i n g r e s p o n s e M s g = t a r g e t . p a t h ( " m y r e s o u r c e " ) . r e q u e s t ( ) . g e t ( S t r i n g . c l a s s ) a s s e r t E q u a l s ( " G o t i t ! " , r e s p o n s e M s g ) } }

Inthisunittest,aGrizzlycontainerisfirststartedandserverapplicationisdeployedinthetests e t U p ( ) methodbyastaticcalltoM a i n . s t a r t S e r v e r ( ) . Next,aJAXRSclientcomponentsarecreatedinthesametestsetupmethod.FirstanewJAXRSclientinstancec isbuiltandthenaJAXRSwebtarget componentpointingtothecontextrootofourapplicationdeployedath t t p : / / l o c a l h o s t : 8 0 8 0 / m y a p p / (avalueofM a i n . B A S E _ U R I constant)isstoredinto at a r g e t fieldoftheunittestclass.Thisfieldisthenusedintheactualunittestmethod(t e s t G e t I t ( ) ). Inthet e s t G e t I t ( ) methodafluentJAXRSClientAPIisusedtoconnecttoandsendaHTTPG E T requesttotheM y R e s o u r c e JAXRSresourceclass listeningon/ m y r e s o u r c e URI.AspartofthesamefluentJAXRSAPImethodinvocationchain,aresponseisreadasaJavaS t r i n g type.Onthesecond lineinthetestmethod,theresponsecontentstringreturnedfromtheserveriscomparedwiththeexpectedphraseinthetestassertion.Tolearnmoreabout usingJAXRSClientAPI,pleaseseetheChapter5,ClientAPIchapter.

1.3.RunningtheProject
Nowthatwehaveseenthecontentoftheproject,let'strytotestrunit.Todothis,weneedtoinvokefollowingcommandonthecommandline:
m v n c l e a n t e s t

Thiswillcompiletheprojectandruntheprojectunittests.Weshouldseeasimilaroutputthatinformsaboutasuccessfulbuildoncethebuildisfinished:
R e s u l t s : T e s t s r u n : 1 , F a i l u r e s : 0 , E r r o r s : 0 , S k i p p e d : 0 [ I N F O ] [ I N F O ] B U I L D S U C C E S S [ I N F O ] [ I N F O ] T o t a l t i m e : 3 4 . 5 2 7 s [ I N F O ] F i n i s h e d a t : S u n M a y 2 6 1 9 : 2 6 : 2 4 C E S T 2 0 1 3 [ I N F O ] F i n a l M e m o r y : 1 7 M / 4 9 0 M [ I N F O ]

Nowthatwehaveverifiedthattheprojectcompilesandthattheunittestpasses,wecanexecutetheapplicationinastandalonemode.Todothis,runthe followingmavencommand:
m v n e x e c : j a v a

Theapplicationstartsandyoushouldsoonseethefollowingnotificationinyourconsole:
M a y 2 6 , 2 0 1 3 8 : 0 8 : 4 5 P M o r g . g l a s s f i s h . g r i z z l y . h t t p . s e r v e r . N e t w o r k L i s t e n e r s t a r t I N F O : S t a r t e d l i s t e n e r b o u n d t o [ l o c a l h o s t : 8 0 8 0 ] M a y 2 6 , 2 0 1 3 8 : 0 8 : 4 5 P M o r g . g l a s s f i s h . g r i z z l y . h t t p . s e r v e r . H t t p S e r v e r s t a r t I N F O : [ H t t p S e r v e r ] S t a r t e d . J e r s e y a p p s t a r t e d w i t h W A D L a v a i l a b l e a t h t t p : / / l o c a l h o s t : 8 0 8 0 / m y a p p / a p p l i c a t i o n . w a d l H i t e n t e r t o s t o p i t . . .

Thisinformsyouthattheapplicationhasbeenstartedandit'sWADLdescriptorisavailableath t t p : / / l o c a l h o s t : 8 0 8 0 / m y a p p / a p p l i c a t i o n . w a d l URL. YoucanretrievetheWADLcontentbyexecutingac u r l h t t p : / / l o c a l h o s t : 8 0 8 0 / m y a p p / a p p l i c a t i o n . w a d l commandinyourconsoleorbytypingthe WADLURLintoyourfavoritebrowser.YoushouldgetbackanXMLdocumentindescribingyourdeployedRESTfulapplicationinaWADLformat.Tolearn moreaboutworkingwithWADL,checktheChapter15,WADLSupportchapter. Thelastthingweshouldtrybeforeconcludingthissectionistoseeifwecancommunicatewithourresourcedeployedat/ m y r e s o u r c e path.Wecanagain eithertypetheresourceURLinthebrowserorwecanusec u r l :


$ c u r l h t t p : / / l o c a l h o s t : 8 0 8 0 / m y a p p / m y r e s o u r c e G o t i t !

Aswecansee,thec u r l commandreturnedwiththeG o t i t ! messagethatwassentbyourresource.Wecanalsoaskc u r l toprovidemoreinformation abouttheresponse,forexamplewecanletitdisplayallresponseheadersbyusingthe i switch:


c u r l i h t t p : / / l o c a l h o s t : 8 0 8 0 / m y a p p / m y r e s o u r c e H T T P / 1 . 1 2 0 0 O K C o n t e n t T y p e : t e x t / p l a i n D a t e : S u n , 2 6 M a y 2 0 1 3 1 8 : 2 7 : 1 9 G M T C o n t e n t L e n g t h : 7 G o t i t !

HereweseethewholecontentoftheresponsemessagethatourJersey/JAXRSapplicationreturned,includingalltheHTTPheaders.NoticetheC o n t e n t T y p e : t e x t / p l a i n headerthatwasderivedfromthevalueof@ProducesannotationattachedtotheM y R e s o u r c e class. Incaseyouwanttoseeevenmoredetailsaboutthecommunicationbetweenourc u r l clientandourresourcerunningonJerseyinaGrizzlyI/Ocontainer, feelfreetotryothervariousoptionsandswitchesthatc u r l provides.Forexample,thislastcommandwillmakec u r l outputalotofadditionalinformation aboutthewholecommunication:


$ c u r l v h t t p : / / l o c a l h o s t : 8 0 8 0 / m y a p p / m y r e s o u r c e * A b o u t t o c o n n e c t ( ) t o l o c a l h o s t p o r t 8 0 8 0 ( # 0 ) * T r y i n g : : 1 . . . * C o n n e c t i o n r e f u s e d * T r y i n g 1 2 7 . 0 . 0 . 1 . . . * c o n n e c t e d * C o n n e c t e d t o l o c a l h o s t ( 1 2 7 . 0 . 0 . 1 ) p o r t 8 0 8 0 ( # 0 ) > G E T / m y a p p / m y r e s o u r c e H T T P / 1 . 1 > U s e r A g e n t : c u r l / 7 . 2 5 . 0 ( x 8 6 _ 6 4 a p p l e d a r w i n 1 1 . 3 . 0 ) l i b c u r l / 7 . 2 5 . 0 O p e n S S L / 1 . 0 . 1 e z l i b / 1 . 2 . 7 l i b i d n / 1 . 2 2 > H o s t : l o c a l h o s t : 8 0 8 0 > A c c e p t : * / * > < H T T P / 1 . 1 2 0 0 O K < C o n t e n t T y p e : t e x t / p l a i n < D a t e : S u n , 2 6 M a y 2 0 1 3 1 8 : 2 9 : 1 8 G M T < C o n t e n t L e n g t h : 7 < * C o n n e c t i o n # 0 t o h o s t l o c a l h o s t l e f t i n t a c t

G o t i t ! * C l o s i n g c o n n e c t i o n # 0

1.4.CreatingaJavaEEWebApplication
TocreateaWebApplicationthatcanbepackagedasWARanddeployedinaServletcontainerfollowasimilarprocesstotheonedescribedinSection1.1, CreatingaNewProjectfromMavenArchetype.InadditiontotheGrizzlybasedarchetype,JerseyprovidesalsoaMavenarcehtypeforcreatingweb applicationskeletons.Tocreatethenewwebapplicationskeletonproject,executethefollowingMavencommandinthedirectorywherethenewproject shouldreside:
m v n a r c h e t y p e : g e n e r a t e D a r c h e t y p e A r t i f a c t I d = j e r s e y q u i c k s t a r t w e b a p p \ D a r c h e t y p e G r o u p I d = o r g . g l a s s f i s h . j e r s e y . a r c h e t y p e s D i n t e r a c t i v e M o d e = f a l s e \ D g r o u p I d = c o m . e x a m p l e D a r t i f a c t I d = s i m p l e s e r v i c e w e b a p p D p a c k a g e = c o m . e x a m p l e \ D a r c h e t y p e V e r s i o n = 2 . 3 . 1

AswiththeGrizzlybasedproject,feelfreetoadjusttheg r o u p I d ,p a c k a g e and/ora r t i f a c t I d ofyournewwebapplicationproject.Alternatively,youcan changeitbyupdatingthenewprojectpom.xmlonceitgetsgenerated. OncetheprojectgenerationfromaJerseymavenarchetypeissuccessfullyfinished,youshouldseethenews i m p l e s e r v i c e w e b a p p projectdirectory createdinyourcurrentlocation.ThedirectorycontainsastandardMavenprojectstructure,similartothes i m p l e s e r v i c e projectcontentwehaveseen earlier,exceptitisextendedwithanadditionalwebapplicationspecificcontent:


Projectbuildandmanagementconfigurationisdescribedinthep o m . x m l locatedintheprojectrootdirectory. Projectsourcesarelocatedunders r c / m a i n / j a v a . Projectresourcesarelocatedunders r c / m a i n / r e s o u r c e s . Projectwebapplicationfilesarelocatedunders r c / m a i n / w e b a p p .

TheprojectcontainsthesameM y R e s o u c e JAXRSresourceclass.ItdoesnotcontainanyunittestsaswellasitdoesnotcontainaM a i n classthatwasused tosetupGrizzlycontainerinthepreviousproject.Instead,itcontainsthestandardJavaEEwebapplicationw e b . x m l deploymentdescriptorunder s r c / m a i n / w e b a p p / W E B I N F .Thelastcomponentintheprojectisani n d e x . j s p pagethatservesasaclientfortheM y R e s o u r c e resourceclassthatis packagedanddeployedwiththeapplication. TocompileandpackagetheapplicationintoaWAR,invokethefollowingmavencommandinyourconsole:
m v n c l e a n p a c k a g e

Asuccessfullbuildoutputwillproduceanoutputsimilartotheonebelow:
R e s u l t s : T e s t s r u n : 0 , F a i l u r e s : 0 , E r r o r s : 0 , S k i p p e d : 0 [ I N F O ] [ I N F O ] m a v e n w a r p l u g i n : 2 . 1 . 1 : w a r ( d e f a u l t w a r ) @ s i m p l e s e r v i c e w e b a p p [ I N F O ] P a c k a g i n g w e b a p p [ I N F O ] A s s e m b l i n g w e b a p p [ s i m p l e s e r v i c e w e b a p p ] i n [ . . . / s i m p l e s e r v i c e w e b a p p / t a r g e t / s i m p l e s e r v i c e w e b a p p ] [ I N F O ] P r o c e s s i n g w a r p r o j e c t [ I N F O ] C o p y i n g w e b a p p r e s o u r c e s [ . . . / s i m p l e s e r v i c e w e b a p p / s r c / m a i n / w e b a p p ] [ I N F O ] W e b a p p a s s e m b l e d i n [ 7 5 m s e c s ] [ I N F O ] B u i l d i n g w a r : . . . / s i m p l e s e r v i c e w e b a p p / t a r g e t / s i m p l e s e r v i c e w e b a p p . w a r [ I N F O ] W E B I N F / w e b . x m l a l r e a d y a d d e d , s k i p p i n g [ I N F O ] [ I N F O ] B U I L D S U C C E S S [ I N F O ] [ I N F O ] T o t a l t i m e : 9 . 0 6 7 s [ I N F O ] F i n i s h e d a t : S u n M a y 2 6 2 1 : 0 7 : 4 4 C E S T 2 0 1 3 [ I N F O ] F i n a l M e m o r y : 1 7 M / 4 9 0 M [ I N F O ]

NowyouarereadytotakethepackagedWAR(locatedunder. / t a r g e t / s i m p l e s e r v i c e w e b a p p . w a r )anddeployittoaServletcontainerofyourchoice.

Important
TodeployaJerseyapplication,youwillneedaServletcontainerthatsupportsServlet2.5orlater.Forfullsetofadvancedfeatures(suchas JAXRS2.0AsyncSupport)youwillneedaServlet3.0orlatercompliantcontainer.

1.5.ExploringOtherJerseyExamples
Inthesectionsabove,wehavecoveredanapproachhowtogetdirtywithJerseyquickly.PleaseconsulttheothersectionsoftheJerseyUserGuidetolearn moreaboutJerseyandJAXRS.EventhoughwetryourbesttocoverasmuchaspossiblyintheUserGuide,thereisalwaysachancethatyouwouldnotbe abletogetafullanswertotheproblemyouaresolving.Inthatcase,considerdivinginourexamplesthatprovideadditionaltipsandhintstothefeaturesyou maywanttouseinyourprojects. JerseycodebasecontainsanumberofusefulexamplesonhowtousevariousJAXRSandJerseyfeatures.Feelfreetobrowsethroughthecodeof individualJerseyExamplesintheJerseysourcerepository.Forofflinebrowsing,youcanalsodownloadabundlewithalltheexamplesfromhere.

Chapter2.Modulesanddependencies
TableofContents 2.1.JavaSECompatibility 2.2.IntroductiontoJerseydependencies 2.3.CommonJerseyUseCases 2.3.1.ServletbasedapplicationonGlassfish 2.3.2.Servletbasedserversideapplication 2.3.3.ClientapplicationonJDK 2.3.4.Serversideapplicationonsupportedcontainers 2.4.Listofmodules

2.1.JavaSECompatibility
AllJerseycomponentsarecompiledwithJavaSE6target.Itmeans,youwillalsoneedatleastJavaSE6tobeabletocompileandrunyourapplication.

2.2.IntroductiontoJerseydependencies
Jerseyisbuilt,assembledandinstalledusingApacheMaven.NonsnapshotJerseyreleasesaredeployedtotheCentralMavenRepository.Jerseyisalso beingdeployedtoJava.NetMavenrepositories,whichcontainalsoJerseySNAPSHOTversions.Incaseyouwouldwanttotestthelatestdevelopmentbuilds

checkouttheJava.NetSnapshotsMavenrepository. AnapplicationthatusesJerseyanddependsonJerseymodulesisinturnrequiredtoalsoincludeintheapplicationdependenciesthesetof3rdparty modulesthatJerseymodulesdependon.Jerseyisdesignedasapluggablecomponentarchitectureanddifferentapplicationscanthereforerequiredifferent setsofJerseymodules.ThisalsomeansthatthesetofexternalJerseydependenciesrequiredtobeincludedintheapplicationdependenciesmayvaryin eachapplicationbasedontheJerseymodulesthatarebeingusedbytheapplication. DevelopersusingMavenoraMavenawarebuildsystemintheirprojectsarelikelytofinditeasiertoincludeandmanagedependenciesoftheirapplications comparedtodevelopersusingantorotherbuildsystemsthatarenotcompatiblewithMaven.Thisdocumentwillexplaintobothmavenandnonmaven developershowtodependonJerseymodulesintheirapplication.AntdevelopersarelikelytofindtheAntTasksforMavenveryuseful.

2.3.CommonJerseyUseCases
2.3.1.ServletbasedapplicationonGlassfish
IfyouareusingGlassfishapplicationserver,youdon'tneedtopackageanythingwithyourapplication,everythingisalreadyincluded.Youjustneedto declare(provided)dependencyonJAXRSAPItobeabletocompileyourapplication.
1 2 3 4 5 6 < d e p e n d e n c y > < g r o u p I d > j a v a x . w s . r s < / g r o u p I d > < a r t i f a c t I d > j a v a x . w s . r s a p i < / a r t i f a c t I d > < v e r s i o n > 2 . 0 < / v e r s i o n > < s c o p e > p r o v i d e d < / s c o p e > < / d e p e n d e n c y >

IfyouareusinganyJerseyspecificfeature,youwillneedtodependonJerseydirectly.
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o n t a i n e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y c o n t a i n e r s e r v l e t < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < s c o p e > p r o v i d e d < / s c o p e > < / d e p e n d e n c y > < ! i f y o u a r e u s i n g J e r s e y c l i e n t s p e c i f i c f e a t u r e s > < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o r e < / g r o u p I d > < a r t i f a c t I d > j e r s e y c l i e n t < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < s c o p e > p r o v i d e d < / s c o p e > < / d e p e n d e n c y >

2.3.2.Servletbasedserversideapplication
Followingdependenciesapplytoapplicationserver(servletcontainers)withoutanyintegratedJAXRSimplementation.Thenapplicationneedstoinclude JAXRSAPIandJerseyimplementationindeployedapplication.
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o n t a i n e r s < / g r o u p I d > < ! i f y o u r c o n t a i n e r i m p l e m e n t s S e r v l e t A P I o l d e r t h a n 3 . 0 , u s e " j e r s e y c o n t a i n e r s e r v l e t c o r e " > < a r t i f a c t I d > j e r s e y c o n t a i n e r s e r v l e t < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y > < ! R e q u i r e d o n l y w h e n y o u a r e u s i n g J A X R S C l i e n t > < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o r e < / g r o u p I d > < a r t i f a c t I d > j e r s e y c l i e n t < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

2.3.3.ClientapplicationonJDK
ApplicationsrunningonplainJDKusingonlyclientpartofJAXRSspecificationneedtodependonlyonclient.Therearevariousadditionalmoduleswhichcan beadded,likeforexamplegrizzlyorapacheconnector(seedependenciessnippedbelow).JerseyclientrunsbydefaultwithplainJDK(using HttpUrlConnection).SeeChapter5,ClientAPI.formoredetails.
1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o r e < / g r o u p I d > < a r t i f a c t I d > j e r s e y c l i e n t < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Currentlyavailableconnectors:
1 2 3 4 5 6 7 8 9 1 0 1 1 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o n n e c t o r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y g r i z z l y c o n n e c t o r < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y > < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o n n e c t o r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y a p a c h e c o n n e c t o r < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

2.3.4.Serversideapplicationonsupportedcontainers
ApartforastandardJAXRSServletbaseddeploymentthatworkswithanyServletcontainerthatsupportsServlet2.5andhigher,Jerseyprovidessupportfor programmaticdeploymenttothefollowingcontainers:Grizzly2(HTTPandServlet),JDKHttpserverandSimpleHttpserver.Thischapterpresentsonly requiredmavendependencies,moreinformationcanbefoundinChapter4,DeployingaRESTfulWebService.
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o n t a i n e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y c o n t a i n e r g r i z z l y 2 h t t p < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y > < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o n t a i n e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y c o n t a i n e r g r i z z l y 2 s e r v l e t < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y > < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o n t a i n e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y c o n t a i n e r j d k h t t p < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

1 6 1 7 1 8 1 9 2 0

< d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . c o n t a i n e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y c o n t a i n e r s i m p l e h t t p < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

2.4.Listofmodules
ThefollowingchaptersprovideanoverviewofallJerseymodulesandtheirdependencieswithlinkstotherespectivebinaries(followalinkonamodulename togetcompletesetofdownloadabledependencies). Table2.1.JerseyCore
Core jerseyclient jerseycommon jerseyserver Jerseycoreclientimplementation. Jerseycorecommonpackages. Jerseycoreserverimplementation.

Table2.2.JerseyContainers
Containers jerseycontainergrizzly2http jerseycontainergrizzly2servlet jerseycontainerjdkhttp jerseycontainerservlet jerseycontainerservletcore jerseycontainersimplehttp Grizzly2HttpContainer. Grizzly2ServletContainer. JDKHttpContainer. JerseycoreServlet3.ximplementation. JerseycoreServlet2.ximplementation. SimpleHttpContainer.

Table2.3.JerseyConnectors
Connectors jerseygrizzlyconnector jerseyapacheconnector JerseyClientTransportviaGrizzly. JerseyClientTransportviaApache.

Table2.4.JerseyMedia
Media jerseymediajsonjackson jerseymediajsonjettison jerseymediajsonprocessing jerseymediamoxy jerseymediamultipart jerseymediasse JerseyJSONJacksonentityproviderssupportmodule. JerseyJSONJettisonentityproviderssupportmodule. JerseyJSONP(JSR353)entityproviderssupportproxymodule. JerseyJSONentityproviderssupportmodulebasedonEclipseLinkMOXy. JerseyMultipartentityproviderssupportmodule. JerseyServerSentEventsentityproviderssupportmodule.

Table2.5.JerseyExtensions
Extensions jerseybeanvalidation jerseymvc jerseymvcfreemarker jerseymvcjsp jerseyproxyclient jerseyservletportability jerseywadldoclet JerseyextensionmoduleprovidingsupportforBeanValidation(JSR349)API. JerseyextensionmoduleprovidingsupportforMVC. JerseyextensionmoduleprovidingsupportforFreemarkertemplates. JerseyextensionmoduleprovidingsupportforJSPtemplates. Jerseyextensionmoduleprovidingsupportfor(proxybased)highlevelclientAPI. LibrarythatenableswritingwebapplicationsthatrunwithbothJersey1.xandJersey2.xservletcontainers. Adocletthatgeneratesaresourcedocxmlfile:thisfilecontainsthejavadocdocumentationofresourceclasses,sothatthiscanbe usedforextendinggeneratedwadlwithusefuldocumentation.

Table2.6.JerseyTestFramework
TestFramework jerseytestframeworkcore jerseytestframeworkprovider bundle jerseytestframeworkprovider defaultclient jerseytestframeworkprovider external jerseytestframeworkprovider grizzly2 jerseytestframeworkprovider inmemory jerseytestframeworkproviderjdk http jerseytestframeworkprovider simple JerseyTestFrameworkCore. JerseyTestFrameworkProvidersBundle. JerseyTestFrameworkDefaultClientProvider. JerseyTestFrameworkExternalcontainer.

JerseyTestFrameworkGrizzly2container. JerseyTestFrameworkInMemorycontainer. JerseyTestFrameworkJDKHTTPcontainer. JerseyTestFrameworkSimpleHTTPcontainer.

Table2.7.JerseyGlassfishBundles
GlassfishBundles jerseygfcdi jerseygfejb JerseyCDIforGlassFishintegration. JerseyEJBforGlassFishintegration.

Table2.8.JerseyExamples
Examples clipboard clipboardprogrammatic exceptionmapping helloworld helloworldprogrammatic helloworldpurejaxrs httptrace httpsclientservergrizzly jaxb jaxrstypesinjection jsonjackson jsonjettison jsonmoxy jsonwithpadding managedclient osgihelloworldwebapp osgihelloworldwebapp osgihelloworldwebapp osgihttpservice osgihttpservice reload serverasync serverasyncmanaged serverasyncstandalone serversentevents simpleconsole ssetwitteraggregator systempropertiesexample xmlmoxy Jerseyclipboardexample. JerseyprogrammaticresourceAPIclipboardexample. Jerseyexampleshowingexceptionmappersinaction. Jerseyannotatedresourceclass"Helloworld"example. JerseyprogrammaticresourceAPI"Helloworld"example. ExampleusingonlythestandardJAXRSAPI'sandthelightweightHTTPserverbundledinJDK. JerseyHTTPTRACEsupportexample JerseyHTTPSClient/ServerexampleonGrizzly. JerseyJAXBexample. JerseyJAXRStypesinjectionexample. JerseyJSONwithJacksonexample. JerseyJSONwithJettisonJAXBexample. JerseyJSONwithMOXyexample. JerseyJSONwithPaddingexample. Jerseymanagedclientexample. OSGiHelloworld. OSGiHelloworldbundle. OSGiHelloworldwar. OSGiHelloworld. OSGiHelloworld. Jerseyresourceconfigurationreloadexample. JerseyJAXRSasynchronousserversideexample. JerseyJAXRSasynchronousserversideexamplewithcustomJerseyexecutorproviders. StandaloneJerseyJAXRSasynchronousserversideprocessingexample. JerseyServerSentEventsexample. JerseySimpleConsoleexample. JerseySSETwitterMessageAggregatorExample. Jerseysystempropertiesexample. JerseyXMLMOXyexample.

Table2.9.JerseyExamplesWebApps
ExamplesWAR beanvalidationwebapp bookmark bookmarkem bookstorewebapp cdiwebapp extendedwadlwebapp freemarkerwebapp helloworldwebapp httpsserverglassfish jerseyejb jsonprocessingwebapp managedbeanswebapp managedclientsimplewebapp managedclientwebapp multipartwebapp sseitemstorewebapp JerseyBeanValidation(JSR349)example. JerseyBookmarkexample. JerseyBookmarkexampleusingEntityManager. JerseyMVCBookstoreexample. JerseyCDIexample. ExtendedWADLexample. JerseyFreemarkerexample. Jerseyannotatedresourceclass"Helloworld"example. JerseyHTTPSserveronGlassFishexample. JerseyEJBexample. JerseyJSONP(JSR353)example. JerseyManagedBeansWebApplicationexample. JerseyManagedClientSimpleWebappexample. Jerseymanagedclientwebapplicationexample. JerseyMultipartexample. JerseySSEbaseditemstoreexample.

Chapter3.JAXRSApplication,ResourcesandSubResources
TableofContents 3.1.RootResourceClasses 3.1.1.@Path

3.1.2.@GET,@PUT,@POST,@DELETE,...(HTTPMethods) 3.1.3.@Produces 3.1.4.@Consumes 3.2.ParameterAnnotations(@*Param) 3.3.Subresources 3.4.LifecycleofRootResourceClasses 3.5.RulesofInjection 3.6.Useof@Context 3.7.Programmaticresourcemodel ThischapterpresentsanoverviewofthecoreJAXRSconceptsresourcesandsubresources. TheJAXRS2.0JavaDoccanbefoundonlinehere. TheJAXRS2.0specificationdraftcanbefoundonlinehere.

3.1.RootResourceClasses
RootresourceclassesarePOJOs(PlainOldJavaObjects)thatareannotatedwith@Pathhaveatleastonemethodannotatedwith@Pathoraresource methoddesignatorannotationsuchas@GET,@PUT,@POST,@DELETE.Resourcemethodsaremethodsofaresourceclassannotatedwitharesource methoddesignator.ThissectionshowshowtouseJerseytoannotateJavaobjectstocreateRESTfulwebservices. ThefollowingcodeexampleisaverysimpleexampleofarootresourceclassusingJAXRSannotations.Theexamplecodeshownhereisfromoneofthe samplesthatshipswithJersey,thezipfileofwhichcanbefoundinthemavenrepositoryhere. Example3.1.Simplehelloworldrootresourceclass
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 p a c k a g e o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . h e l l o w o r l d i m p o r t j a v a x . w s . r s . G E T i m p o r t j a v a x . w s . r s . P a t h i m p o r t j a v a x . w s . r s . P r o d u c e s @ P a t h ( " h e l l o w o r l d " ) p u b l i c c l a s s H e l l o W o r l d R e s o u r c e { p u b l i c s t a t i c f i n a l S t r i n g C L I C H E D _ M E S S A G E = " H e l l o W o r l d ! " @ G E T @ P r o d u c e s ( " t e x t / p l a i n " ) p u b l i c S t r i n g g e t H e l l o ( ) { r e t u r n C L I C H E D _ M E S S A G E } }

Let'slookatsomeoftheJAXRSannotationsusedinthisexample.

3.1.1.@Path
The@Pathannotation'svalueisarelativeURIpath.Intheexampleabove,theJavaclasswillbehostedattheURIpath/ h e l l o w o r l d .Thisisanextremely simpleuseofthe@Pathannotation.WhatmakesJAXRSsousefulisthatyoucanembedvariablesintheURIs. URIpathtemplatesareURIswithvariablesembeddedwithintheURIsyntax.Thesevariablesaresubstitutedatruntimeinorderforaresourcetorespondto arequestbasedonthesubstitutedURI.Variablesaredenotedbycurlybraces.Forexample,lookatthefollowing@Pathannotation:
@ P a t h ( " / u s e r s / { u s e r n a m e } " )

Inthistypeofexample,auserwillbepromptedtoentertheirname,andthenaJerseywebserviceconfiguredtorespondtorequeststothisURIpath templatewillrespond.Forexample,iftheuserenteredtheirusernameas"Galileo",thewebservicewillrespondtothefollowingURL:
h t t p : / / e x a m p l e . c o m / u s e r s / G a l i l e o

Toobtainthevalueoftheusernamevariablethe@PathParammaybeusedonmethodparameterofarequestmethod,forexample: Example3.2.SpecifyingURIpathparameter
1 2 3 4 5 6 7 8 9 @ P a t h ( " / u s e r s / { u s e r n a m e } " ) p u b l i c c l a s s U s e r R e s o u r c e { @ G E T @ P r o d u c e s ( " t e x t / x m l " ) p u b l i c S t r i n g g e t U s e r ( @ P a t h P a r a m ( " u s e r n a m e " ) S t r i n g u s e r N a m e ) { . . . } }

Ifitisrequiredthatausernamemustonlyconsistofloweranduppercasenumericcharactersthenitispossibletodeclareaparticularregularexpression, whichoverridesthedefaultregularexpression,"[^/]+?",forexample:
1 @ P a t h ( " u s e r s / { u s e r n a m e : [ a z A Z ] [ a z A Z _ 0 9 ] * } " )

Inthistypeofexampletheusernamevariablewillonlymatchusernamesthatbeginwithoneupperorlowercaseletterandzeroormorealphanumeric charactersandtheunderscorecharacter.Ifausernamedoesnotmatchthata404(NotFound)responsewilloccur. A@Pathvaluemayormaynotbeginwitha'/',itmakesnodifference.Likewise,bydefault,a@Pathvaluemayormaynotendina'/',itmakesnodifference, andthusrequestURLsthatendordonotendina'/'willbothbematched.

3.1.2.@GET,@PUT,@POST,@DELETE,...(HTTPMethods)
@GET,@PUT,@POST,@DELETEand@HEADareresourcemethoddesignatorannotationsdefinedbyJAXRSandwhichcorrespondtothesimilarly namedHTTPmethods.Intheexampleabove,theannotatedJavamethodwillprocessHTTPGETrequests.Thebehaviorofaresourceisdeterminedby whichoftheHTTPmethodstheresourceisrespondingto. ThefollowingexampleisanextractfromthestorageservicesamplethatshowstheuseofthePUTmethodtocreateorupdateastoragecontainer: Example3.3.PUTmethod
1 2 3 4 5 6 7 @ P U T p u b l i c R e s p o n s e p u t C o n t a i n e r ( ) { S y s t e m . o u t . p r i n t l n ( " P U T C O N T A I N E R " + c o n t a i n e r ) U R I u r i = u r i I n f o . g e t A b s o l u t e P a t h ( ) C o n t a i n e r c = n e w C o n t a i n e r ( c o n t a i n e r , u r i . t o S t r i n g ( ) )

8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7

R e s p o n s e r i f ( ! M e m o r y S t o r e . M S . h a s C o n t a i n e r ( c ) ) { r = R e s p o n s e . c r e a t e d ( u r i ) . b u i l d ( ) } e l s e { r = R e s p o n s e . n o C o n t e n t ( ) . b u i l d ( ) } M e m o r y S t o r e . M S . c r e a t e C o n t a i n e r ( c ) r e t u r n r }

BydefaulttheJAXRSruntimewillautomaticallysupportthemethodsHEADandOPTIONS,ifnotexplicitlyimplemented.ForHEADtheruntimewillinvokethe implementedGETmethod(ifpresent)andignoretheresponseentity(ifset).AresponsereturnedfortheOPTIONSmethoddependsontherequestedmedia typedefinedinthe'Accept'header.TheOPTIONSmethodcanreturnaresponsewithasetofsupportedresourcemethodsinthe'Allow'headerorreturna WADLdocument.Seewadlsectionformoreinformation.

3.1.3.@Produces
The@ProducesannotationisusedtospecifytheMIMEmediatypesofrepresentationsaresourcecanproduceandsendbacktotheclient.Inthisexample, theJavamethodwillproducerepresentationsidentifiedbytheMIMEmediatype"text/plain".@Producescanbeappliedatboththeclassandmethodlevels. Here'sanexample: Example3.4.SpecifyingoutputMIMEtype
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 @ P a t h ( " / m y R e s o u r c e " ) @ P r o d u c e s ( " t e x t / p l a i n " ) p u b l i c c l a s s S o m e R e s o u r c e { @ G E T p u b l i c S t r i n g d o G e t A s P l a i n T e x t ( ) { . . . } @ G E T @ P r o d u c e s ( " t e x t / h t m l " ) p u b l i c S t r i n g d o G e t A s H t m l ( ) { . . . } }

Thed o G e t A s P l a i n T e x t methoddefaultstotheMIMEtypeofthe@Producesannotationattheclasslevel.Thed o G e t A s H t m l method's@Produces annotationoverridestheclasslevel@Producessetting,andspecifiesthatthemethodcanproduceHTMLratherthanplaintext. IfaresourceclassiscapableofproducingmorethatoneMIMEmediatypethentheresourcemethodchosenwillcorrespondtothemostacceptablemedia typeasdeclaredbytheclient.MorespecificallytheAcceptheaderoftheHTTPrequestdeclareswhatismostacceptable.ForexampleiftheAcceptheaderis "A c c e p t : t e x t / p l a i n "thenthed o G e t A s P l a i n T e x t methodwillbeinvoked.AlternativelyiftheAcceptheaderis"A c c e p t : t e x t / p l a i n q = 0 . 9 , t e x t / h t m l ",whichdeclaresthattheclientcanacceptmediatypesof"text/plain"and"text/html"butprefersthelatter,thenthed o G e t A s H t m l methodwillbe invoked. Morethanonemediatypemaybedeclaredinthesame@Producesdeclaration,forexample: Example3.5.UsingmultipleoutputMIMEtypes
1 2 3 4 5 @ G E T @ P r o d u c e s ( { " a p p l i c a t i o n / x m l " , " a p p l i c a t i o n / j s o n " } ) p u b l i c S t r i n g d o G e t A s X m l O r J s o n ( ) { . . . }

Thed o G e t A s X m l O r J s o n methodwillgetinvokedifeitherofthemediatypes"application/xml"and"application/json"areacceptable.Ifbothareequally acceptablethentheformerwillbechosenbecauseitoccursfirst. Optionally,servercanalsospecifythequalityfactorforindividualmediatypes.Theseareconsideredifseveralareequallyacceptablebytheclient.For example: Example3.6.Serversidecontentnegotiation


1 2 3 4 5 @ G E T @ P r o d u c e s ( { " a p p l i c a t i o n / x m l q s = 0 . 9 " , " a p p l i c a t i o n / j s o n " } ) p u b l i c S t r i n g d o G e t A s X m l O r J s o n ( ) { . . . }

Intheabovesample,ifclientacceptsboth"application/xml"and"application/json"(equally),thenaserveralwayssends"application/json",since "application/xml"hasalowerqualityfactor. TheexamplesaboverefersexplicitlytoMIMEmediatypesforclarity.Itispossibletorefertoconstantvalues,whichmayreducetypographicalerrors,seethe constantfieldvaluesofMediaType.

3.1.4.@Consumes
The@ConsumesannotationisusedtospecifytheMIMEmediatypesofrepresentationsthatcanbeconsumedbyaresource.Theaboveexamplecanbe modifiedtosettheclichedmessageasfollows: Example3.7.SpecifyinginputMIMEtype
1 2 3 4 5 @ P O S T @ C o n s u m e s ( " t e x t / p l a i n " ) p u b l i c v o i d p o s t C l i c h e d M e s s a g e ( S t r i n g m e s s a g e ) { / / S t o r e t h e m e s s a g e }

Inthisexample,theJavamethodwillconsumerepresentationsidentifiedbytheMIMEmediatype"text/plain".Noticethattheresourcemethodreturnsvoid. Thismeansnorepresentationisreturnedandresponsewithastatuscodeof204(NoContent)willbereturnedtotheclient. @Consumescanbeappliedatboththeclassandthemethodlevelsandmorethanonemediatypemaybedeclaredinthesame@Consumesdeclaration.

3.2.ParameterAnnotations(@*Param)
Parametersofaresourcemethodmaybeannotatedwithparameterbasedannotationstoextractinformationfromarequest.Oneofthepreviousexamples

presentedtheuseof@PathParamtoextractapathparameterfromthepathcomponentoftherequestURLthatmatchedthepathdeclaredin@Path. @QueryParamisusedtoextractqueryparametersfromtheQuerycomponentoftherequestURL.Thefollowingexampleisanextractfromthesparklines sample: Example3.8.Queryparameters


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 @ P a t h ( " s m o o t h " ) @ G E T p u b l i c R e s p o n s e s m o o t h ( @ D e f a u l t V a l u e ( " 2 " ) @ Q u e r y P a r a m ( " s t e p " ) i n t s t e p , @ D e f a u l t V a l u e ( " t r u e " ) @ Q u e r y P a r a m ( " m i n m " ) b o o l e a n h a s M i n , @ D e f a u l t V a l u e ( " t r u e " ) @ Q u e r y P a r a m ( " m a x m " ) b o o l e a n h a s M a x , @ D e f a u l t V a l u e ( " t r u e " ) @ Q u e r y P a r a m ( " l a s t m " ) b o o l e a n h a s L a s t , @ D e f a u l t V a l u e ( " b l u e " ) @ Q u e r y P a r a m ( " m i n c o l o r " ) C o l o r P a r a m m i n C o l o r , @ D e f a u l t V a l u e ( " g r e e n " ) @ Q u e r y P a r a m ( " m a x c o l o r " ) C o l o r P a r a m m a x C o l o r , @ D e f a u l t V a l u e ( " r e d " ) @ Q u e r y P a r a m ( " l a s t c o l o r " ) C o l o r P a r a m l a s t C o l o r ) { . . . }

Ifaqueryparameter"step"existsinthequerycomponentoftherequestURIthenthe"step"valuewillbewillextractedandparsedasa32bitsignedinteger andassignedtothestepmethodparameter.If"step"doesnotexistthenadefaultvalueof2,asdeclaredinthe@DefaultValueannotation,willbeassignedto thestepmethodparameter.Ifthe"step"valuecannotbeparsedasa32bitsignedintegerthenaHTTP404(NotFound)responseisreturned.Userdefined JavatypessuchasC o l o r P a r a m maybeused,whichasimplementedasfollows: Example3.9.CustomJavatypeforconsumingrequestparameters


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 p u b l i c c l a s s C o l o r P a r a m e x t e n d s C o l o r { p u b l i c C o l o r P a r a m ( S t r i n g s ) { s u p e r ( g e t R G B ( s ) ) } p r i v a t e s t a t i c i n t g e t R G B ( S t r i n g s ) { i f ( s . c h a r A t ( 0 ) = = ' # ' ) { t r y { C o l o r c = C o l o r . d e c o d e ( " 0 x " + s . s u b s t r i n g ( 1 ) ) r e t u r n c . g e t R G B ( ) } c a t c h ( N u m b e r F o r m a t E x c e p t i o n e ) { t h r o w n e w W e b A p p l i c a t i o n E x c e p t i o n ( 4 0 0 ) } } e l s e { t r y { F i e l d f = C o l o r . c l a s s . g e t F i e l d ( s ) r e t u r n ( ( C o l o r ) f . g e t ( n u l l ) ) . g e t R G B ( ) } c a t c h ( E x c e p t i o n e ) { t h r o w n e w W e b A p p l i c a t i o n E x c e p t i o n ( 4 0 0 ) } } } }

IngeneraltheJavatypeofthemethodparametermay: 1. Beaprimitivetype 2. HaveaconstructorthatacceptsasingleS t r i n g argument 3. Haveastaticmethodnamedv a l u e O f orf r o m S t r i n g thatacceptsasingleS t r i n g argument(see,forexample,I n t e g e r . v a l u e O f ( S t r i n g ) and j a v a . u t i l . U U I D . f r o m S t r i n g ( S t r i n g ) ) 4. Havearegisteredimplementationofj a v a x . w s . r s . e x t . P a r a m C o n v e r t e r P r o v i d e r JAXRSextensionSPIthatreturnsa j a v a x . w s . r s . e x t . P a r a m C o n v e r t e r instancecapableofa"fromstring"conversionforthetype.or 5. BeL i s t < T > ,S e t < T > orS o r t e d S e t < T > ,whereT satisfies2or3above.Theresultingcollectionisreadonly. Sometimesparametersmaycontainmorethanonevalueforthesamename.Ifthisisthecasethentypesin5)maybeusedtoobtainallvalues. Ifthe@DefaultValueisnotusedinconjunctionwith@QueryParamandthequeryparameterisnotpresentintherequestthenvaluewillbeanempty collectionforL i s t ,S e t orS o r t e d S e t ,n u l l forotherobjecttypes,andtheJavadefineddefaultforprimitivetypes. The@PathParamandtheotherparameterbasedannotations,@MatrixParam,@HeaderParam,@CookieParam,@FormParamobeythesamerulesas @QueryParam.@MatrixParamextractsinformationfromURLpathsegments.@HeaderParamextractsinformationfromtheHTTPheaders.@CookieParam extractsinformationfromthecookiesdeclaredincookierelatedHTTPheaders. @FormParamisslightlyspecialbecauseitextractsinformationfromarequestrepresentationthatisoftheMIMEmediatype" a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d " andconformstotheencodingspecifiedbyHTMLforms,asdescribedhere.Thisparameterisveryusefulforextractinginformationthatis POSTedbyHTMLforms,forexamplethefollowingextractstheformparameternamed"name"fromthePOSTedformdata: Example3.10.ProcessingPOSTedHTMLform
1 2 3 4 5 @ P O S T @ C o n s u m e s ( " a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d " ) p u b l i c v o i d p o s t ( @ F o r m P a r a m ( " n a m e " ) S t r i n g n a m e ) { / / S t o r e t h e m e s s a g e }

Ifitisnecessarytoobtainageneralmapofparameternametovaluesthen,forqueryandpathparametersitispossibletodothefollowing: Example3.11.ObtaininggeneralmapofURIpathand/orqueryparameters
1 2 3 4 5 @ G E T p u b l i c S t r i n g g e t ( @ C o n t e x t U r i I n f o u i ) { M u l t i v a l u e d M a p < S t r i n g , S t r i n g > q u e r y P a r a m s = u i . g e t Q u e r y P a r a m e t e r s ( ) M u l t i v a l u e d M a p < S t r i n g , S t r i n g > p a t h P a r a m s = u i . g e t P a t h P a r a m e t e r s ( ) }

Forheaderandcookieparametersthefollowing:

Example3.12.Obtaininggeneralmapofheaderparameters
1 2 3 4 5 @ G E T p u b l i c S t r i n g g e t ( @ C o n t e x t H t t p H e a d e r s h h ) { M u l t i v a l u e d M a p < S t r i n g , S t r i n g > h e a d e r P a r a m s = h h . g e t R e q u e s t H e a d e r s ( ) M a p < S t r i n g , C o o k i e > p a t h P a r a m s = h h . g e t C o o k i e s ( ) }

Ingeneral@ContextcanbeusedtoobtaincontextualJavatypesrelatedtotherequestorresponse. Becauseformparameters(unlikeothers)arepartofthemessageentity,itispossibletodothefollowing: Example3.13.Obtaininggeneralmapofformparameters


1 2 3 4 5 @ P O S T @ C o n s u m e s ( " a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d " ) p u b l i c v o i d p o s t ( M u l t i v a l u e d M a p < S t r i n g , S t r i n g > f o r m P a r a m s ) { / / S t o r e t h e m e s s a g e }

I.e.youdon'tneedtousethe@Contextannotation. Anotherkindofinjectionisthe@BeanParamwhichallowstoinjecttheparametersdescribedaboveintoasinglebean.Abeanannotatedwith@BeanParam containinganyfieldsandappropriate* p a r a m annotation(like@PathParam)willbeinitializedwithcorrespondingrequestvaluesinexpectedwayasifthese fieldswereintheresourceclass.Theninsteadofinjectingrequestvalueslikepathparamintoaconstructorparametersorclassfieldsthe@BeanParamcan beusedtoinjectsuchabeanintoaresourceorresourcemethod.The@BeanParamisusedthiswaytoaggregatemorerequestparametersintoasingle bean. Example3.14.Exampleofthebeanwhichwillbeusedas@BeanParam


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 p u b l i c c l a s s M y B e a n P a r a m { @ P a t h P a r a m ( " p " ) p r i v a t e S t r i n g p a t h P a r a m @ M a t r i x P a r a m ( " m " ) @ E n c o d e d @ D e f a u l t V a l u e ( " d e f a u l t " ) p r i v a t e S t r i n g m a t r i x P a r a m @ H e a d e r P a r a m ( " h e a d e r " ) p r i v a t e S t r i n g h e a d e r P a r a m p r i v a t e S t r i n g q u e r y P a r a m p u b l i c M y B e a n P a r a m ( @ Q u e r y P a r a m ( " q " ) S t r i n g q u e r y P a r a m ) { t h i s . q u e r y P a r a m = q u e r y P a r a m } p u b l i c S t r i n g g e t P a t h P a r a m ( ) { r e t u r n p a t h P a r a m } . . . }

Example3.15.InjectionofMyBeanParamasamethodparameter:
1 2 3 4 5 @ P O S T p u b l i c v o i d p o s t ( @ B e a n P a r a m M y B e a n P a r a m b e a n P a r a m , S t r i n g e n t i t y ) { f i n a l S t r i n g p a t h P a r a m = b e a n P a r a m . g e t P a t h P a r a m ( ) / / c o n t a i n s i n j e c t e d p a t h p a r a m e t e r " p " . . . }

Theexampleshowsaggregationofinjections@PathParam,@QueryParam@MatrixParamand@HeaderParamintoonesinglebean.Therulesforinjections insidethebeanarethesameasdescribedabovefortheseinjections.The@DefaultValueisusedtodefinethedefaultvalueformatrixparameter matrixParam.Alsothe@Encodedannotationhasthesamebehaviourasifitwereusedforinjectionintheresourcemethoddirectly.Injectingthebean parameterinto@Singletonresourceclassfieldsisnotallowed(injectionsintomethodparametermustbeusedinstead). @BeanParamcancontainallparametersinjectionsinjections(@PathParam,@QueryParam,@MatrixParam,@HeaderParam,@CookieParam, @FormParam).Morebeanscanbeinjectedintooneresourceormethodparameterseveniftheyinjectthesamerequestvalues.Forexamplethefollowingis possible: Example3.16.Injectionofmorebeansintooneresourcemethods:


1 2 3 4 5 6 @ P O S T p u b l i c v o i d p o s t ( @ B e a n P a r a m M y B e a n P a r a m b e a n P a r a m , @ B e a n P a r a m A n o t h e r B e a n a n o t h e r B e a n , @ P a t h P a r a m ( " p " ) p a t h P a r a m , S t r i n g e n t i t y ) { / / b e a n P a r a m . g e t P a t h P a r a m ( ) = = p a t h P a r a m . . . }

3.3.Subresources
@Pathmaybeusedonclassesandsuchclassesarereferredtoasrootresourceclasses.@Pathmayalsobeusedonmethodsofrootresourceclasses. Thisenablescommonfunctionalityforanumberofresourcestobegroupedtogetherandpotentiallyreused. Thefirstway@Pathmaybeusedisonresourcemethodsandsuchmethodsarereferredtoassubresourcemethods.Thefollowingexampleshowsthe methodsignaturesforarootresourceclassfromthejmakibackendsample: Example3.17.Subresourcemethods
1 2 3 4 5 6 7 8 9 @ S i n g l e t o n @ P a t h ( " / p r i n t e r s " ) p u b l i c c l a s s P r i n t e r s R e s o u r c e { @ G E T @ P r o d u c e s ( { " a p p l i c a t i o n / j s o n " , " a p p l i c a t i o n / x m l " } ) p u b l i c W e b R e s o u r c e L i s t g e t M y R e s o u r c e s ( ) { . . . } @ G E T @ P a t h ( " / l i s t " )

1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1

@ P r o d u c e s ( { " a p p l i c a t i o n / j s o n " , " a p p l i c a t i o n / x m l " } ) p u b l i c W e b R e s o u r c e L i s t g e t L i s t O f P r i n t e r s ( ) { . . . } @ G E T @ P a t h ( " / j M a k i T a b l e " ) @ P r o d u c e s ( " a p p l i c a t i o n / j s o n " ) p u b l i c P r i n t e r T a b l e M o d e l g e t T a b l e ( ) { . . . } @ G E T @ P a t h ( " / j M a k i T r e e " ) @ P r o d u c e s ( " a p p l i c a t i o n / j s o n " ) p u b l i c T r e e M o d e l g e t T r e e ( ) { . . . } @ G E T @ P a t h ( " / i d s / { p r i n t e r i d } " ) @ P r o d u c e s ( { " a p p l i c a t i o n / j s o n " , " a p p l i c a t i o n / x m l " } ) p u b l i c P r i n t e r g e t P r i n t e r ( @ P a t h P a r a m ( " p r i n t e r i d " ) S t r i n g p r i n t e r I d ) { . . . } @ P U T @ P a t h ( " / i d s / { p r i n t e r i d } " ) @ C o n s u m e s ( { " a p p l i c a t i o n / j s o n " , " a p p l i c a t i o n / x m l " } ) p u b l i c v o i d p u t P r i n t e r ( @ P a t h P a r a m ( " p r i n t e r i d " ) S t r i n g p r i n t e r I d , P r i n t e r p r i n t e r ) { . . . } @ D E L E T E @ P a t h ( " / i d s / { p r i n t e r i d } " ) p u b l i c v o i d d e l e t e P r i n t e r ( @ P a t h P a r a m ( " p r i n t e r i d " ) S t r i n g p r i n t e r I d ) { . . . } }

IfthepathoftherequestURLis"printers"thentheresourcemethodsnotannotatedwith@Pathwillbeselected.IftherequestpathoftherequestURLis "printers/list"thenfirsttherootresourceclasswillbematchedandthenthesubresourcemethodsthatmatch"list"willbeselected,whichinthiscaseisthe subresourcemethodg e t L i s t O f P r i n t e r s .So,inthisexamplehierarchicalmatchingonthepathoftherequestURLisperformed. Thesecondway@Pathmaybeusedisonmethodsnotannotatedwithresourcemethoddesignatorssuchas@GETor@POST.Suchmethodsarereferred toassubresourcelocators.Thefollowingexampleshowsthemethodsignaturesforarootresourceclassandaresourceclassfromtheoptimistic concurrencysample: Example3.18.Subresourcelocators


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 @ P a t h ( " / i t e m " ) p u b l i c c l a s s I t e m R e s o u r c e { @ C o n t e x t U r i I n f o u r i I n f o @ P a t h ( " c o n t e n t " ) p u b l i c I t e m C o n t e n t R e s o u r c e g e t I t e m C o n t e n t R e s o u r c e ( ) { r e t u r n n e w I t e m C o n t e n t R e s o u r c e ( ) } @ G E T @ P r o d u c e s ( " a p p l i c a t i o n / x m l " ) p u b l i c I t e m g e t ( ) { . . . } } } p u b l i c c l a s s I t e m C o n t e n t R e s o u r c e { @ G E T p u b l i c R e s p o n s e g e t ( ) { . . . } @ P U T @ P a t h ( " { v e r s i o n } " ) p u b l i c v o i d p u t ( @ P a t h P a r a m ( " v e r s i o n " ) i n t v e r s i o n , @ C o n t e x t H t t p H e a d e r s h e a d e r s , b y t e [ ] i n ) { . . . } }

TherootresourceclassI t e m R e s o u r c e containsthesubresourcelocatormethodg e t I t e m C o n t e n t R e s o u r c e thatreturnsanewresourceclass.Ifthepath oftherequestURLis"item/content"thenfirstofalltherootresourcewillbematched,thenthesubresourcelocatorwillbematchedandinvoked,which returnsaninstanceoftheI t e m C o n t e n t R e s o u r c e resourceclass.Subresourcelocatorsenablereuseofresourceclasses.Amethodcanbeannotatedwith the@Pathannotationwithemptypath(@ P a t h ( " / " ) or@ P a t h ( " " ) )whichmeansthatthesubresourcelocatorismatchedforthepathoftheenclosing resource(withoutsubresourcepath). Example3.19.Subresourcelocatorswithemptypath
1 2 3 4 5 6 7 8 @ P a t h ( " / i t e m " ) p u b l i c c l a s s I t e m R e s o u r c e { @ P a t h ( " / " ) p u b l i c I t e m C o n t e n t R e s o u r c e g e t I t e m C o n t e n t R e s o u r c e ( ) { r e t u r n n e w I t e m C o n t e n t R e s o u r c e ( ) } }

Intheexampleabovethesubresourcelocatormethodg e t I t e m C o n t e n t R e s o u r c e ismatchedforexampleforrequestpath"/item/locator"orevenforonly "/item". Inadditiontheprocessingofresourceclassesreturnedbysubresourcelocatorsisperformedatruntimethusitispossibletosupportpolymorphism.Asub resourcelocatormayreturndifferentsubtypesdependingontherequest(forexampleasubresourcelocatorcouldreturndifferentsubtypesdependenton theroleoftheprinciplethatisauthenticated).Soforexamplethefollowingsubresourcelocatorisvalid: Example3.20.Subresourcelocatorsreturningsubtype


1 2 3 4 5 6 7 8 @ P a t h ( " / i t e m " ) p u b l i c c l a s s I t e m R e s o u r c e { @ P a t h ( " / " ) p u b l i c O b j e c t g e t I t e m C o n t e n t R e s o u r c e ( ) { r e t u r n n e w A n y R e s o u r c e ( ) } }

Notethattheruntimewillnotmanagethelifecycleorperformanyfieldinjectionontoinstancesreturnedfromsubresourcelocatormethods.Thisisbecause theruntimedoesnotknowwhatthelifecycleoftheinstanceis.IfitisrequiredthattheruntimemanagesthesubresourcesasstandardresourcestheC l a s s shouldbereturnedasshowninthefollowingexample: Example3.21.Subresourcelocatorscreatedfromclasses

1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4

i m p o r t j a v a x . i n j e c t . S i n g l e t o n @ P a t h ( " / i t e m " ) p u b l i c c l a s s I t e m R e s o u r c e { @ P a t h ( " c o n t e n t " ) p u b l i c C l a s s < I t e m C o n t e n t S i n g l e t o n R e s o u r c e > g e t I t e m C o n t e n t R e s o u r c e ( ) { r e t u r n I t e m C o n t e n t S i n g l e t o n R e s o u r c e . c l a s s } } @ S i n g l e t o n p u b l i c c l a s s I t e m C o n t e n t S i n g l e t o n R e s o u r c e { / / t h i s c l a s s i s m a n a g e d i n t h e s i n g l e t o n l i f e c y c l e }

JAXRSresourcesaremanagedinperrequestscopebydefaultwhichmeansthatnewresourceiscreatedforeachrequest.Inthisexamplethe j a v a x . i n j e c t . S i n g l e t o n annotationsaysthattheresourcewillbemanagedassingletonandnotinrequestscope.Thesubresourcelocatormethod returnsaclasswhichmeansthattheruntimewillmanagedtheresourceinstanceanditslifecycle.Ifthemethodwouldreturninstanceinstead,the S i n g l e t o n annotationwouldhavenoeffectandthereturnedinstancewouldbeused. Thesubresourcelocatorcanalsoreturnaprogrammaticresourcemodel.Seeresourcebuildersectionforinformationofhowtheprogrammaticresource modelisconstructed.Thefollowingexampleshowsverysimpleresourcereturnedfromthesubresourcelocatormethod. Example3.22.Subresourcelocatorsreturningresourcemodel


1 2 3 4 5 6 7 8 9 1 0 i m p o r t o r g . g l a s s f i s h . j e r s e y . s e r v e r . m o d e l . R e s o u r c e @ P a t h ( " / i t e m " ) p u b l i c c l a s s I t e m R e s o u r c e { @ P a t h ( " c o n t e n t " ) p u b l i c R e s o u r c e g e t I t e m C o n t e n t R e s o u r c e ( ) { r e t u r n R e s o u r c e . f r o m ( I t e m C o n t e n t S i n g l e t o n R e s o u r c e . c l a s s ) } }

Thecodeabovehasexactlythesameeffectaspreviousexample.R e s o u r c e isaresourcesimpleresourceconstructedfrom I t e m C o n t e n t S i n g l e t o n R e s o u r c e .Morecomplexprogrammaticresourcecanbereturnedaslongtheyarevalidresources.

3.4.LifecycleofRootResourceClasses
Bydefaultthelifecycleofrootresourceclassesisperrequestwhich,namelythatanewinstanceofarootresourceclassiscreatedeverytimetherequest URIpathmatchestherootresource.Thismakesforaverynaturalprogrammingmodelwhereconstructorsandfieldscanbeutilized(asintheprevious sectionshowingtheconstructoroftheS p a r k l i n e s R e s o u r c e class)withoutconcernformultipleconcurrentrequeststothesameresource. Ingeneralthisisunlikelytobeacauseofperformanceissues.ClassconstructionandgarbagecollectionofJVMshasvastlyimprovedovertheyearsand manyobjectswillbecreatedanddiscardedtoserveandprocesstheHTTPrequestandreturntheHTTPresponse. InstancesofsingletonrootresourceclassescanbedeclaredbyaninstanceofApplication. JerseysupportstwofurtherlifecyclesusingJerseyspecificannotations. Table3.1.Resourcescopes
Scope Annotation Annotationfullclassname Description

Defaultlifecycle(appliedwhennoannotationispresent).Inthisscopethe resourceinstanceiscreatedforeachnewrequestandusedforprocessingof @RequestScoped thisrequest.Iftheresourceisusedmorethanonetimeintherequest Requestscope org.glassfish.jersey.process.internal.RequestScoped (ornone) processing,alwaysthesameinstancewillbeused.Thiscanhappenwhena resourceisasubresourceisreturnedmoretimesduringthematching.Inthis situationonlyoninstancewillservertherequests. Perlookup scope @PerLookup org.glassfish.jersey.process.internal.RequestScoped Inthisscopetheresourceinstanceiscreatedeverytimeitisneededforthe processingevenithandlesthesamerequest. Inthisscopethereisonlyoneinstanceperjaxrsapplication.Singleton resourcecanbeeitherannotatedwith@Singletonanditsclasscanbe registeredusingtheinstanceofApplication.Youcanalsocreatesingletonsby registeringsingletoninstancesintoApplication.

Singleton

@Singleton

javax.inject.Singleton

3.5.RulesofInjection
Previoussectionshavepresentedexamplesofannotatedtypes,mostlyannotatedmethodparametersbutalsoannotatedfieldsofaclass,fortheinjectionof valuesontothosetypes. Thissectionpresentstherulesofinjectionofvaluesonannotatedtypes.Injectioncanbeperformedonfields,constructorparameters,resource/sub resource/subresourcelocatormethodparametersandbeansettermethods.Thefollowingpresentsanexampleofallsuchinjectioncases: Example3.23.Injection
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 @ P a t h ( " i d : \ d + " ) p u b l i c c l a s s I n j e c t e d R e s o u r c e { / / I n j e c t i o n o n t o f i e l d @ D e f a u l t V a l u e ( " q " ) @ Q u e r y P a r a m ( " p " ) p r i v a t e S t r i n g p / / I n j e c t i o n o n t o c o n s t r u c t o r p a r a m e t e r p u b l i c I n j e c t e d R e s o u r c e ( @ P a t h P a r a m ( " i d " ) i n t i d ) { . . . } / / I n j e c t i o n o n t o r e s o u r c e m e t h o d p a r a m e t e r @ G E T p u b l i c S t r i n g g e t ( @ C o n t e x t U r i I n f o u i ) { . . . } / / I n j e c t i o n o n t o s u b r e s o u r c e r e s o u r c e m e t h o d p a r a m e t e r @ P a t h ( " s u b i d " ) @ G E T p u b l i c S t r i n g g e t ( @ P a t h P a r a m ( " s u b i d " ) S t r i n g i d ) { . . . } / / I n j e c t i o n o n t o s u b r e s o u r c e l o c a t o r m e t h o d p a r a m e t e r @ P a t h ( " s u b i d " )

2 1 2 2 2 3 2 4 2 5 2 6

p u b l i c S u b R e s o u r c e g e t S u b R e s o u r c e ( @ P a t h P a r a m ( " s u b i d " ) S t r i n g i d ) { . . . } / / I n j e c t i o n u s i n g b e a n s e t t e r m e t h o d @ H e a d e r P a r a m ( " X h e a d e r " ) p u b l i c v o i d s e t H e a d e r ( S t r i n g h e a d e r ) { . . . } }

Therearesomerestrictionswheninjectingontoresourceclasseswithalifecycleofsingletonscope.Insuchcasestheclassfieldsorconstructorparameters cannotbeinjectedwithrequestspecificparameters.So,forexamplethefollowingisnotallowed. Example3.24.Wronginjectionintoasingletonscope


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 @ P a t h ( " r e s o u r c e " ) @ S i n g l e t o n p u b l i c s t a t i c c l a s s M y S i n g l e t o n R e s o u r c e { @ Q u e r y P a r a m ( " q u e r y " ) S t r i n g p a r a m / / W R O N G : i n i t i a l i z a t i o n o f a p p l i c a t i o n w i l l f a i l a s y o u c a n n o t / / i n j e c t r e q u e s t s p e c i f i c p a r a m e t e r s i n t o a s i n g l e t o n r e s o u r c e . @ G E T p u b l i c S t r i n g g e t ( ) { r e t u r n " q u e r y p a r a m : " + p a r a m } }

Theexampleabovewillcausevalidationfailureduringapplicationinitializationassingletonresourcescannotinjectrequestspecificparameters.Thesame examplewouldfailifthequeryparameterwouldbeinjectedintoconstructorparameterofsuchasingleton.Inotherwords,ifyouwishoneresourceinstance toservermorerequests(inthesametime)itcannotbeboundtoaspecificrequestparameter. Theexceptionexistsforspecificrequestobjectswhichcaninjectedevenintoconstructororclassfields.Fortheseobjectstheruntimewillinjectproxieswhich areabletosimultaneouslyservermorerequest.TheserequestobjectsareH t t p H e a d e r s ,R e q u e s t ,U r i I n f o ,S e c u r i t y C o n t e x t .Theseproxiescanbe injectedusingthe@Contextannotation.Thefollowingexampleshowsinjectionofproxiesintothesingletonresourceclass. Example3.25.Injectionofproxiesintosingleton


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 @ P a t h ( " r e s o u r c e " ) @ S i n g l e t o n p u b l i c s t a t i c c l a s s M y S i n g l e t o n R e s o u r c e { @ C o n t e x t R e q u e s t r e q u e s t / / t h i s i s o k : t h e p r o x y o f R e q u e s t w i l l b e i n j e c t e d i n t o t h i s s i n g l e t o n p u b l i c M y S i n g l e t o n R e s o u r c e ( @ C o n t e x t S e c u r i t y C o n t e x t s e c u r i t y C o n t e x t ) { / / t h i s i s o k t o o : t h e p r o x y o f S e c u r i t y C o n t e x t w i l l b e i n j e c t e d } @ G E T p u b l i c S t r i n g g e t ( ) { r e t u r n " q u e r y p a r a m : " + p a r a m } }

Tosummarizetheinjectioncanbedoneintothefollowingconstructs: Table3.2.Overviewofinjectiontypes
Javaconstruct Classfields Constructorparameters Resourcemethods Subresourcelocators Description Injectvaluedirectlyintothefieldoftheclass.Thefieldcanbeprivateandmustnotbefinal.CannotbeusedinSingletonscopeexcept proxiabletypesmentionedabove. Theconstructorwillbeinvokedwithinjectedvalues.Ifmoreconstructorsexiststheonewiththemostinjectableparameterswillbeinvoked. CannotbeusedinSingletonscopeexceptproxiabletypesmentionedabove. Theresourcemethods(theseannotatedwith@GET,@POST,...)cancontainparametersthatcanbeinjectedwhentheresourcemethodis executed.Canbeusedinanyscope. Thesubresourcelocators(methodsannotatedwith@Pathbutnot@GET,@POST,...)cancontainparametersthatcanbeinjectedwhenthe resourcemethodisexecuted.Canbeusedinanyscope. Insteadofinjectingvaluesdirectlyintofieldthevaluecanbeinjectedintothesettermethodwhichwillinitializethefield.Thisinjectioncanbe usedonlywith@Contextannotation.Thismeansitcannotbeusedforexampleforinjectingofqueryparamsbutitcanbeusedforinjections ofrequest.Thesetterswillbecalledaftertheobjectcreationandonlyonce.Thenameofthemethoddoesnotnecessaryhaveasetter pattern.CannotbeusedinSingletonscopeexceptproxiabletypesmentionedabove.

Settermethods

Thefollowingexampleshowsallpossiblejavaconstructsintowhichthevaluescanbeinjected. Example3.26.Exampleofpossibleinjections
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 @ P a t h ( " r e s o u r c e " ) p u b l i c s t a t i c c l a s s S u m m a r y O f I n j e c t i o n s R e s o u r c e { @ Q u e r y P a r a m ( " q u e r y " ) S t r i n g p a r a m / / i n j e c t i o n i n t o a c l a s s f i e l d @ G E T p u b l i c S t r i n g g e t ( @ Q u e r y P a r a m ( " q u e r y " ) S t r i n g m e t h o d Q u e r y P a r a m ) { / / i n j e c t i o n i n t o a r e s o u r c e m e t h o d p a r a m e t e r r e t u r n " q u e r y p a r a m : " + p a r a m } @ P a t h ( " s u b r e s o u r c e l o c a t o r " ) p u b l i c C l a s s < S u b R e s o u r c e > s u b R e s o u r c e L o c a t o r ( @ Q u e r y P a r a m ( " q u e r y " ) S t r i n g s u b R e s o u r c e Q u e r y P a r a m ) { / / i n j e c t i o n i n t o a s u b r e s o u r c e l o c a t o r p a r a m e t e r r e t u r n S u b R e s o u r c e . c l a s s } p u b l i c S u m m a r y O f I n j e c t i o n s R e s o u r c e ( @ Q u e r y P a r a m ( " q u e r y " ) S t r i n g c o n s t r u c t o r Q u e r y P a r a m ) { / / i n j e c t i o n i n t o a c o n s t r u c t o r p a r a m e t e r } @ C o n t e x t p u b l i c v o i d s e t R e q u e s t ( R e q u e s t r e q u e s t ) {

2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6

/ / i n j e c t i o n i n t o a s e t t e r m e t h o d S y s t e m . o u t . p r i n t l n ( r e q u e s t ! = n u l l ) } } p u b l i c s t a t i c c l a s s S u b R e s o u r c e { @ G E T p u b l i c S t r i n g g e t ( ) { r e t u r n " s u b r e s o u r c e " } }

The@FormParamannotationisspecialandmayonlybeutilizedonresourceandsubresourcemethods.Thisisbecauseitextractsinformationfroma requestentity.

3.6.Useof@Context
Previoussectionshaveintroducedtheuseof@Context.Chapter5oftheJAXRSspecificationpresentsallthestandardJAXRSJavatypesthatmaybeused with@Context. WhendeployingaJAXRSapplicationusingservletthenServletConfig,ServletContext,HttpServletRequestandHttpServletResponseareavailableusing @Context.

3.7.Programmaticresourcemodel
Resourcescanbeconstructedfromclassesorinstancesbutalsocanbeconstructedfromaprogrammaticresourcemodel.Everyresourcecreatedfromfrom resourceclassescanalsobeconstructedusingtheprogrammaticresourcebuilderapi.Seeresourcebuildersectionformoreinformation.

Chapter4.DeployingaRESTfulWebService
TableofContents 4.1.AutoDiscoverableFeatures 4.1.1.ConfiguringtheFeatureAutodiscoverymechanism 4.2.Turnoffclasspathscanning JAXRSprovidesadeploymentagnosticabstractclassApplicationfordeclaringrootresourceandproviderclasses,androotresourceandprovidersingleton instances.AWebservicemayextendthisclasstodeclarerootresourceandproviderclasses.Forexample, Example4.1.Deploymentagnosticapplicationmodel
1 2 3 4 5 6 7 8 p u b l i c c l a s s M y A p p l i c a t i o n e x t e n d s A p p l i c a t i o n { @ O v e r r i d e p u b l i c S e t < C l a s s < ? > > g e t C l a s s e s ( ) { S e t < C l a s s < ? > > s = n e w H a s h S e t < C l a s s < ? > > ( ) s . a d d ( H e l l o W o r l d R e s o u r c e . c l a s s ) r e t u r n s } }

AlternativelyitispossibletoreuseoneofJersey'simplementationsthatscansforrootresourceandproviderclassesgivenaclasspathorasetofpackage names.Suchclassesareautomaticallyaddedtothesetofclassesthatarereturnedbyg e t C l a s s e s .Forexample,thefollowingscansforrootresourceand providerclassesinpackages"org.foo.rest","org.bar.rest"andinanysubpackagesofthosetwo: Example4.2.ReusingJerseyimplementationinyourcustomapplicationmodel


1 2 3 4 5 p u b l i c c l a s s M y A p p l i c a t i o n e x t e n d s R e s o u r c e C o n f i g { p u b l i c M y A p p l i c a t i o n ( ) { p a c k a g e s ( " o r g . f o o . r e s t o r g . b a r . r e s t " ) } }

TherearemultipledeploymentoptionsfortheclassthatimplementsApplicationinterfaceintheServlet3.0container.Forsimpledeployments,now e b . x m l is neededatall.Instead,an@ApplicationPathannotationcanbeusedtoannotatetheuserdefinedapplicationclassandspecifythebaseresourceURIofall applicationresources: Example4.3.DeploymentofaJAXRSapplicationusing@ A p p l i c a t i o n P a t h withServlet3.0


1 2 3 4 5 6 7 @ A p p l i c a t i o n P a t h ( " r e s o u r c e s " ) p u b l i c c l a s s M y A p p l i c a t i o n e x t e n d s R e s o u r c e C o n f i g { p u b l i c M y A p p l i c a t i o n ( ) { p a c k a g e s ( " o r g . f o o . r e s t o r g . b a r . r e s t " ) } . . . }

PleasenotethatthereismorewhichcanbesetorcalledduringexecutionofResourceConfigdescendantsconstructor,seeResourceConfigjavadocformore details. YoualsoneedtosetmavenwarpluginattributefailOnMissingWebXmltofalseinpom.xmlwhenbuilding.warwithoutweb.xmlfileusingmaven: Example4.4.Configurationofmavenwarplugininp o m . x m l withServlet3.0


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 < p l u g i n s > . . . < p l u g i n > < g r o u p I d > o r g . a p a c h e . m a v e n . p l u g i n s < / g r o u p I d > < a r t i f a c t I d > m a v e n w a r p l u g i n < / a r t i f a c t I d > < v e r s i o n > 2 . 3 < / v e r s i o n > < c o n f i g u r a t i o n > < f a i l O n M i s s i n g W e b X m l > f a l s e < / f a i l O n M i s s i n g W e b X m l > < / c o n f i g u r a t i o n > < / p l u g i n > . . . < / p l u g i n s >

AnotherdeploymentoptionistodeclareJAXRSapplicationdetailsinthew e b . x m l .Thisisusuallysuitableincaseofmorecomplexdeployments,e.g.when

securitymodelneedstobeproperlydefinedorwhenadditionalinitializationparametershavetobepassedtoJerseyruntime.JAXRS1.1specifiesthatafully qualifiednameoftheclassthatimplementsApplicationmaybedeclaredinthe< s e r v l e t n a m e > elementoftheJAXRSapplication'sw e b . x m l .Thisis supportedinaWebcontainerimplementingServlet3.0asfollows: Example4.5.DeploymentofaJAXRSapplicationusingw e b . x m l withServlet3.0


1 2 3 4 5 6 7 8 9 1 0 1 1 < w e b a p p > < s e r v l e t > < s e r v l e t n a m e > o r g . f o o . r e s t . M y A p p l i c a t i o n < / s e r v l e t n a m e > < / s e r v l e t > . . . < s e r v l e t m a p p i n g > < s e r v l e t n a m e > o r g . f o o . r e s t . M y A p p l i c a t i o n < / s e r v l e t n a m e > < u r l p a t t e r n > / r e s o u r c e s < / u r l p a t t e r n > < / s e r v l e t m a p p i n g > . . . < / w e b a p p >

Notethatthe< s e r v l e t c l a s s > elementisomittedfromtheservletdeclaration.ThisisacorrectdeclarationutilizingtheServlet3.0extensionmechanism. Alsonotethat< s e r v l e t m a p p i n g > isusedtodefinethebaseresourceURI. WhenrunninginaServlet2.xtheninsteaditisnecessarytodeclaretheJerseyspecificservletandpasstheApplicationimplementationclassnameasoneof theservlet'si n i t p a r a m entries: Example4.6.DeploymentofyourapplicationusingJerseyspecificservlet
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 < w e b a p p > < s e r v l e t > < s e r v l e t n a m e > J e r s e y W e b A p p l i c a t i o n < / s e r v l e t n a m e > < s e r v l e t c l a s s > o r g . g l a s s f i s h . j e r s e y . s e r v l e t . S e r v l e t C o n t a i n e r < / s e r v l e t c l a s s > < i n i t p a r a m > < p a r a m n a m e > j a v a x . w s . r s . A p p l i c a t i o n < / p a r a m n a m e > < p a r a m v a l u e > o r g . f o o . r e s t . M y A p p l i c a t i o n < / p a r a m v a l u e > < / i n i t p a r a m > . . . < / s e r v l e t > . . . < / w e b a p p >

Ifthereisnoconfigurationtobesetanddeployedapplicationconsistsonlyfromresourcesandprovidersstoredinparticularpackages,Jerseycanscanthem andregisterautomatically: Example4.7.UsingJerseyspecificservletwithoutanapplicationmodelinstance


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 < w e b a p p > < s e r v l e t > < s e r v l e t n a m e > J e r s e y W e b A p p l i c a t i o n < / s e r v l e t n a m e > < s e r v l e t c l a s s > o r g . g l a s s f i s h . j e r s e y . s e r v l e t . S e r v l e t C o n t a i n e r < / s e r v l e t c l a s s > < i n i t p a r a m > < p a r a m n a m e > j e r s e y . c o n f i g . s e r v e r . p r o v i d e r . p a c k a g e s < / p a r a m n a m e > < p a r a m v a l u e > o r g . f o o . r e s t o r g . b a r . r e s t < / p a r a m v a l u e > < / i n i t p a r a m > . . . < / s e r v l e t > . . . < / w e b a p p >

JAXRSalsoprovidestheabilitytoobtainacontainerspecificartifactfromanApplicationinstance.Forexample,JerseysupportsusingGrizzlyasfollows:
1 H t t p H a n d l e r e n d p o i n t = R u n t i m e D e l e g a t e . g e t I n s t a n c e ( ) . c r e a t e E n d p o i n t ( n e w M y A p p l i c a t i o n ( ) , H t t p H a n d l e r . c l a s s )

JerseyalsoprovidesGrizzlyhelperclassestodeploytheHttpHandlerinstanceatabaseURLforinprocessdeployment. TheJerseysamplesprovidemanyexamplesofServletbasedandGrizzlyinprocessbaseddeployments.

4.1.AutoDiscoverableFeatures
ForafewmodulesprovidedbyJerseythereisnoneedtoexplicitlyregistertheirFeaturesastheseF e a t u r e sarediscoveredandregisteredinthe Configuration(onclient/server)automaticallybyJerseywhenthemodulesimplementingthesefeaturesarepresentontheclasspathduringtheanapplication deployment.Themodulesthatareautomaticallydiscoveredinclude:
j e r s e y m e d i a m o x y (JSONpart) j e r s e y m e d i a j s o n p r o c e s s i n g j e r s e y b e a n v a l i d a t i o n

Besidesthesemodulestherearealsofewfeatures/providerspresentinj e r s e y s e r v e r modulethatarediscoveredbythismechanismandtheiravailability isaffectedbyJerseyautodiscoverysupportconfiguration(seeSection4.1.1,ConfiguringtheFeatureAutodiscoverymechanism): WadlFeatureenablesWADLprocessing. UriConnegFilteraURIbasedcontentnegotiationfilter.

Note
AutodiscoveryfunctionalityisinJerseysupportedbyimplementinganinternalSPIA u t o D i s c o v e r a b l e interface.Thisinterfaceisnotpublicat themoment,sobecarefulwhenusingit.

4.1.1.ConfiguringtheFeatureAutodiscoverymechanism
TheautodiscoveryoffeaturesinJerseythatisenabledbydefaultcanbedisabledbyusingspecial(common/server/client)properties: Commonautodiscoveryproperties CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE Disablesautodiscoverygloballyonclient/server.

CommonProperties.JSON_PROCESSING_FEATURE_DISABLE DisablesconfigurationofJsonProcessing(JSR353)feature. CommonProperties.MOXY_JSON_FEATURE_DISABLE DisablesconfigurationofMOXyJsonfeature. Foreachofthesepropertiesthereisaclient/servercounterpartthatonlydisablesthefeatureontheclientorserverrespectively(see ClientProperties/ServerProperties).Eachoftheseclient/serverspecificautodiscoveryrelatedpropertiesoverridesthevalueoftherelatedcommonproperty (ifset).

Note
Incaseanautodiscoverablefeatureisdisabledthenallthefeatured,componentsand/orproperties,registeredwiththefeaturebydefault usingtheautodiscoverymechanismhavetoberegisteredmanually.

4.2.Turnoffclasspathscanning
JerseyusescommonServiceLoaderorLookupdesignpatterntoobtainallserviceimplementations.Itmeansitlookupswholeclasspathtofindappropriate filesinM E T A I N F / s e r v i c e s / .Theclasspathlookupmaybetimeconsuming.Themorejarorwarfilesonclasspaththelookupislonger.Ifyoucountany msofapplicationbootstrapyoucangenerallydisableserviceslookup. JerseyislookingforimplementationoffollowingSPIs
A u t o D i s c o v e r a b l e (server,client)itmeansifyoudisableserviceloadingtheAutoDiscoverablefeatureisautomaticallydisabledtoo M e s s a g e B o d y R e a d e r (server,client) M e s s a g e B o d y W r i t e r (server,client) H e a d e r D e l e g a t e P r o v i d e r (server,client) C o m p o n e n t P r o v i d e r (server) C o n t a i n e r P r o v i d e r (server) A s y n c C o n t e x t D e l e g a t e P r o v i d e r (server/servlet)

InallcasesitispossibletoregisteranSPIimplementationclassorinstanceprogrammatically.ThereforeyoucandisableserviceslookupinJerseyandsave dozensofmsduringapplicationinitialization.TheserviceslookupinJerseythatisenabledbydefaultcanbedisabledbyusingspecialproperty CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE.Thereisaclient/servercounterpartthatonlydisablesthefeatureontheclientorserver respectively:ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE/ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE.Theclient/server specificpropertyoverridesthevalueoftherelatedcommonproperty(ifset). Forexample,followingcodesnippetregistersdifferenttypesofimplementations:C o n t a i n e r R e q u e s t F i l t e r ,F e a t u r e ,C o m p o n e n t P r o v i d e r and C o n t a i n e r P r o v i d e r : Example4.8.RegisteringSPIimplementationsusingResourceConfig


1 2 3 4 5 6 f i n a l R e s o u r c e C o n f i g r e s o u r c e C o n f i g = n e w R e s o u r c e C o n f i g ( M y R e s o u r c e . c l a s s ) r e s o u r c e C o n f i g . r e g i s t e r ( o r g . g l a s s f i s h . j e r s e y . s e r v e r . f i l t e r . U r i C o n n e g F i l t e r . c l a s s ) r e s o u r c e C o n f i g . r e g i s t e r ( o r g . g l a s s f i s h . j e r s e y . s e r v e r . v a l i d a t i o n . V a l i d a t i o n F e a t u r e . c l a s s ) r e s o u r c e C o n f i g . r e g i s t e r ( o r g . g l a s s f i s h . j e r s e y . s e r v e r . s p r i n g . S p r i n g C o m p o n e n t P r o v i d e r . c l a s s ) r e s o u r c e C o n f i g . r e g i s t e r ( o r g . g l a s s f i s h . j e r s e y . g r i z z l y 2 . h t t p s e r v e r . G r i z z l y H t t p C o n t a i n e r P r o v i d e r . c l a s s ) r e s o u r c e C o n f i g . p r o p e r t y ( S e r v e r P r o p e r t i e s . M E T A I N F _ S E R V I C E S _ L O O K U P _ D I S A B L E , t r u e )

Chapter5.ClientAPI
TableofContents 5.1.UniformInterfaceConstraint 5.2.EaseofuseandreusingJAXRSartifacts 5.3.OverviewoftheClientAPI 5.3.1.GettingstartedwiththeclientAPI 5.3.2.CreatingandconfiguringaClientinstance 5.3.3.Targetingawebresource 5.3.4.IdentifyingresourceonWebTarget 5.3.5.InvokingaHTTPrequest 5.3.6.Examplesummary 5.4.Javainstancesandtypesforrepresentations 5.4.1.Addingsupportfornewrepresentations 5.5.ClientTransportConnectors 5.6.Usingclientrequestandresponsefilters 5.7.Closingconnections 5.8.SecuringaClient 5.8.1.HTTPBasicAuthenticationSupport 5.8.2.HTTPDigestAuthenticationSupport ThissectionintroducestheJAXRSClientAPI,whichisafluentJavabasedAPIforcommunicationwithRESTfulWebservices.ThisstandardAPIthatisalso partofJavaEE7isdesignedtomakeitveryeasytoconsumeaWebserviceexposedviaHTTPprotocolandenablesdeveloperstoconciselyandefficiently implementportableclientsidesolutionsthatleverageexistingandwellestablishedclientsideHTTPconnectorimplementations. TheJAXRSclientAPIcanbeutilizedtoconsumeanyWebserviceexposedontopofaHTTPprotocolorit'sextension(e.g.WebDAV),andisnotrestrictedto servicesimplementedusingJAXRS.Yet,developersfamiliarwithJAXRSshouldfindtheclientAPIcomplementarytotheirservices,especiallyiftheclient APIisutilizedbythoseservicesthemselves,ortotestthoseservices.TheJAXRSclientAPIfindsinspirationintheproprietaryJersey1.xClientAPIand developersfamiliarwiththeJersey1.xClientAPIshouldfinditeasytounderstandalltheconceptsintroducedinthenewJAXRSClientAPI. ThegoalsoftheclientAPIarethreefold: 1. EncapsulateakeyconstraintoftheRESTarchitecturalstyle,namelytheUniformInterfaceConstraintandassociateddataelements,asclientsideJava artifacts 2. MakeitaseasytoconsumeRESTfulWebservicesexposedoverHTTP,sameastheJAXRSserversideAPImakesiteasytodevelopRESTfulWeb servicesand 3. SharecommonconceptsandextensibilitypointsoftheJAXRSAPIbetweentheserverandtheclientsideprogrammingmodels.

AsanextensiontothestandardJAXRSClientAPI,theJerseyClientAPIsupportsapluggablearchitecturetoenabletheuseofdifferentunderlyingHTTP clientConnectorimplementations.SeveralsuchimplementationsarecurrentlyprovidedwithJersey.Wehaveadefaultclientconnectorusing H t t p ( s ) U R L C o n n e c t i o n suppliedwiththeJDKaswellasconnectorimplementationsbasedonApacheHTTPClient,andGrizzlyAsynchronousClient.

5.1.UniformInterfaceConstraint
TheuniforminterfaceconstraintboundsthearchitectureofRESTfulWebservicessothataclient,suchasabrowser,canutilizethesameinterfaceto communicatewithanyservice.ThisisaverypowerfulconceptinsoftwareengineeringthatmakesWebbasedsearchenginesandservicemashups possible.Itinducespropertiessuchas: 1. simplicity,thearchitectureiseasiertounderstandandmaintainand 2. evolvabilityorloosecoupling,clientsandservicescanevolveovertimeperhapsinnewandunexpectedways,whileretainingbackwardscompatibility. Furtherconstraintsarerequired: 1. everyresourceisidentifiedbyaURI 2. aclientinteractswiththeresourceviaHTTPrequestsandresponsesusingafixedsetofHTTPmethods 3. oneormorerepresentationscanbereturnedandareidentifiedbymediatypesand 4. thecontentsofwhichcanlinktofurtherresources. TheaboveprocessrepeatedoverandagainshouldbefamiliartoanyonewhohasusedabrowsertofillinHTMLformsandfollowlinks.Thatsameprocessis applicabletononbrowserbasedclients. ManyexistingJavabasedclientAPIs,suchastheApacheHTTPclientAPIorH t t p U r l C o n n e c t i o n suppliedwiththeJDKplacetoomuchfocusontheClient Serverconstraintfortheexchangesofrequestandresponsesratherthanaresource,identifiedbyaURI,andtheuseofafixedsetofHTTPmethods. AresourceintheJAXRSclientAPIisaninstanceoftheJavaclassWebTarget.andencapsulatesanURI.ThefixedsetofHTTPmethodscanbeinvoked basedontheW e b T a r g e t .TherepresentationsareJavatypes,instancesofwhich,maycontainlinksthatnewinstancesofW e b T a r g e t maybecreatedfrom.

5.2.EaseofuseandreusingJAXRSartifacts
SinceaJAXRScomponentisrepresentedasanannotatedJavatype,itmakesiteasytoconfigure,passaroundandinjectinwaysthatarenotsointuitiveor possiblewithotherclientsideAPIs.TheJerseyClientAPIreusesmanyaspectsoftheJAXRSandtheJerseyimplementationsuchas: 1. URIbuildingusingUriBuilderandUriTemplatetosafelybuildURIs 2. BuiltinsupportforJavatypesofrepresentationssuchasb y t e [ ] ,S t r i n g ,N u m b e r ,B o o l e a n ,C h a r a c t e r ,I n p u t S t r e a m ,j a v a . i o . R e a d e r ,F i l e , D a t a S o u r c e ,JAXBbeansaswellasadditionalJerseyspecificJSONandMultiPartsupport. 3. UsingthefluentbuilderstyleAPIpatterntomakeiteasiertoconstructrequests. SomeAPIs,liketheApacheHTTPClientorHttpURLConnectioncanberatherhardtouseand/orrequiretoomuchcodetodosomethingrelativelysimple, especiallywhentheclientneedstounderstanddifferentpayloadrepresentations.ThisiswhytheJerseyimplementationofJAXRSClientAPIprovides supportforwrappingH t t p U r l C o n n e c t i o n andtheApacheHTTPclient.ThusitispossibletogetthebenefitsoftheestablishedJAXRSimplementationsand featureswhilegettingtheeaseofusebenefitofthesimpledesignoftheJAXRSclientAPI.Forexample,withalowlevelHTTPclientlibrary,sendingaPOST requestwithabunchoftypedHTMLformparametersandreceivingaresponsedeserializedintoaJAXBbeanisnotstraightforwardatall.WiththenewJAX RSClientAPIsupportedbyJerseythistaskisveryeasy: Example5.1.POSTrequestwithformparameters
1 2 3 4 5 6 7 8 9 1 0 1 1 C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( ) W e b T a r g e t t a r g e t = c l i e n t . t a r g e t ( " h t t p : / / l o c a l h o s t : 9 9 9 8 " ) . p a t h ( " r e s o u r c e " ) F o r m f o r m = n e w F o r m ( ) f o r m . p a r a m ( " x " , " f o o " ) f o r m . p a r a m ( " y " , " b a r " ) M y J A X B B e a n b e a n = t a r g e t . r e q u e s t ( M e d i a T y p e . A P P L I C A T I O N _ J S O N _ T Y P E ) . p o s t ( E n t i t y . e n t i t y ( f o r m , M e d i a T y p e . A P P L I C A T I O N _ F O R M _ U R L E N C O D E D _ T Y P E ) , M y J A X B B e a n . c l a s s )

IntheExample5.1,POSTrequestwithformparametersanewW e b T a r g e t instanceiscreatedusinganewClientinstancefirst,nextaForminstanceis createdwithtwoformparameters.Onceready,theF o r m instanceisP O S T edtothetargetresource.First,theacceptablemediatypeisspecifiedinthe r e q u e s t ( . . . ) method.Theninthep o s t ( . . . ) method,acalltoastaticmethodonJAXRSEntityismadetoconstructtherequestentityinstanceandattach thepropercontentmediatypetotheformentitythatisbeingsent.Thesecondparameterinthep o s t ( . . . ) methodspecifiestheJavatypeoftheresponse entitythatshouldbereturnedfromthemethodincaseofasuccessfulresponse.InthiscaseaninstanceofJAXBbeanisrequestedtobereturnedon success.TheJerseyclientAPItakescareofselectingtheproperMessageBodyWriter<T>fortheserializationoftheF o r m instance,invokingtheP O S T request andproducinganddeserializationoftheresponsemessagepayloadintoaninstanceofaJAXBbeanusingaproperMessageBodyReader<T>. IfthecodeabovehadtobewrittenusingH t t p U r l C o n n e c t i o n ,thedeveloperwouldhavetowritecustomcodetoserializetheformdatathataresentwithin thePOSTrequestanddeserializetheresponseinputstreamintoaJAXBbean.Additionally,morecodewouldhavetobewrittentomakeiteasytoreusethe logicwhencommunicatingwiththesameresource h t t p : / / l o c a l h o s t : 8 0 8 0 / r e s o u r c e thatisrepresentedbytheJAXRSW e b T a r g e t instanceinour example.

5.3.OverviewoftheClientAPI
5.3.1.GettingstartedwiththeclientAPI
RefertothedependenciesfordetailsonthedependencieswhenusingtheJerseyJAXRSClientsupport. YoumayalsowanttouseacustomConnectorimplementation.Insuchcaseyouwouldneedtoincludeadditionaldependenciesonthemodule(s)containing thecustomclientconnectorthatyouwanttouse.Seesection"ConfiguringcustomConnectors"abouthowtouseandconfigureacustomJerseyclient transportC o n n e c t o r .

5.3.2.CreatingandconfiguringaClientinstance
JAXRSClientAPIisadesignedtoallowfluentprogrammingmodel.Thismeans,aconstructionofaC l i e n t instance,fromwhichaW e b T a r g e t iscreated, fromwhicharequestInvocationisbuiltandinvokedcanbechainedinasingle"flow"ofinvocations.Theindividualstepsoftheflowwillbeshowninthe followingsections.ToutilizetheclientAPIitisfirstnecessarytobuildaninstanceofaClientusingoneofthestaticClientBuilderfactorymethods.Here'sthe mostsimpleexample:
1 C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( )

TheC l i e n t B u i l d e r isaJAXRSAPIusedtocreatenewinstancesofC l i e n t .Inaslightlymoreadvancedscenarios,C l i e n t B u i l d e r canbeusedto

configureadditionalclientinstanceproperties,suchasaSSLtransportsettings,ifneeded(see???below). AC l i e n t instancecanbeconfiguredduringcreationbypassingaClientConfigtothen e w C l i e n t ( C o n f i g u r a b l e ) C l i e n t B u i l d e r factorymethod. ClientConfigimplementsConfigurableandthereforeitoffersmethodstoregisterproviders(e.g.featuresorindividualentityproviders,filtersorinterceptors) andsetupproperties.Thefollowingcodeshowsaregistrationofcustomclientfilters:


1 2 3 4 C l i e n t C o n f i g c l i e n t C o n f i g = n e w C l i e n t C o n f i g ( ) c l i e n t C o n f i g . r e g i s t e r ( M y C l i e n t R e s p o n s e F i l t e r . c l a s s ) c l i e n t C o n f i g . r e g i s t e r ( n e w A n o t h e r C l i e n t F i l t e r ( ) ) C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( c l i e n t C o n f i g )

Intheexample,filtersareregisteredusingtheC l i e n t C o n f i g . r e g i s t e r ( . . . ) method.Therearemultipleoverloadedversionsofthemethodthatsupport registrationoffeatureandproviderclassesorinstances.OnceaC l i e n t C o n f i g instanceisconfigured,itcanbepassedtotheC l i e n t B u i l d e r tocreatea preconfiguredC l i e n t instance. NotethattheJerseyC l i e n t C o n f i g supportsthefluentAPImodelofConfigurable.Withthatthecodethatconfiguresanewclientinstancecanbealsowritten usingamorecompactstyleasshownbelow.
1 2 3 C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( n e w C l i e n t C o n f i g ( ) . r e g i s t e r ( M y C l i e n t R e s p o n s e F i l t e r . c l a s s ) . r e g i s t e r ( n e w A n o t h e r C l i e n t F i l t e r ( ) )

TheabilitytoleveragethiscompactpatternisinherenttoallJAXRSandJerseyClientAPIcomponents. SinceC l i e n t implementsConfigurableinterfacetoo,itcanbeconfiguredfurtherevenafterithasbeencreated.Importantistomentionthatanyconfiguration changedoneonaC l i e n t instancewillnotinfluencetheClientConfiginstancethatwasusedtoprovidetheinitialC l i e n t instanceconfigurationatthe instancecreationtime.ThenextpieceofcodeshowsaconfigurationofanexistingC l i e n t instance.


1 c l i e n t . r e g i s t e r ( T h i r d C l i e n t F i l t e r . c l a s s )

Similarlytoearlierexamples,sinceC l i e n t . r e g i s t e r ( . . . ) methodsupportsthefluentAPIstyle,multipleclientinstanceconfigurationcallscanbechained:
1 2 3 c l i e n t . r e g i s t e r ( F i l t e r A . c l a s s ) . r e g i s t e r ( n e w F i l t e r B ( ) ) . p r o p e r t y ( " m y p r o p e r t y " , t r u e )

TogetthecurrentconfigurationoftheC l i e n t instanceag e t C o n f i g u r a t i o n ( ) methodcanbeused.


1 2 3 4 5 6 C l i e n t C o n f i g c l i e n t C o n f i g = n e w C l i e n t C o n f i g ( ) c l i e n t C o n f i g . r e g i s t e r ( M y C l i e n t R e s p o n s e F i l t e r . c l a s s ) c l i e n t C o n f i g . r e g i s t e r ( n e w A n o t h e r C l i e n t F i l t e r ( ) ) C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( c l i e n t C o n f i g ) c l i e n t . r e g i s t e r ( T h i r d C l i e n t F i l t e r . c l a s s ) C o n f i g u r a t i o n n e w C o n f i g u r a t i o n = c l i e n t . g e t C o n f i g u r a t i o n ( )

Inthecode,anadditionalM y C l i e n t R e s p o n s e F i l t e r classandA n o t h e r C l i e n t F i l t e r instanceareregisteredinthec l i e n t C o n f i g .Thec l i e n t C o n f i g is thenusedtoconstructanewC l i e n t instance.TheT h i r d C l i e n t F i l t e r isaddedseparatelytotheconstructedC l i e n t instance.Thisdoesnotinfluencethe configurationrepresentedbytheoriginalc l i e n t C o n f i g .Inthelaststepan e w C o n f i g u r a t i o n isretrievedfromthec l i e n t .Thisconfigurationcontainsall threeregisteredfilterswhiletheoriginalc l i e n t C o n f i g instancestillcontainsonlytwofilters.Unlikec l i e n t C o n f i g createdseparately,the n e w C o n f i g u r a t i o n retrievedfromthec l i e n t instancerepresentsaliveclientconfigurationview.Anyadditionalconfigurationchangesmadetothec l i e n t instancearealsoreflectedinthen e w C o n f i g u r a t i o n .So,n e w C o n f i g u r a t i o n isreallyaviewofthec l i e n t configurationandnotaconfigurationstatecopy. TheseprinciplesareimportantintheclientAPIandwillbeusedinthefollowingsectionstoo.Forexample,youcanconstructacommonbaseconfigurationfor allclients(inourcaseitwouldbec l i e n t C o n f i g )andthenreusethiscommonconfigurationinstancetoconfiguremultiplec l i e n t instancesthatcanbe furtherspecialized.Similarly,youcanuseanexistingc l i e n t instanceconfigurationtoconfigureanotherclientinstancewithouthavingtoworryaboutany sideeffectsintheoriginalc l i e n t instance.

5.3.3.Targetingawebresource
OnceyouhaveaC l i e n t instanceyoucancreateaW e b T a r g e t fromit.
1 W e b T a r g e t w e b T a r g e t = c l i e n t . t a r g e t ( " h t t p : / / e x a m p l e . c o m / r e s t " )

AC l i e n t containsseveralt a r g e t ( . . . ) methodsthatallowforcreationofW e b T a r g e t instance.Inthiscasewe'reusingt a r g e t ( S t r i n g u r i ) version.The u r i passedtothemethodasaS t r i n g istheURIofthetargetedwebresource.InmorecomplexscenariositcouldbethecontextrootURIofthewhole RESTfulapplication,fromwhichW e b T a r g e t instancesrepresentingindividualresourcetargetscanbederivedandindividuallyconfigured.Thisispossible, becauseJAXRSW e b T a r g e t alsoimplementsC o n f i g u r a b l e :
1 2 W e b T a r g e t w e b T a r g e t = c l i e n t . t a r g e t ( " h t t p : / / e x a m p l e . c o m / r e s t " ) w e b T a r g e t . r e g i s t e r ( F i l t e r F o r E x a m p l e C o m . c l a s s )

TheconfigurationprinciplesusedinJAXRSclientAPIapplytoW e b T a r g e t aswell.EachW e b T a r g e t instanceinheritsaconfigurationfromit'sparent(eithera clientoranotherwebtarget)andcanbefurthercustomconfiguredwithoutaffectingtheconfigurationoftheparentcomponent.Inthiscase,the F i l t e r F o r E x a m p l e C o m willberegisteredonlyinthew e b T a r g e t andnotinc l i e n t .So,thec l i e n t canstillbeusedtocreatenewW e b T a r g e t instances pointingatotherURIsusingjustthecommonclientconfiguration,whichF i l t e r F o r E x a m p l e C o m filterisnotpartof.

5.3.4.IdentifyingresourceonWebTarget
Let'sassumewehaveaw e b T a r g e t pointingat" h t t p : / / e x a m p l e . c o m / r e s t " URIthatrepresentsacontextrootofaRESTfulapplicationandthereisa resourceexposedontheURI" h t t p : / / e x a m p l e . c o m / r e s t / r e s o u r c e " .Asalreadymentioned,aW e b T a r g e t instancecanbeusedtoderiveotherweb targets.Usethefollowingcodetodefineapathtotheresource.
1 W e b T a r g e t r e s o u r c e W e b T a r g e t = w e b T a r g e t . p a t h ( " r e s o u r c e " )

Ther e s o u r c e W e b T a r g e t nowpointstotheresourceonURI" h t t p : / / e x a m p l e . c o m / r e s t / r e s o u r c e " .Againifweconfigurether e s o u r c e W e b T a r g e t with afilterspecifictother e s o u r c e ,itwillnotinfluencetheoriginalw e b T a r g e t instance.However,thefilterF i l t e r F o r E x a m p l e C o m registrationwillstillbe inheritedbyther e s o u r c e W e b T a r g e t asithasbeencreatedfromw e b T a r g e t .Thismechanismallowsyoutosharethecommonconfigurationofrelated resources(typicallyhostedunderthesameURIroot,inourcaserepresentedbythew e b T a r g e t instance),whileallowingforfurtherconfiguration specializationbasedonthespecificrequirementsofeachindividualresource.Thesameconfigurationprinciplesofinheritance(toallowcommonconfig propagation)anddecoupling(toallowindividualconfigcustomization)appliestoallcomponentsinJAXRSClientAPIdiscussedbelow. Let'ssaythereisasubresourceonthepath" h t t p : / / e x a m p l e . c o m / r e s t / r e s o u r c e / h e l l o w o r l d " .YoucanderiveaW e b T a r g e t forthisresourcesimply by:
1 W e b T a r g e t h e l l o w o r l d W e b T a r g e t = r e s o u r c e W e b T a r g e t . p a t h ( " h e l l o w o r l d " )

Let'sassumethattheh e l l o w o r l d resourceacceptsaqueryparamforG E T requestswhichdefinesthegreetingmessage.Thenextcodesnippetshowsa codethatcreatesanewW e b T a r g e t withthequeryparamdefined.


1 2 W e b T a r g e t h e l l o w o r l d W e b T a r g e t W i t h Q u e r y P a r a m = h e l l o w o r l d W e b T a r g e t . q u e r y P a r a m ( " g r e e t i n g " , " H i W o r l d ! " )

PleasenotethatapartfrommethodsthatcanderivenewW e b T a r g e t instancebasedonaURIpathorqueryparameters,theJAXRSW e b T a r g e t API

containsalsomethodsforworkingwithmatrixparameterstoo.

5.3.5.InvokingaHTTPrequest
Let'snowfocusoninvokingaG E T HTTPrequestonthecreatedwebtargets.TostartbuildinganewHTTPrequestinvocation,weneedtocreateanew Invocation.Builder.
1 2 3 I n v o c a t i o n . B u i l d e r i n v o c a t i o n B u i l d e r = h e l l o w o r l d W e b T a r g e t W i t h Q u e r y P a r a m . r e q u e s t ( M e d i a T y p e . T E X T _ P L A I N _ T Y P E ) i n v o c a t i o n B u i l d e r . h e a d e r ( " s o m e h e a d e r " , " t r u e " )

Anewinvocationbuilderinstanceiscreatedusingoneofther e q u e s t ( . . . ) methodsthatareavailableonW e b T a r g e t .Acoupleofthesemethodsaccept parametersthatletyoudefinethemediatypeoftherepresentationrequestedtobereturnedfromtheresource.Herewearesayingthatwerequesta " t e x t / p l a i n " type.ThistellsJerseytoaddaA c c e p t : t e x t / p l a i n HTTPheadertoourrequest. Thei n v o c a t i o n B u i l d e r isusedtosetuprequestspecificparameters.Herewecansetupheadersfortherequestorforexamplecookieparameters.Inour examplewesetupa" s o m e h e a d e r " headertovaluet r u e . Oncefinishedwithrequestcustomizations,it'stimetoinvoketherequest.Wehavetwooptionsnow.WecanusetheI n v o c a t i o n . B u i l d e r tobuildageneric Invocationinstancethatwillbeinvokedsometimelater.UsingI n v o c a t i o n wewillbeabletoe.g.setadditionalrequestpropertieswhicharepropertiesina batchofseveralrequestsandusethegenericJAXRSI n v o c a t i o n APItoinvokethebatchofrequestswithoutactuallyknowingallthedetails(suchas requestHTTPmethod,configurationetc.).Anypropertiessetonaninvocationinstancecanbereadduringtherequestprocessing.Forexample,inacustom ClientRequestFilteryoucancallg e t P r o p e r t y ( ) methodonthesuppliedClientRequestContexttoreadarequestproperty.Notethattheserequestproperties aredifferentfromtheconfigurationpropertiessetonC o n f i g u r a b l e .Asmentionedearlier,anI n v o c a t i o n instanceprovidesgenericinvocationAPItoinvoke theHTTPrequestitrepresentseithersynchronouslyorasynchronously.SeetheChapter10,AsynchronousServicesandClientsformoreinformationon asynchronousinvocations. IncaseyoudonotwanttodoanybatchprocessingonyourHTTPrequestinvocationspriortoinvokingthem,thereisanother,moreconvenientapproach thatyoucanusetoinvokeyourrequestsdirectlyfromanI n v o c a t i o n . B u i l d e r instance.ThisapproachisdemonstratedinthenextJavacodelisting.
1 R e s p o n s e r e s p o n s e = i n v o c a t i o n B u i l d e r . g e t ( )

Whileshort,thecodeintheexampleperformsmultipleactions.First,itwillbuildthetherequestfromthei n v o c a t i o n B u i l d e r .TheURIofrequestwillbe h t t p : / / e x a m p l e . c o m / r e s t / r e s o u r c e / h e l l o w o r l d ? g r e e t i n g = " H i % 2 0 W o r l d ! " andtherequestwillcontains o m e h e a d e r : t r u e andA c c e p t : t e x t / p l a i n headers.Therequestwillthenpasstroughallconfiguredrequestfilters(A n o t h e r C l i e n t F i l t e r ,T h i r d C l i e n t F i l t e r and F i l t e r F o r E x a m p l e C o m ).Onceprocessedbythefilters,therequestwillbesenttotheremoteresource.Let'ssaytheresourcethenreturnsanHTTP200 messagewithaplaintextresponsecontentthatcontainsthevaluesentintherequestg r e e t i n g queryparameter.Nowwecanobservethereturned response:
1 2 S y s t e m . o u t . p r i n t l n ( r e s p o n s e . g e t S t a t u s ( ) ) S y s t e m . o u t . p r i n t l n ( r e s p o n s e . r e a d E n t i t y ( S t r i n g . c l a s s ) )

whichwillproducethefollowingoutputtotheconsole:
2 0 0 H i W o r l d !

Aswecansee,therequestwassuccessfullyprocessed(code200)andreturnedanentity(representation)is" H i W o r l d ! " .Notethatsincevehave configuredaM y C l i e n t R e s p o n s e F i l t e r intheresourcetarget,whenr e s p o n s e . r e a d E n t i t y ( S t r i n g . c l a s s ) getscalled,theresponsereturnedfromthe remoteendpointispassedthroughtheresponsefilterchain(includingtheM y C l i e n t R e s p o n s e F i l t e r )andentityinterceptorchainandatlastaproper MessageBodyReader<T>islocatedtoreadtheresponsecontentbytesfromtheresponsestreamintoaJavaS t r i n g instance.CheckChapter9,Filtersand Interceptorstolearmoreaboutrequestandresponsefiltersandentityinterceptors. ImaginenowthatyouwouldliketoinvokeaP O S T requestbutwithoutanyqueryparameters.Youwouldjustusetheh e l l o w o r l d W e b T a r g e t instancecreated earlierandcallthep o s t ( ) insteadofg e t ( ) .
1 2 3 R e s p o n s e p o s t R e s p o n s e = h e l l o w o r l d W e b T a r g e t . r e q u e s t ( M e d i a T y p e . T E X T _ P L A I N _ T Y P E ) . p o s t ( E n t i t y . e n t i t y ( " A s t r i n g e n t i t y t o b e P O S T e d " , M e d i a T y p e . T E X T _ P L A I N ) )

5.3.6.Examplesummary
Thefollowingcodeputstogetherthepiecesusedintheearlierexamples. Example5.2.UsingJAXRSClientAPI
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 C l i e n t C o n f i g c l i e n t C o n f i g = n e w C l i e n t C o n f i g ( ) c l i e n t C o n f i g . r e g i s t e r ( M y C l i e n t R e s p o n s e F i l t e r . c l a s s ) c l i e n t C o n f i g . r e g i s t e r ( n e w A n o t h e r C l i e n t F i l t e r ( ) ) C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( c l i e n t C o n f i g ) c l i e n t . r e g i s t e r ( T h i r d C l i e n t F i l t e r . c l a s s ) W e b T a r g e t w e b T a r g e t = c l i e n t . t a r g e t ( " h t t p : / / e x a m p l e . c o m / r e s t " ) w e b T a r g e t . r e g i s t e r ( F i l t e r F o r E x a m p l e C o m . c l a s s ) W e b T a r g e t r e s o u r c e W e b T a r g e t = w e b T a r g e t . p a t h ( " r e s o u r c e " ) W e b T a r g e t h e l l o w o r l d W e b T a r g e t = r e s o u r c e W e b T a r g e t . p a t h ( " h e l l o w o r l d " ) W e b T a r g e t h e l l o w o r l d W e b T a r g e t W i t h Q u e r y P a r a m = h e l l o w o r l d W e b T a r g e t . q u e r y P a r a m ( " g r e e t i n g " , " H i W o r l d ! " ) I n v o c a t i o n . B u i l d e r i n v o c a t i o n B u i l d e r = h e l l o w o r l d W e b T a r g e t W i t h Q u e r y P a r a m . r e q u e s t ( M e d i a T y p e . T E X T _ P L A I N _ T Y P E ) i n v o c a t i o n B u i l d e r . h e a d e r ( " s o m e h e a d e r " , " t r u e " ) R e s p o n s e r e s p o n s e = i n v o c a t i o n B u i l d e r . g e t ( ) S y s t e m . o u t . p r i n t l n ( r e s p o n s e . g e t S t a t u s ( ) ) S y s t e m . o u t . p r i n t l n ( r e s p o n s e . r e a d E n t i t y ( S t r i n g . c l a s s ) )

NowwecantrytoleveragethefluentAPIstyletowritethiscodeinamorecompactway. Example5.3.UsingJAXRSClientAPIfluently
1 2 3 4 5 6 7 8 9 1 0 1 1 C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( n e w C l i e n t C o n f i g ( ) . r e g i s t e r ( M y C l i e n t R e s p o n s e F i l t e r . c l a s s ) . r e g i s t e r ( n e w A n o t h e r C l i e n t F i l t e r ( ) ) ) S t r i n g e n t i t y = c l i e n t . t a r g e t ( " h t t p : / / e x a m p l e . c o m / r e s t " ) . r e g i s t e r ( F i l t e r F o r E x a m p l e C o m . c l a s s ) . p a t h ( " r e s o u r c e / h e l l o w o r l d " ) . q u e r y P a r a m ( " g r e e t i n g " , " H i W o r l d ! " ) . r e q u e s t ( M e d i a T y p e . T E X T _ P L A I N _ T Y P E ) . h e a d e r ( " s o m e h e a d e r " , " t r u e " ) . g e t ( S t r i n g . c l a s s )

ThecodeabovedoesthesamethingexceptitskipsthegenericR e s p o n s e processinganddirectlyrequestsanentityinthelastg e t ( S t r i n g . c l a s s ) method call.Thisshortcutmethodlet'syouspecifythat(incasetheresponsewasreturnedsuccessfullywithaHTTP2xxstatuscode)theresponseentityshouldbe returnedasJavaS t r i n g type.ThiscompactexampledemonstratesanotheradvantageoftheJAXRSclientAPI.ThefluencyofJAXRSClientAPIis convenientespeciallywithsimpleusecases.HereisanotheraverysimpleGETrequestreturningaStringrepresentation(entity):


1 2 3 S t r i n g r e s p o n s e E n t i t y = C l i e n t B u i l d e r . n e w C l i e n t ( ) . t a r g e t ( " h t t p : / / e x a m p l e . c o m " ) . p a t h ( " r e s o u r c e / r e s t " ) . r e q u e s t ( ) . g e t ( S t r i n g . c l a s s )

5.4.Javainstancesandtypesforrepresentations
AlltheJavatypesandrepresentationssupportedbydefaultontheJerseyserversideforrequestsandresponsesarealsosupportedontheclientside.For example,toprocessaresponseentity(orrepresentation)asastreamofbytesuseInputStreamasfollows:
1 2 3 4 5 I n p u t S t r e a m i n = r e s p o n s e . r e a d E n t i t y ( I n p u t S t r e a m . c l a s s ) . . . / / R e a d f r o m t h e s t r e a m i n . c l o s e ( )

Notethatitisimportanttoclosethestreamafterprocessingsothatresourcesarefreedup. ToP O S T afileuseaF i l e instanceasfollows:


1 2 3 4 5 F i l e f = . . . . . . w e b T a r g e t . r e q u e s t ( ) . p o s t ( E n t i t y . e n t i t y ( f , M e d i a T y p e . T E X T _ P L A I N _ T Y P E ) )

5.4.1.Addingsupportfornewrepresentations
ThesupportfornewapplicationdefinedrepresentationsasJavatypesrequirestheimplementationofthesameJAXRSentityproviderextensioninterfaces asfortheserversideJAXRSAPI,namelyMessageBodyReader<T>andMessageBodyWriter<T>respectively,forrequestandresponseentities(orinbound andoutboundrepresentations). ClassesorimplementationsoftheproviderbasedinterfacesneedtoberegisteredasproviderswithintheJAXRSorJerseyClientAPIcomponentsthat implementC o n f i g u r a b l e contract(C l i e n t B u i l d e r ,C l i e n t ,W e b T a r g e t orC l i e n t C o n f i g ),aswasshownintheearliersections.Somemediatypesare providedintheformofJAXRSFeatureaconceptthatallowstheextensionproviderstogrouptogethermultipledifferentextensionprovidersand/or configurationpropertiesinordertosimplifytheregistrationandconfigurationoftheprovidedfeaturebytheendusers.Forexample,MoxyJsonFeaturecanbe registertoenableandconfigureJSONbindingsupportviaMOXylibrary.

5.5.ClientTransportConnectors
Bydefault,thetransportlayerinJerseyisprovidedbyH t t p U r l C o n n e c t i o n .ThistransportisimplementedinJerseyviaHttpUrlConnectorthatimplements JerseyspecificConnectorSPI.Youcanimplementand/orregisteryourownC o n n e c t o r instancetotheJerseyC l i e n t implementation,thatwillreplacethe defaultH t t p U r l C o n n e c t i o n basedtransportlayer.Jerseyprovidesseveralalternativeclienttransportconnectorimplementationsthatarereadytouse.You canuseApacheConnector(addamavendependencytoo r g . g l a s s f i s h . j e r s e y . c o n n e c t o r s : j e r s e y a p a c h e c o n n e c t o r )orGrizzlyConnector(adda mavendependencytoo r g . g l a s s f i s h . j e r s e y . c o n n e c t o r s : j e r s e y g r i z z l y c o n n e c t o r )alternatively.Please,noteagain,thattheConnectorSPIisnot afeatureofJAXRSbutisaJerseyspecificextensionAPIthatwillonlyworkwithJersey.FollowingexampleshowshowtosetupthecustomC o n n e c t o r tothe Jerseyclient.
1 2 3 4 C l i e n t C o n f i g c l i e n t C o n f i g = n e w C l i e n t C o n f i g ( ) C o n n e c t o r c o n n e c t o r = n e w G r i z z l y C o n n e c t o r ( c l i e n t C o n f i g ) c l i e n t C o n f i g . c o n n e c t o r ( c o n n e c t o r ) C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( c l i e n t C o n f i g )

C l i e n t acceptsasasaconstructorargumentaC o n f i g u r a b l e instance.JerseyimplementationoftheC o n f i g u r a b l e providerfortheclientis C l i e n t C o n f i g .ByusingtheJerseyC l i e n t C o n f i g youcanconfigurethecustomC o n n e c t o r intotheC l i e n t C o n f i g .TheG r i z z l y C o n n e c t o r isusedasa customconnectorintheexampleabove.PleasenotethattheconnectorcannotberegisteredasaproviderusingC o n f i g u r a b l e . r e g i s t e r ( . . . ) atthe

moment.

5.6.Usingclientrequestandresponsefilters
Filteringrequestsandresponsescanprovideusefullowerlevelconceptfocusedonacertainindependentaspectordomainthatisdecoupledfromthe applicationlayerofbuildingandsendingrequests,andprocessingresponses.Filterscanread/modifytherequestURI,headersandentityorread/modifythe responsestatus,headersandentity. Jerseycontainsthefollowingusefulclientsidefiltersthatyoumaywanttouseinyourapplications:
CsrfProtectionFilter:Crosssiterequestforgeryprotectionfilter(addsX R e q u e s t e d B y toeachstatechangingrequest). EncodingFeature:FeaturethatregistersencodingfilterwhichuseregisteredContentEncoderstoencodeanddecodethecommunication.Theencoding/decodingis performedininterceptor(youdon'tneedtoregisterthisinterceptor).CheckthejavadocoftheEncodingFeatureinordertouseit. HttpBasicAuthFilter:HTTPBasicAuthenticationfilter(see???below). HttpDigestAuthFilter:HTTPDigestAuthenticationfilter.

NotethatthesefeaturesareprovidedbyJersey,butsincetheyuseandimplementJAXRSAPI,thefeaturesshouldbeportableandruninanyJAXRS implementation,notjustJersey.SeeChapter9,FiltersandInterceptorschapterformoreinformationonfiltersandinterceptors.

5.7.Closingconnections
Theunderlyingconnectionsareopenedforeachrequestandclosedaftertheresponseisreceivedandentityisprocessed(entityisread).Seethefollowing example: Example5.4.Closingconnections
1 2 3 4 5 f i n a l W e b T a r g e t t a r g e t = . . . s o m e w e b t a r g e t R e s p o n s e r e s p o n s e = t a r g e t . p a t h ( " r e s o u r c e " ) . r e q u e s t ( ) . g e t ( ) S y s t e m . o u t . p r i n t l n ( " C o n n e c t i o n i s s t i l l o p e n . " ) S y s t e m . o u t . p r i n t l n ( " s t r i n g r e s p o n s e : " + r e s p o n s e . r e a d E n t i t y ( S t r i n g . c l a s s ) ) S y s t e m . o u t . p r i n t l n ( " N o w t h e c o n n e c t i o n i s c l o s e d . " )

Ifyoudon'treadtheentity,thenyouneedtoclosetheresponsemanuallybyr e s p o n s e . c l o s e ( ) .AlsoiftheentityisreadintoanInputStream(by r e s p o n s e . r e a d E n t i t y ( I n p u t S t r e a m . c l a s s ) ),theconnectionstaysopenuntilyoufinishreadingfromtheI n p u t S t r e a m .Inthatcase,theInputStreamor theResponseshouldbeclosedmanuallyattheendofreadingfromInputStream.

5.8.SecuringaClient
ThissectiondescribeshowtosetupSSLconfigurationonJerseyclient(usingJAXRSAPI).TheSSLconfigurationissetupinClientBuilder.Theclientbuilder containsmethodsfordefinitionofKeyStore,TrustStoreorentireSslContext.Seethefollowingexample:
1 2 3 S S L C o n t e x t s s l = . . . y o u r c o n f i g u r e d S S L c o n t e x t C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . s s l C o n t e x t ( s s l ) . b u i l d ( ) R e s p o n s e r e s p o n s e = c l i e n t . t a r g e t ( " h t t p s : / / e x a m p l e . c o m / r e s o u r c e " ) . r e q u e s t ( ) . g e t ( )

TheexampleaboveshowshowtosetupacustomS s l C o n t e x t totheC l i e n t B u i l d e r .CreatingaS s l C o n t e x t canbemoredifficultasyoumightneedtoinit instanceproperlywiththeprotocol,K e y S t o r e ,T r u s t S t o r e ,etc.JerseyoffersautilitySslConfiguratorclassthatcanbeusedtosetuptheS s l C o n t e x t .The S s l C o n f i g u r a t o r canbeconfiguredbasedonstandardizedsystempropertiesforSSLconfiguration,soforexampleyoucanconfiguretheK e y S t o r e file nameusingaenvironmentvariablej a v a x . n e t . s s l . k e y S t o r e andS s l C o n f i g u r a t o r willusesuchavariabletosetuptheS s l C o n t e x t .Seejavadocof SslConfiguratorformoredetails.ThefollowingcodeshowshowaS s l C o n f i g u r a t o r canbeusedtocreateacustomSSLcontext.
1 2 3 4 5 6 7 8 S s l C o n f i g u r a t o r s s l C o n f i g = S s l C o n f i g u r a t o r . n e w I n s t a n c e ( ) . t r u s t S t o r e F i l e ( " . / t r u s t s t o r e _ c l i e n t " ) . t r u s t S t o r e P a s s w o r d ( " s e c r e t p a s s w o r d f o r t r u s t s t o r e " ) . k e y S t o r e F i l e ( " . / k e y s t o r e _ c l i e n t " ) . k e y P a s s w o r d ( " s e c r e t p a s s w o r d f o r k e y s t o r e " ) S S L C o n t e x t s s l C o n t e x t = s s l C o n f i g . c r e a t e S S L C o n t e x t ( ) C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . s s l C o n t e x t ( s s l C o n t e x t ) . b u i l d ( )

NotethatyoucanalsosetupK e y S t o r e andT r u s t S t o r e directlyonaC l i e n t B u i l d e r instancewithoutwrappingthemintotheS s l C o n t e x t .However,ifyou setupaS s l C o n t e x t itwilloverrideanypreviouslydefinedK e y S t o r e andT r u s t S t o r e settings.C l i e n t B u i l d e r alsooffersamethodfordefiningacustom HostnameVerifierimplementation.H o s t n a m e V e r i f i e r implementationsareinvokedwhendefaulthostURLverificationfails.

Important
NotethattoutilizeHTTPwithSSLitisnecessarytoutilizethe h t t p s scheme. CurrentlythedefaultconnectorH t t p U r l C o n n e c t o r basedonH t t p U r l C o n n e c t i o n implementssupportforSSLdefinedbyJAXRSconfigurationdiscussed inthissample.

5.8.1.HTTPBasicAuthenticationSupport
JerseycontainsafilterthatallowsclienttoauthenticatetoserverswhichrequiresHTTPBasicAuthentication.UseHttpBasicAuthFiltertoaddauthentication headertorequestsinitiatedfromfromtheclient.Seetheexampleofhowtoconfigureandregisterthefilter:
1 c l i e n t . r e g i s t e r ( n e w H t t p B a s i c A u t h F i l t e r ( " H o m e r " , " S e c r e t P a s s w o r d " ) )

5.8.2.HTTPDigestAuthenticationSupport
JerseycontainsafilterthatallowsclienttoauthenticatetoserverswhichrequiresHTTPDigestAuthentication.UseHttpDigestAuthFiltertoaddauthentication headertorequestsinitiatedfromfromtheclient.Seetheexampleofhowtoconfigureandregisterthefilter:
1 c l i e n t . r e g i s t e r ( n e w H t t p D i g e s t A u t h F i l t e r ( " H o m e r " , " S e c r e t P a s s w o r d " ) )

Chapter6.RepresentationsandResponses
TableofContents 6.1.RepresentationsandJavaTypes 6.2.BuildingResponses 6.3.WebApplicationExceptionandMappingExceptionstoResponses 6.4.ConditionalGETsandReturning304(NotModified)Responses

6.1.RepresentationsandJavaTypes
Previoussectionson@Producesand@Consumesannotationsreferredtomediatypeofanentityrepresentation.Examplesabovedepictedresource methodsthatcouldconsumeand/orproduceStringJavatypeforanumberofdifferentmediatypes.Thisapproachiseasytounderstandandrelatively straightforwardwhenappliedtosimpleusecases. Tocoveralsoothercases,handlingnontextualdataforexampleorhandlingdatastoredinthefilesystem,etc.,JAXRSimplementationsarerequiredto supportalsootherkindsofmediatypeconversionswhereadditional,nonString,Javatypesarebeingutilized.FollowingisashortlistingoftheJavatypes thataresupportedoutoftheboxwithrespecttosupportedmediatype: Allmediatypes(* / * )
b y t e [ ] j a v a . l a n g . S t r i n g j a v a . i o . R e a d e r (inboundonly) j a v a . i o . F i l e j a v a x . a c t i v a t i o n . D a t a S o u r c e j a v a x . w s . r s . c o r e . S t r e a m i n g O u t p u t (outboundonly) XMLmediatypes(t e x t / x m l ,a p p l i c a t i o n / x m l anda p p l i c a t i o n / . . . + x m l ) j a v a x . x m l . t r a n s f o r m . S o u r c e j a v a x . x m l . b i n d . J A X B E l e m e n t

ApplicationsuppliedJAXBclasses(typesannotatedwith@XmlRootElementor@XmlType) Formcontent(a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d )
M u l t i v a l u e d M a p < S t r i n g , S t r i n g >

Plaintext(t e x t / p l a i n )
j a v a . l a n g . B o o l e a n j a v a . l a n g . C h a r a c t e r j a v a . l a n g . N u m b e r

Unlikemethodparametersthatareassociatedwiththeextractionofrequestparameters,themethodparameterassociatedwiththerepresentationbeing consumeddoesnotrequireannotating.Inotherwordstherepresentation(entity)parameterdoesnotrequireaspecific'entity'annotation.Amethod parameterwithoutaannotationisanentity.Amaximumofonesuchunannotatedmethodparametermayexistsincetheremayonlybeamaximumofone suchrepresentationsentinarequest. Therepresentationbeingproducedcorrespondstowhatisreturnedbytheresourcemethod.ForexampleJAXRSmakesitsimpletoproduceimagesthat areinstanceofF i l e asfollows: Example6.1.UsingF i l e withaspecificmediatypetoproducearesponse


1 2 3 @ G E T @ P a t h ( " / i m a g e s / { i m a g e } " ) @ P r o d u c e s ( " i m a g e / * " )

4 5 6 7 8 9 1 0 1 1 1 2 1 3

p u b l i c R e s p o n s e g e t I m a g e ( @ P a t h P a r a m ( " i m a g e " ) S t r i n g i m a g e ) { F i l e f = n e w F i l e ( i m a g e ) i f ( ! f . e x i s t s ( ) ) { t h r o w n e w W e b A p p l i c a t i o n E x c e p t i o n ( 4 0 4 ) } S t r i n g m t = n e w M i m e t y p e s F i l e T y p e M a p ( ) . g e t C o n t e n t T y p e ( f ) r e t u r n R e s p o n s e . o k ( f , m t ) . b u i l d ( ) }

TheF i l e typecanalsobeusedwhenconsumingarepresentation(requestentity).Inthatcaseatemporaryfilewillbecreatedfromtheincomingrequest entityandpassedasaparametertotheresourcemethod. TheC o n t e n t T y p e responseheader(ifnotsetprogrammaticallyasdescribedinthenextsection)willbeautomaticallysetbasedonthemediatypes declaredby@Producesannotation.Giventhefollowingmethod,themostacceptablemediatypeisusedwhenmultipleoutputmediatypesareallowed:


1 2 3 4 5 @ G E T @ P r o d u c e s ( { " a p p l i c a t i o n / x m l " , " a p p l i c a t i o n / j s o n " } ) p u b l i c S t r i n g d o G e t A s X m l O r J s o n ( ) { . . . }

Ifa p p l i c a t i o n / x m l isthemostacceptablemediatypedefinedbytherequest(e.g.byheaderA c c e p t : a p p l i c a t i o n / x m l ),thentheC o n t e n t T y p e responseheaderwillbesettoa p p l i c a t i o n / x m l .

6.2.BuildingResponses
SometimesitisnecessarytoreturnadditionalinformationinresponsetoaHTTPrequest.SuchinformationmaybebuiltandreturnedusingResponseand Response.ResponseBuilder.Forexample,acommonRESTfulpatternforthecreationofanewresourceistosupportaPOSTrequestthatreturnsa201 (Created)statuscodeandaL o c a t i o n headerwhosevalueistheURItothenewlycreatedresource.Thismaybeachievedasfollows: Example6.2.Returning201statuscodeandaddingL o c a t i o n headerinresponsetoPOSTrequest
1 2 3 4 5 6 7 @ P O S T @ C o n s u m e s ( " a p p l i c a t i o n / x m l " ) p u b l i c R e s p o n s e p o s t ( S t r i n g c o n t e n t ) { U R I c r e a t e d U r i = . . . c r e a t e ( c o n t e n t ) r e t u r n R e s p o n s e . c r e a t e d ( c r e a t e d U r i ) . b u i l d ( ) }

Intheabovenorepresentationproducedisreturned,thiscanbeachievedbybuildinganentityaspartoftheresponseasfollows: Example6.3.Addinganentitybodytoacustomresponse
1 2 3 4 5 6 7 @ P O S T @ C o n s u m e s ( " a p p l i c a t i o n / x m l " ) p u b l i c R e s p o n s e p o s t ( S t r i n g c o n t e n t ) { U R I c r e a t e d U r i = . . . S t r i n g c r e a t e d C o n t e n t = c r e a t e ( c o n t e n t ) r e t u r n R e s p o n s e . c r e a t e d ( c r e a t e d U r i ) . e n t i t y ( E n t i t y . t e x t ( c r e a t e d C o n t e n t ) ) . b u i l d ( ) }

Responsebuildingprovidesotherfunctionalitysuchassettingtheentitytagandlastmodifieddateoftherepresentation.

6.3.WebApplicationExceptionandMappingExceptionstoResponses
PrevioussectionshowshowtoreturnHTTPresponses,thatarebuiltupprogrammatically.ItispossibletousetheverysamemechanismtoreturnHTTP errorsdirectly,e.g.whenhandlingexceptionsinatrycatchblock.However,tobetteralignwiththeJavaprogrammingmodel,JAXRSallowstodefinedirect mappingofJavaexceptionstoHTTPerrorresponses. ThefollowingexampleshowsthrowingC u s t o m N o t F o u n d E x c e p t i o n fromaresourcemethodinordertoreturnanerrorHTTPresponsetotheclient: Example6.4.Throwingexceptionstocontrolresponse
1 2 3 4 5 6 7 8 9 @ P a t h ( " i t e m s / { i t e m i d } / " ) p u b l i c I t e m g e t I t e m ( @ P a t h P a r a m ( " i t e m i d " ) S t r i n g i t e m i d ) { I t e m i = g e t I t e m s ( ) . g e t ( i t e m i d ) i f ( i = = n u l l ) { t h r o w n e w C u s t o m N o t F o u n d E x c e p t i o n ( " I t e m , " + i t e m i d + " , i s n o t f o u n d " ) } r e t u r n i }

ThisexceptionisanapplicationspecificexceptionthatextendsWebApplicationExceptionandbuildsaHTTPresponsewiththe404statuscodeandan optionalmessageasthebodyoftheresponse: Example6.5.Applicationspecificexceptionimplementation


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 p u b l i c c l a s s C u s t o m N o t F o u n d E x c e p t i o n e x t e n d s W e b A p p l i c a t i o n E x c e p t i o n { / * * * C r e a t e a H T T P 4 0 4 ( N o t F o u n d ) e x c e p t i o n . * / p u b l i c C u s t o m N o t F o u n d E x c e p t i o n ( ) { s u p e r ( R e s p o n s e s . n o t F o u n d ( ) . b u i l d ( ) ) } / * * * C r e a t e a H T T P 4 0 4 ( N o t F o u n d ) e x c e p t i o n . * @ p a r a m m e s s a g e t h e S t r i n g t h a t i s t h e e n t i t y o f t h e 4 0 4 r e s p o n s e . * / p u b l i c C u s t o m N o t F o u n d E x c e p t i o n ( S t r i n g m e s s a g e ) { s u p e r ( R e s p o n s e . s t a t u s ( R e s p o n s e s . N O T _ F O U N D ) . e n t i t y ( m e s s a g e ) . t y p e ( " t e x t / p l a i n " ) . b u i l d ( ) ) } }

InothercasesitmaynotbeappropriatetothrowinstancesofWebApplicationException,orclassesthatextendWebApplicationException,andinsteaditmay bepreferabletomapanexistingexceptiontoaresponse.Forsuchcasesitispossibletouseacustomexceptionmappingprovider.Theprovidermust implementtheExceptionMapper<EextendsThrowable>interface.Forexample,thefollowingmapstheEntityNotFoundExceptiontoaHTTP404(NotFound) response: Example6.6.Mappinggenericexceptionstoresponses


1 2 3 4 5 6 7 8 9 @ P r o v i d e r p u b l i c c l a s s E n t i t y N o t F o u n d M a p p e r i m p l e m e n t s E x c e p t i o n M a p p e r < j a v a x . p e r s i s t e n c e . E n t i t y N o t F o u n d E x c e p t i o n > { p u b l i c R e s p o n s e t o R e s p o n s e ( j a v a x . p e r s i s t e n c e . E n t i t y N o t F o u n d E x c e p t i o n e x ) { r e t u r n R e s p o n s e . s t a t u s ( 4 0 4 ) . e n t i t y ( e x . g e t M e s s a g e ( ) ) . t y p e ( " t e x t / p l a i n " ) . b u i l d ( ) } }

Theaboveclassisannotatedwith@Provider,thisdeclaresthattheclassisofinteresttotheJAXRSruntime.Suchaclassmaybeaddedtothesetof classesoftheApplicationinstancethatisconfigured.WhenanapplicationthrowsanEntityNotFoundExceptionthet o R e s p o n s e methodofthe E n t i t y N o t F o u n d M a p p e r instancewillbeinvoked. Jerseysupportsextensionoftheexceptionmappers.Theseextendedmappersmustimplementthe o r g . g l a s s f i s h . j e r s e y . s p i . E x t e n d e d E x c e p t i o n M a p p e r interface.Thisinterfaceadditionallydefinesmethodi s M a p p a b l e ( T h r o w a b l e ) whichwillbe invokedbytheJerseyruntimewhenexceptionisthrownandthisproviderisconsideredasmappablebasedontheexceptiontype.Usingthismethodthe providercanrejectmappingoftheexceptionbeforethemethodt o R e s p o n s e isinvoked.Theprovidercanforexamplechecktheexceptionparametersand basedonthemreturnfalseandletotherprovidertobechosenfortheexceptionmapping.

6.4.ConditionalGETsandReturning304(NotModified)Responses
ConditionalGETsareagreatwaytoreducebandwidth,andpotentiallyimproveontheserversideperformance,dependingonhowtheinformationusedto determineconditionsiscalculated.Awelldesignedwebsitemayforexamplereturn304(NotModified)responsesformanyofstaticimagesitserves. JAXRSprovidessupportforconditionalGETsusingthecontextualinterfaceRequest. ThefollowingexampleshowsconditionalGETsupport: Example6.7.ConditionalGETsupport
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 p u b l i c S p a r k l i n e s R e s o u r c e ( @ Q u e r y P a r a m ( " d " ) I n t e g e r L i s t d a t a , @ D e f a u l t V a l u e ( " 0 , 1 0 0 " ) @ Q u e r y P a r a m ( " l i m i t s " ) I n t e r v a l l i m i t s , @ C o n t e x t R e q u e s t r e q u e s t , @ C o n t e x t U r i I n f o u i ) { i f ( d a t a = = n u l l ) { t h r o w n e w W e b A p p l i c a t i o n E x c e p t i o n ( 4 0 0 ) } t h i s . d a t a = d a t a t h i s . l i m i t s = l i m i t s i f ( ! l i m i t s . c o n t a i n s ( d a t a ) ) { t h r o w n e w W e b A p p l i c a t i o n E x c e p t i o n ( 4 0 0 ) } t h i s . t a g = c o m p u t e E n t i t y T a g ( u i . g e t R e q u e s t U r i ( ) ) i f ( r e q u e s t . g e t M e t h o d ( ) . e q u a l s ( " G E T " ) ) { R e s p o n s e . R e s p o n s e B u i l d e r r b = r e q u e s t . e v a l u a t e P r e c o n d i t i o n s ( t a g ) i f ( r b ! = n u l l ) { t h r o w n e w W e b A p p l i c a t i o n E x c e p t i o n ( r b . b u i l d ( ) ) } } }

TheconstructoroftheS p a r k l i n e s R e s o u c e rootresourceclasscomputesanentitytagfromtherequestURIandthencallsthe request.evaluatePreconditionswiththatentitytag.IfaclientrequestcontainsanI f N o n e M a t c h headerwithavaluethatcontainsthesameentitytagthat wascalculatedthentheevaluatePreconditionsreturnsaprefilledoutresponse,withthe304statuscodeandentitytagset,thatmaybebuiltandreturned. Otherwise,evaluatePreconditionsreturnsn u l l andthenormalresponsecanbereturned. Noticethatinthisexampletheconstructorofaresourceclassisusedtoperformactionsthatmayotherwisehavetobeduplicatedtoinvokedforeach resourcemethod.Thelifecycleofresourceclassesisperrequestwhichmeansthattheresourceinstanceiscreatedforeachrequestandthereforecanwork withrequestparametersandforexamplemakechangestotherequestprocessingbythrowinganexceptionasitisshowninthisexample.

Chapter7.JAXRSEntityProviders
TableofContents 7.1.Introduction 7.2.HowtoWriteCustomEntityProviders 7.2.1.MessageBodyWriter 7.2.2.MessageBodyReader 7.3.EntityProviderSelection 7.4.JerseyM e s s a g e B o d y W o r k e r s API 7.5.DefaultJerseyEntityProviders

7.1.Introduction
Entitypayload,ifpresentinanreceivedHTTPmessage,ispassedtoJerseyfromanI/Ocontainerasaninputstream.Thestreammay,forexample,contain datarepresentedasaplaintext,XMLorJSONdocument.However,inmanyJAXRScomponentsthatprocesstheseinbounddata,suchasresource methodsorclientresponses,theJAXRSAPIusercanaccesstheinboundentityasanarbitraryJavaobjectthatiscreatedfromthecontentoftheinput streambasedontherepresentationtypeinformation.Forexample,anentitycreatedfromaninputstreamthatcontainsdatarepresentedasaXML document,canbeconvertedtoacustomJAXBbean.Similarconceptissupportedfortheoutboundentities.Anentityreturnedfromtheresourcemethodin theformofanarbitraryJavaobjectcanbeserializedbyJerseyintoacontaineroutputstreamasaspecifiedrepresentation.Ofcourse,whileJAXRS implementationsdoprovidedefaultsupportformostcommoncombinationsofJavatypeandit'srespectiveonthewirerepresentationformats,JAXRS implementationsdonotsupporttheconversiondescribedaboveforanyarbitraryJavatypeandanyarbitraryrepresentationformatbydefault.Instead,a genericextensionconceptisexposedinJAXRSAPItoallowapplicationlevelcustomizationsofthisJAXRSruntimetosupportforentityconversions.The

JAXRSextensionAPIcomponentsthatprovidetheuserlevelextensibilityaretypicallyreferredtobyseveraltermswiththesamemeaning,suchasentity providers,messagebodyproviders,messagebodyworkersormessagebodyreadersandwriters.Youmayfindallthesetermsusedinterchangeably throughouttheuserguideandtheyallrefertothesameconcept. InJAXRSextensionAPI(orSPIserviceproviderinterface,ifyoulike)theconceptiscapturedin2interfaces.Oneforhandlinginboundentity representationtoJavadeserializationMessageBodyReader<T>andtheotheroneforhandlingtheoutboundentityJavatorepresentationserialization MessageBodyWriter<T>.AM e s s a g e B o d y R e a d e r < T > ,asthenamesuggests,isanextensionthatsupportsreadingthemessagebodyrepresentationfroman inputstreamandconvertingthedataintoaninstanceofaspecificJavatype.AM e s s a g e B o d y W r i t e r < T > isthenresponsibleforconvertingamessage payloadfromaninstanceofaspecificJavatypeintoaspecificrepresentationformatthatissentoverthewiretotheotherpartyaspartofanHTTPmessage exchange.Bothoftheseproviderscanbeusedtoprovidemessagepayloadserializationanddeserializationsupportontheserveraswellastheclientside. AmessagebodyreaderorwriterisalwaysusedwheneveraHTTPrequestorresponsecontainsanentityandtheentityiseitherrequestedbytheapplication code(e.g.injectedasaparameterofJAXRSresourcemethodoraresponseentityreadontheclientfromaResponse)orhastobeserializedandsentto theotherparty(e.g.aninstancereturnedfromaJAXRSresourcemethodorarequestentitysentbyaJAXRSclient).

7.2.HowtoWriteCustomEntityProviders
Abestwayhowtolearnaboutentityprovidersistowalkthroughanexampleofwritingone.Thereforewewilldescribeheretheprocessofimplementinga customMessageBodyWriter<T>andMessageBodyReader<T>usingapracticalexample.Let'sfirstsetupthestagebydefiningaJAXRSresourceclassfor theserversidestoryofourapplication. Example7.1.Exampleresourceclass
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 @ P a t h ( " r e s o u r c e " ) p u b l i c c l a s s M y R e s o u r c e { @ G E T @ P r o d u c e s ( " a p p l i c a t i o n / x m l " ) p u b l i c M y B e a n g e t M y B e a n ( ) { r e t u r n n e w M y B e a n ( " H e l l o W o r l d ! " , 4 2 ) } @ P O S T @ C o n s u m e s ( " a p p l i c a t i o n / x m l " ) p u b l i c S t r i n g p o s t M y B e a n ( M y B e a n m y B e a n ) { r e t u r n m y B e a n . a n y S t r i n g } }

TheresourceclassdefinesG E T andP O S T resourcemethods.BothmethodsworkwithanentitythatisaninstanceofM y B e a n . TheM y B e a n classisdefinedinthenextexample: Example7.2.MyBeanentityclass


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 @ X m l R o o t E l e m e n t p u b l i c c l a s s M y B e a n { @ X m l E l e m e n t p u b l i c S t r i n g a n y S t r i n g @ X m l E l e m e n t p u b l i c i n t a n y N u m b e r p u b l i c M y B e a n ( S t r i n g a n y S t r i n g , i n t a n y N u m b e r ) { t h i s . a n y S t r i n g = a n y S t r i n g t h i s . a n y N u m b e r = a n y N u m b e r } / / e m p t y c o n s t r u c t o r n e e d e d f o r d e s e r i a l i z a t i o n b y J A X B p u b l i c M y B e a n ( ) { } @ O v e r r i d e p u b l i c S t r i n g t o S t r i n g ( ) { r e t u r n " M y B e a n { " + " a n y S t r i n g = ' " + a n y S t r i n g + ' \ ' ' + " , a n y N u m b e r = " + a n y N u m b e r + ' } ' } }

7.2.1.MessageBodyWriter
TheM y B e a n isaJAXBannotatedPOJO.InG E T resourcemethodwereturntheinstanceofMyBeanandwewouldlikeJerseyruntimetoserializeitintoXML andwriteitasanentitybodytotheresponseoutputstream.WedesignacustomM e s s a g e B o d y W r i t e r < T > thatcanserializethisPOJOintoXML.Seethe followingcodesample:

Note
Pleasenote,thatthisisonlyademonstrationofhowtowriteacustomentityprovider.Jerseyalreadycontainsdefaultsupportforentity providersthatcanserializeJAXBbeansintoXML. Example7.3.MessageBodyWriterexample
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 @ P r o d u c e s ( " a p p l i c a t i o n / x m l " ) p u b l i c c l a s s M y B e a n M e s s a g e B o d y W r i t e r i m p l e m e n t s M e s s a g e B o d y W r i t e r < M y B e a n > { @ O v e r r i d e p u b l i c b o o l e a n i s W r i t e a b l e ( C l a s s < ? > t y p e , T y p e g e n e r i c T y p e , A n n o t a t i o n [ ] a n n o t a t i o n s , M e d i a T y p e m e d i a T y p e ) { r e t u r n t y p e = = M y B e a n . c l a s s } @ O v e r r i d e p u b l i c l o n g g e t S i z e ( M y B e a n m y B e a n , C l a s s < ? > t y p e , T y p e g e n e r i c T y p e , A n n o t a t i o n [ ] a n n o t a t i o n s , M e d i a T y p e m e d i a T y p e ) { / / d e p r e c a t e d b y J A X R S 2 . 0 a n d i g n o r e d b y J e r s e y r u n t i m e r e t u r n 0 } @ O v e r r i d e p u b l i c v o i d w r i t e T o ( M y B e a n m y B e a n , C l a s s < ? > t y p e , T y p e g e n e r i c T y p e , A n n o t a t i o n [ ] a n n o t a t i o n s , M e d i a T y p e m e d i a T y p e ,

2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7

M u l t i v a l u e d M a p < S t r i n g , O b j e c t > h t t p H e a d e r s , O u t p u t S t r e a m e n t i t y S t r e a m ) t h r o w s I O E x c e p t i o n , W e b A p p l i c a t i o n E x c e p t i o n { t r y { J A X B C o n t e x t j a x b C o n t e x t = J A X B C o n t e x t . n e w I n s t a n c e ( M y B e a n . c l a s s ) / / s e r i a l i z e t h e e n t i t y m y B e a n t o t h e e n t i t y o u t p u t s t r e a m j a x b C o n t e x t . c r e a t e M a r s h a l l e r ( ) . m a r s h a l ( m y B e a n , e n t i t y S t r e a m ) } c a t c h ( J A X B E x c e p t i o n j a x b E x c e p t i o n ) { t h r o w n e w P r o c e s s i n g E x c e p t i o n ( " E r r o r s e r i a l i z i n g a M y B e a n t o t h e o u t p u t s t r e a m " , j a x b E x c e p t i o n ) } } }

TheM y B e a n M e s s a g e B o d y W r i t e r implementstheM e s s a g e B o d y W r i t e r < T > interfacethatcontainsthreemethods.Inthenextsectionswe'llexplorethese methodsmoreclosely.

7.2.1.1.M e s s a g e B o d y W r i t e r . i s W r i t e a b l e
Amethodi s W r i t e a b l e shouldreturntrueiftheM e s s a g e B o d y W r i t e r < T > isabletowritethegiventype.MethoddoesnotdecideonlybasedontheJavatype oftheentitybutalsoonannotationsattachedtotheentityandtherequestedrepresentationmediatype. Parameterst y p e andg e n e r i c T y p e bothdefinetheentity,wheret y p e isarawJavatype(forexample,aj a v a . u t i l . L i s t class>andg e n e r i c T y p e isa ParameterizedTypeincludinggenericinformation(forexampleL i s t < S t r i n g > ). Parametera n n o t a t i o n s containsannotationsthatareeitherattachedtotheresourcemethodand/orannotationsthatareattachedtotheentitybybuilding responselikeinthefollowingpieceofcode: Example7.4.Exampleofassignmentofannotationstoaresponseentity
1 2 3 4 5 6 7 8 9 1 0 1 1 @ P a t h ( " r e s o u r c e " ) p u b l i c s t a t i c c l a s s A n n o t a t e d R e s o u r c e { @ G E T p u b l i c R e s p o n s e g e t ( ) { A n n o t a t i o n a n n o t a t i o n = A n n o t a t e d R e s o u r c e . c l a s s . g e t A n n o t a t i o n ( P a t h . c l a s s ) r e t u r n R e s p o n s e . o k ( ) . e n t i t y ( " E n t i t y " , n e w A n n o t a t i o n [ ] { a n n o t a t i o n } ) . b u i l d ( ) } }

Intheexampleabove,theM e s s a g e B o d y W r i t e r < T > wouldgeta n n o t a t i o n s parametercontainingaJAXRS@ G E T annotationasitannotatestheresource methodandalsoa@ P a t h annotationasitispassedintheresponse(butnotbecauseitannotatestheresourceonlyresourcemethodannotationsare included).InthecaseofM y R e s o u r c e andmethodg e t M y B e a n theannotationswouldcontainthe@GETandthe@Producesannotation. Thelastparameterofthei s W r i t e a b l e methodisthem e d i a T y p e whichisthemediatypeattachedtotheresponseentitybyannotatingtheresourcemethod witha@ P r o d u c e s annotationortherequestmediatypespecifiedintheJAXRSClientAPI.Inourexample,themediatypepassedtoprovidersforthe resourceM y R e s o u r c e andmethodg e t M y B e a n wouldbe" a p p l i c a t i o n / x m l " . Inourimplementationofthei s W r i t e a b l e method,wejustcheckthatthetypeisM y B e a n .Pleasenote,thatthismethodmightbeexecutedmultipletimesby JerseyruntimeasJerseyneedstocheckwhetherthisprovidercanbeusedforaparticularcombinationofentityJavatype,mediatype,andattached annotations,whichmaybepotentiallyaperformancehog.Youcanlimitthenumberofexecutionbyproperlydefiningthe@ P r o d u c e s annotationonthe M e s s a g e B o d y W r i t e r < T > .Inourcasethanksto@ P r o d u c e s annotation,theproviderwillbeconsideredaswriteable(andthemethodi s W r i t e a b l e mightbe executed)onlyifthemediatypeoftheoutboundmessageis" a p p l i c a t i o n / x m l " .Additionally,theproviderwillonlybeconsideredaspossiblecandidate anditsi s W r i t e a b l e methodwillbeexecuted,ifthegenerictypeoftheprovideriseitherasubclassorsuperclassoft y p e parameter.

7.2.1.2.M e s s a g e B o d y W r i t e r . w r i t e T o
Onceamessagebodywriterisselectedasthemostappropriate(seetheSection7.3,EntityProviderSelectionformoredetailsonentityproviderselection), itsw r i t e T o methodisinvoked.Thismethodreceivesparameterswiththesamemeaningasini s W r i t e a b l e aswellasafewadditionalones. Inadditiontotheparametersalreadyintroduced,thew r i t e T o methoddefiesalsoh t t p H e a d e r s parameter,thatcontainsHTTPheadersassociatedwiththe outboundmessage.

Note
WhenaM e s s a g e B o d y W r i t e r < T > isinvoked,theheadersstillcanbemodifiedinthispointandanymodificationwillbereflectedinthe outboundHTTPmessagebeingsent.Themodificationofheadersmusthoweverhappenbeforeafirstbyteiswrittentothesuppliedoutput stream. Anothernewparameter,m y B e a n ,containstheentityinstancetobeserialized(thetypeofentitycorrespondstogenerictypeofM e s s a g e B o d y W r i t e r < T > ). Relatedparametere n t i t y S t r e a m containstheentityoutputstreamtowhichthemethodshouldserializetheentity.InourcaseweuseJAXBtomarshallthe entityintothee n t i t y S t r e a m .Note,thatthee n t i t y S t r e a m isnotclosedattheendofmethodthestreamwillbeclosedbyJersey.

Important
Donotclosetheentityoutputstreaminthew r i t e T o methodofyourM e s s a g e B o d y W r i t e r < T > implementation.

7.2.1.3.M e s s a g e B o d y W r i t e r . g e t S i z e
ThemethodisdeprecatedsinceJAXRS2.0andJersey2ignoresthereturnvalue.InJAXRS1.0themethodcouldreturnthesizeoftheentitythatwouldbe thenusedfor"ContentLength"responseheader.InJersey2.0the"ContentLength"parameteriscomputedautomaticallyusinganinternaloutboundentity buffering.FordetailsaboutconfigurationoptionsofoutboundentitybufferingseethejavadocofMessageProperties,property O U T B O U N D _ C O N T E N T _ L E N G T H _ B U F F E R whichconfiguresthesizeofthebuffer.

Note
YoucandisabletheJerseyoutboundentitybufferingbysettingthebuffersizeto0.

7.2.1.4.TestingaM e s s a g e B o d y W r i t e r < T >


BeforetestingtheM y B e a n M e s s a g e B o d y W r i t e r ,thewritermustberegisteredasacustomJAXRSextensionprovider.Itshouldeitherbeaddedtoyour applicationResourceConfig,orreturnedfromyourcustomApplicationsubclass,orannotatedwith@ProviderannotationtoleverageJAXRSproviderauto

discoveryfeature. AfterregisteringtheM y B e a n M e s s a g e B o d y W r i t e r andM y R e s o u r c e classinourapplication,therequestcanbeinitiated(inthisexamplefromClientAPI). Example7.5.ClientcodetestingMyBeanMessageBodyWriter


1 2 3 4 5 6 7 W e b T a r g e t w e b T a r g e t = / / i n i t i a l i z e w e b t a r g e t t o t h e c o n t e x t r o o t / / o f e x a m p l e a p p l i c a t i o n R e s p o n s e r e s p o n s e = w e b T a r g e t . p a t h ( " r e s o u r c e " ) . r e q u e s t ( M e d i a T y p e . A P P L I C A T I O N _ X M L ) . g e t ( ) S y s t e m . o u t . p r i n t l n ( r e s p o n s e . g e t S t a t u s ( ) ) S t r i n g m y B e a n X m l = r e s p o n s e . r e a d E n t i t y ( S t r i n g . c l a s s ) S y s t e m . o u t . p r i n t l n ( m y B e a n X m l )

TheclientcodeinitiatestheG E T whichwillbematchedtotheresourcemethodM y R e s o u r c e . g e t M y B e a n ( ) .TheresponseentityisdeserializedasaS t r i n g . Theresultofconsoleoutputis: Example7.6.ResultofMyBeanMessageBodyWritertest


2 0 0 < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " s t a n d a l o n e = " y e s " ? > < m y B e a n > < a n y S t r i n g > H e l l o W o r l d ! < / a n y S t r i n g > < a n y N u m b e r > 4 2 < / a n y N u m b e r > < / m y B e a n >

Thereturnedstatusis200andtheentityisstoredintheresponseinaX M L format.Next,wewilllookathowtheJerseydeserializesthisXMLdocumentintoa M y B e a n consumedbyourP O S T resourcemethod.

7.2.2.MessageBodyReader
InordertodeserializetheentityofM y B e a n ontheserverortheclient,weneedtoimplementacustomMessageBodyReader<T>.

Note
Pleasenote,thatthisisonlyademonstrationofhowtowriteacustomentityprovider.Jerseyalreadycontainsdefaultsupportforentity providersthatcanserializeJAXBbeansintoXML. OurM e s s a g e B o d y R e a d e r < T > implementationislistedinExample7.7,MessageBodyReaderexample. Example7.7.MessageBodyReaderexample
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 p u b l i c s t a t i c c l a s s M y B e a n M e s s a g e B o d y R e a d e r i m p l e m e n t s M e s s a g e B o d y R e a d e r < M y B e a n > { @ O v e r r i d e p u b l i c b o o l e a n i s R e a d a b l e ( C l a s s < ? > t y p e , T y p e g e n e r i c T y p e , A n n o t a t i o n [ ] a n n o t a t i o n s , M e d i a T y p e m e d i a T y p e ) { r e t u r n t y p e = = M y B e a n . c l a s s } @ O v e r r i d e p u b l i c M y B e a n r e a d F r o m ( C l a s s < M y B e a n > t y p e , T y p e g e n e r i c T y p e , A n n o t a t i o n [ ] a n n o t a t i o n s , M e d i a T y p e m e d i a T y p e , M u l t i v a l u e d M a p < S t r i n g , S t r i n g > h t t p H e a d e r s , I n p u t S t r e a m e n t i t y S t r e a m ) t h r o w s I O E x c e p t i o n , W e b A p p l i c a t i o n E x c e p t i o n { t r y { J A X B C o n t e x t j a x b C o n t e x t = J A X B C o n t e x t . n e w I n s t a n c e ( M y B e a n . c l a s s ) M y B e a n m y B e a n = ( M y B e a n ) j a x b C o n t e x t . c r e a t e U n m a r s h a l l e r ( ) . u n m a r s h a l ( e n t i t y S t r e a m ) r e t u r n m y B e a n } c a t c h ( J A X B E x c e p t i o n j a x b E x c e p t i o n ) { t h r o w n e w P r o c e s s i n g E x c e p t i o n ( " E r r o r d e s e r i a l i z i n g a M y B e a n . " , j a x b E x c e p t i o n ) } } }

ItisobviousthattheM e s s a g e B o d y R e a d e r < T > interfaceissimilartoM e s s a g e B o d y W r i t e r < T > .Inthenextcoupleofsectionswewillexploreit'sAPImethods.

7.2.2.1.M e s s a g e B o d y R e a d e r . i s R e a d a b l e
Itdefinesthemethodi s R e a d a b l e ( ) whichhasaverysimliarmeaningasmethodi s W r i t e a b l e ( ) inM e s s a g e B o d y W r i t e r < T > .Themethodreturnst r u e ifit isabletodeserializethegiventype.Thea n n o t a t i o n s parametercontainsannotationsthatareattachedtotheentityparameterintheresourcemethod.In ourP O S T resourcemethodp o s t M y B e a n theentityparameterm y B e a n isnotannotated,thereforenoannotationwillbepassedtotheisReadable.The m e d i a T y p e parametercontainstheentitymediatype.Themediatype,inourcase,mustbeconsumablebytheP O S T resourcemethod,whichisspecifiedby placingaJAXRS@Consumesannotationtothemethod.Theresourcemethodp o s t M y B e a n ( ) isannotatedwith@ C o n s u m e s ( " a p p l i c a t i o n / x m l " ) , thereforeforpurposeofdeserializationofentityforthep o s t M y B e a n ( ) method,onlyrequestswithentitiesrepresentedas" a p p l i c a t i o n / x m l " mediatype willmatchthemethod.However,thismethodmightbeexecutedforforentitytypesthataresubclassesorsuperclassesofthedeclaredgenerictypeonthe M e s s a g e B o d y R e a d e r < T > willbealsoconsidered.Itisaresponsibilityofthei s R e a d a b l e methodtodecidewhetheritisabletodeserializetheentityandtype comparisonisoneofthebasicdecisionsteps.

Tip
Inordertoreducenumberofi s R e a d a b l e executions,alwaysdefinecorrectlytheconsumablemediatype(s)withthe@ C o n s u m e s annotation onyourcustomM e s s a g e B o d y R e a d e r < T > .

7.2.2.2.M e s s a g e B o d y R e a d e r . r e a d F r o m
Ther e a d F o r m ( ) methodgetstheparameterswiththesamemeaningasini s R e a d a b l e ( ) .Theadditionale n t i t y S t r e a m parameterprovidesahandleto theentityinputstreamfromwhichtheentitybytesshouldbereadanddeserializedintoaJavaentitywhichisthenreturnedfromthemethod.Our M y B e a n M e s s a g e B o d y R e a d e r deserializestheincomingXMLdataintoaninstanceofM y B e a n usingJAXB.

Important
DonotclosetheentityinputstreaminyourM e s s a g e B o d y R e a d e r < T > implementation.ThestreamwillbeautomaticallyclosedbyJersey runtime.

7.2.2.3.TestingaM e s s a g e B o d y W r i t e r < T >


Nowlet'ssendatestrequestusingtheJAXRSClientAPI. Example7.8.TestingMyBeanMessageBodyReader
1 2 3 4 5 6 7 f i n a l M y B e a n m y B e a n = n e w M y B e a n ( " p o s t e d M y B e a n " , 1 1 ) R e s p o n s e r e s p o n s e = w e b T a r g e t . p a t h ( " r e s o u r c e " ) . r e q u e s t ( " a p p l i c a t i o n / x m l " ) . p o s t ( E n t i t y . e n t i t y ( m y B e a n , " a p p l i c a t i o n / x m l " ) ) S y s t e m . o u t . p r i n t l n ( r e s p o n s e . g e t S t a t u s ( ) ) f i n a l S t r i n g r e s p o n s e E n t i t y = r e s p o n s e . r e a d E n t i t y ( S t r i n g . c l a s s ) S y s t e m . o u t . p r i n t l n ( r e s p o n s e E n t i t y )

Theconsoleoutputis: Example7.9.ResultoftestingMyBeanMessageBodyReader
2 0 0 p o s t e d M y B e a n

7.2.2.4.UsingEntityProviderswithJAXRSClientAPI
Both,M e s s a g e B o d y R e a d e r < T > andM e s s a g e B o d y W r i t e r < T > canberegisteredinaconfigurationofJAXRSClientAPIcomponentstypicallywithoutanyneed tochangetheircode.TheexampleExample7.10,MessageBodyReaderregisteredonaJAXRSclientisavariationontheExample7.5,Clientcodetesting MyBeanMessageBodyWriterlistedinoneoftheprevioussections. Example7.10.MessageBodyReaderregisteredonaJAXRSclient
1 2 3 4 5 6 7 8 C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . r e g i s t e r ( M y B e a n M e s s a g e B o d y R e a d e r . c l a s s ) . b u i l d ( ) R e s p o n s e r e s p o n s e = c l i e n t . t a r g e t ( " h t t p : / / e x a m p l e / c o m m / r e s o u r c e " ) . r e q u e s t ( M e d i a T y p e . A P P L I C A T I O N _ X M L ) . g e t ( ) S y s t e m . o u t . p r i n t l n ( r e s p o n s e . g e t S t a t u s ( ) ) M y B e a n m y B e a n = r e s p o n s e . r e a d E n t i t y ( M y B e a n . c l a s s ) S y s t e m . o u t . p r i n t l n ( m y B e a n )

ThecodeaboveregistersM y B e a n M e s s a g e B o d y R e a d e r totheClientconfigurationusingaClientBuilderwhichmeansthattheproviderwillbeusedforany WebTargetproducedbythec l i e n t instance.

Note
YoucouldalsoregistertheJAXRSentity(andanyother)providerstoindividualW e b T a r g e t instancesproducedbytheclient. Then,usingthefluentchainofmethodinvocations,aresourcetargetpointingtoourM y R e s o u r c e isdefined,aHTTPG E T requestisinvoked.Theresponse entityisthenreadasaninstanceofaM y B e a n typebyinvokingther e s p o n s e . r e a d E n t i t y method,thatinternallylocatestheregistered M y B e a n M e s s a g e B o d y R e a d e r andusesitforentitydeserialization. Theconsoleoutputfortheexampleis: Example7.11.Resultofclientcodeexecution
2 0 0 M y B e a n { a n y S t r i n g = ' H e l l o W o r l d ! ' , a n y N u m b e r = 4 2 }

7.3.EntityProviderSelection
Usuallytherearemanyentityprovidersregisteredontheserverorclientside(bedefaulttheremustbeatleastprovidersmandatedbytheJAXRS specification,suchasprovidersforprimitivetypes,bytearray,JAXBbeans,etc.).JAXRSdefinesanalgorithmforselectingthemostsuitableproviderfor entityprocessing.ThisalgorithmworkswithinformationsuchasentityJavatypeandonthewiremediatyperepresentationofentity,andsearchesforthe mostsuitableentityproviderfromthelistofavailableprovidersbasedonthesupportedmediatypedeclaredoneachprovider(definedby@ P r o d u c e s or @ C o n s u m e s ontheproviderclass)aswellasbasedonthegenerictypedeclarationoftheavailableproviders.Whenalistofsuitablecandidateentityproviders isselectedandsortedbasedontherulesdefinedinJAXRSspecification,aJAXRSruntimethenitinvokesi s R e a d a b l e ori s W r i t e a b l e method respectivelyoneachproviderinthelistuntilafirstproviderisfoundthatreturnst r u e .Thisprovideristhenusedtoprocesstheentity. ThefollowingstepsdescribethealgorithmforselectingaM e s s a g e B o d y W r i t e r < T > (extractedfromJAXRSwithlittlemodifications).Thestepsrefertothe previouslydiscussedexampleapplication.TheM e s s a g e B o d y W r i t e r < T > issearchedforpurposeofdeserializationofM y B e a n entityreturnedfromthemethod g e t M y B e a n .So,typeisM y B e a n andmediatype" a p p l i c a t i o n / x m l " .Let'sassumetheruntimecontainsalsoregisteredproviders,namely:
A :@ P r o d u c e s ( " a p p l i c a t i o n / * " ) withgenerictype< O b j e c t > B :@ P r o d u c e s ( " * / * " ) withgenerictype< M y B e a n > C :@ P r o d u c e s ( " t e x t / p l a i n " ) withgenerictype< M y B e a n > D :@ P r o d u c e s ( " a p p l i c a t i o n / x m l " ) withgenerictype< O b j e c t > M y B e a n M e s s a g e B o d y W r i t e r :@ P r o d u c e s ( " a p p l i c a t i o n / x m l " ) withgenerictype< M y B e a n >

ThealgorithmexecutedbyaJAXRSruntimetoselectaproperM e s s a g e B o d y W r i t e r < T > implementationisillustratedinProcedure7.1, M e s s a g e B o d y W r i t e r < T > SelectionAlgorithm. Procedure7.1.M e s s a g e B o d y W r i t e r < T > SelectionAlgorithm 1. Obtaintheobjectthatwillbemappedtothemessageentitybody.ForareturntypeofResponseorsubclasses,theobjectisthevalueoftheentity property,forotherreturntypesitisthereturnedobject. Soinourcase,fortheresourcemethodg e t M y B e a n thetypewillbeM y B e a n . 2. Determinethemediatypeoftheresponse. Inourcase.forresourcemethodg e t M y B e a n annotatedwith@ P r o d u c e s ( " a p p l i c a t i o n / x m l " ) ,themediatypewillbe" a p p l i c a t i o n / x m l " . 3. SelectthesetofMessageBodyWriterprovidersthatsupporttheobjectandmediatypeofthemessageentitybody.

Inourcase,forentitymediatype" a p p l i c a t i o n / x m l " andtypeM y B e a n ,theappropriateM e s s a g e B o d y W r i t e r < T > willbetheA ,B ,D and M y B e a n M e s s a g e B o d y W r i t e r .TheproviderC doesnotdefinetheappropriatemediatype.A andB arefineastheirtypeismoregenericandcompatible with" a p p l i c a t i o n / x m l " . 4. SorttheselectedMessageBodyWriterproviderswithaprimarykeyofgenerictypewhereproviderswhosegenerictypeisthenearestsuperclassofthe objectclassaresortedfirstandasecondarykeyofmediatype.Additionally,JAXRSspecificationmandatesthatcustom,userregisteredproviders havetobesortedaheadofdefaultprovidersprovidedbyJAXRSimplementation.Thisisusedasatertiarycomparisonkey.Userprovidersareplaces priortoJerseyinternalprovidersintothefinalorderedlist. Thesortedproviderswillbe:M y B e a n M e s s a g e B o d y W r i t e r ,B .D ,A . 5. IteratethroughthesortedM e s s a g e B o d y W r i t e r < T > providersand,utilizingthei s W r i t e a b l e methodofeachuntilyoufindaM e s s a g e B o d y W r i t e r < T > thatreturnst r u e . ThefirstproviderinthelistourM y B e a n M e s s a g e B o d y W r i t e r returnst r u e asitcomparestypesandthetypesmatches.Ifitwouldreturnf a l s e ,the nextproviderB wouldbycheckbyinvokingitsi s W r i t e a b l e method. 6. Ifstep5locatesasuitableM e s s a g e B o d y W r i t e r < T > thenuseitswriteTomethodtomaptheobjecttotheentitybody.
M y B e a n M e s s a g e B o d y W r i t e r . w r i t e T o willbeexecutedanditwillserializetheentity.

Otherwise,theserverruntimeMUSTgenerateagenerateanI n t e r n a l S e r v e r E r r o r E x c e p t i o n ,asubclassofW e b A p p l i c a t i o n E x c e p t i o n withitsstatussetto500,andnoentityandtheclientruntimeMUSTgenerateaP r o c e s s i n g E x c e p t i o n . Wehavesuccessfullyfoundaprovider,thusnoexceptionisgenerated.

Note
JAXRS2.0isincompatiblewithJAXRS1.xinonestepoftheentityproviderselectionalgorithm.JAXRS1.xdefinessortingkeysprioritiesin theStep4inexactlyoppositeorder.So,inJAXRS1.xthekeysaredefinedintheorder:primarymediatype,secondarytypedeclaration distancewherecustomprovidershavealwaysprecedencetointernalproviders.IfyouwanttoforceJerseytousethealgorithmcompatible withJAXRS1.x,setuptheproperty(toResourceConfigorreturnfromApplicationfromitsg e t P r o p e r t i e s method):
j e r s e y . c o n f i g . w o r k e r s . l e g a c y O r d e r i n g = t r u e

DocumentationofthispropertycanbefoundinthejavadocofMessageProperties. ThealgorithmforselectionofM e s s a g e B o d y R e a d e r < T > issimilar,includingtheincompatibilitybetweenJAXRS2.0andJAXRS1.xandthepropertyto workaroundit.Thealgorithmisdefinedasfollows: Procedure7.2.M e s s a g e B o d y R e a d e r < T > SelectionAlgorithm 1. Obtainthemediatypeoftherequest.IftherequestdoesnotcontainaC o n t e n t T y p e headerthenusea p p l i c a t i o n / o c t e t s t r e a m mediatype. 2. IdentifytheJavatypeoftheparameterwhosevaluewillbemappedfromtheentitybody.TheJavatypeontheserveristhetypeoftheentityparameter oftheresourcemethod.OntheclientitistheC l a s s passedtor e a d F r o m method. 3. SelectthesetofavailableM e s s a g e B o d y R e a d e r < T > providersthatsupportthemediatypeoftherequest. 4. IteratethroughtheselectedM e s s a g e B o d y R e a d e r < T > classesand,utilizingtheiri s R e a d a b l e method,choosethefirstM e s s a g e B o d y R e a d e r < T > providerthatsupportsthedesiredcombinationofJavatype/mediatype/annotationsparameters. 5. IfStep4locatesasuitableM e s s a g e B o d y R e a d e r < T > ,thenuseitsr e a d F r o m methodtomaptheentitybodytothedesiredJavatype. Otherwise,theserverruntimeMUSTgenerateaN o t S u p p o r t e d E x c e p t i o n (HTTP415statuscode)andnoentityandtheclientruntimeMUST generateaninstanceofP r o c e s s i n g E x c e p t i o n .

7.4.JerseyM e s s a g e B o d y W o r k e r s API
IncaseyouneedtodirectlyworkwithJAXRSentityproviders,forexampletoserializeanentityinyourresourcemethod,filterorinacompositeentity provider,youwouldneedtoperformquitealotofsteps.YouwouldneedtochoosetheappropriateM e s s a g e B o d y W r i t e r < T > basedonthetype,mediatype andotherparameters.Thenyouwouldneedtoinstantiateit,checkitbyi s W r i t e a b l e methodandbasicallyperformallthestepsthatarenormallyperformed byJersey(seeProcedure7.2,M e s s a g e B o d y R e a d e r < T > SelectionAlgorithm). Toremovethisburdenfromdevelopers,JerseyexposesaproprietarypublicAPIthatsimplifiesthemanipulationofentityproviders.TheAPIisdefinedby MessageBodyWorkersinterfaceandJerseyprovidesanimplementationthatcanbeinjectedusingthe@Contextinjectionannotation.Theinterfacedeclares methodsforselectionofmostappropriateM e s s a g e B o d y R e a d e r < T > andM e s s a g e B o d y W r i t e r < T > basedontherulesdefinedinJAXRSspec,methodsfor writingandreadingentitythatensureproperandtimelyinvocationofinterceptorsandotherusefulmethods. SeethefollowingexampleofusageofM e s s a g e B o d y W o r k e r s . Example7.12.UsageofMessageBodyWorkersinterface
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 @ P a t h ( " w o r k e r s " ) p u b l i c s t a t i c c l a s s W o r k e r s R e s o u r c e { @ C o n t e x t p r i v a t e M e s s a g e B o d y W o r k e r s w o r k e r s @ G E T @ P r o d u c e s ( " a p p l i c a t i o n / x m l " ) p u b l i c S t r i n g g e t M y B e a n A s S t r i n g ( ) { f i n a l M y B e a n m y B e a n = n e w M y B e a n ( " H e l l o W o r l d ! " , 4 2 ) / / b u f f e r i n t o w h i c h m y B e a n w i l l b e s e r i a l i z e d B y t e A r r a y O u t p u t S t r e a m b a o s = n e w B y t e A r r a y O u t p u t S t r e a m ( ) / / g e t m o s t a p p r o p r i a t e M B W f i n a l M e s s a g e B o d y W r i t e r < M y B e a n > m e s s a g e B o d y W r i t e r = w o r k e r s . g e t M e s s a g e B o d y W r i t e r ( M y B e a n . c l a s s , M y B e a n . c l a s s , n e w A n n o t a t i o n [ ] { } , M e d i a T y p e . A P P L I C A T I O N _ X M L _ T Y P E ) t r y { / / u s e t h e M B W t o s e r i a l i z e m y B e a n i n t o b a o s m e s s a g e B o d y W r i t e r . w r i t e T o ( m y B e a n , M y B e a n . c l a s s , M y B e a n . c l a s s , n e w A n n o t a t i o n [ ] { } , M e d i a T y p e . A P P L I C A T I O N _ X M L _ T Y P E , n e w M u l t i v a l u e d H a s h M a p < S t r i n g , O b j e c t > ( ) , b a o s ) } c a t c h ( I O E x c e p t i o n e ) { t h r o w n e w R u n t i m e E x c e p t i o n ( " E r r o r w h i l e s e r i a l i z i n g M y B e a n . " , e ) }

3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0

f i n a l S t r i n g s t r i n g X m l O u t p u t = b a o s . t o S t r i n g ( ) / / s t r i n g X m l O u t p u t n o w c o n t a i n s X M L r e p r e s e n t a t i o n : / / " < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " s t a n d a l o n e = " y e s " ? > / / < m y B e a n > < a n y S t r i n g > H e l l o W o r l d ! < / a n y S t r i n g > / / < a n y N u m b e r > 4 2 < / a n y N u m b e r > < / m y B e a n > " r e t u r n s t r i n g X m l O u t p u t } }

IntheexamplearesourceinjectsM e s s a g e B o d y W o r k e r s andusesitforselectionofthemostappropriateM e s s a g e B o d y W r i t e r < T > .Thenthewriterisutilized toserializetheentityintothebufferasXMLdocument.TheS t r i n g contentofthebufferisthenreturned.ThiswillcausethatJerseywillnotuse M y B e a n M e s s a g e B o d y W r i t e r toserializetheentityasitisalreadyintheS t r i n g type(M y B e a n M e s s a g e B o d y W r i t e r doesnotsupportS t r i n g ).Instead,a simpleS t r i n g basedM e s s a g e B o d y W r i t e r < T > willbechosenanditwillonlyserializetheS t r i n g withXMLtotheoutputentitystreambywritingoutthebytes oftheS t r i n g . Ofcourse,thecodeintheexampledoesnotbringanybenefitastheentitycouldhavebeenserializedbyM y B e a n M e s s a g e B o d y W r i t e r byJerseyasin previousexamplesthepurposeoftheexamplewastoshowhowtouseM e s s a g e B o d y W o r k e r s inaresourcemethod.

7.5.DefaultJerseyEntityProviders
Jerseyinternallycontainsentityprovidersforthesetypeswithcombinationofmediatypes(inbrackets):
b y t e [ ] (* / * ) String(* / * ) InputStream(* / * ) Reader(* / * ) File(* / * ) DataSource(* / * ) Source(t e x t / x m l ,a p p l i c a t i o n / x m l andmediatypesoftheforma p p l i c a t i o n / * + x m l ) JAXBElement(t e x t / x m l ,a p p l i c a t i o n / x m l andmediatypesoftheforma p p l i c a t i o n / * + x m l ) MultivaluedMap<K,V>(a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d ) Form(a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d ) StreamingOutput((* / * ))thisclasscanbeusedasanlightweightM e s s a g e B o d y W r i t e r < T > thatcanbereturnedfromaresourcemethod Boolean,CharacterandNumber(t e x t / p l a i n )correspondingprimitivetypessupportedviaboxing/unboxingconversion

ForothermediatypesupportedinjerseypleaseseetheChapter8,SupportforCommonMediaTypeRepresentationswhichdescribesadditionalJersey entityproviderextensionsforserializationtoJSON,XML,serializationofcollections,MultiPartandothers.

Chapter8.SupportforCommonMediaTypeRepresentations
TableofContents 8.1.JSON 8.1.1.ApproachestoJSONSupport 8.1.2.MOXy 8.1.3.JavaAPIforJSONProcessing(JSONP) 8.1.4.Jackson 8.1.5.Jettison 8.1.6.@ J S O N P JSONwithPaddingSupport 8.2.XML 8.2.1.LowlevelXMLsupport 8.2.2.GettingstartedwithJAXB 8.2.3.POJOs 8.2.4.UsingcustomJAXBContext 8.2.5.MOXy 8.3.Multipart 8.3.1.Overview 8.3.2.Client 8.3.3.Server

8.1.JSON
JerseyJSONsupportcomesasasetofextensionmoduleswhereeachofthesemodulescontainsanimplementationofaFeaturethatneedstoberegistered intoyourConfigurableinstance(client/server).TherearemultipleframeworksthatprovidesupportforJSONprocessingand/orJSONtoJavabinding.The moduleslistedbellowprovidesupportforJSONrepresentationsbyintegratingtheindividualJSONframeworksintoJersey.Atpresent,Jerseyintegrateswith thefollowingmodulestoprovideJSONsupport: MOXyJSONbindingsupportviaMOXyisadefaultandpreferredwayofsupportingJSONbindinginyourJerseyapplicationssinceJersey2.0.When JSONMOXymoduleisontheclasspath,JerseywillautomaticallydiscoverthemoduleandseamlesslyenableJSONbindingsupportviaMOXyinyour applications.(SeeSection4.1,AutoDiscoverableFeatures.) JavaAPIforJSONProcessing(JSONP) Jackson Jettison

8.1.1.ApproachestoJSONSupport
EachoftheaforementionedextensionmodulesusesoneormoreofthethreebasicapproachesavailablewhenworkingwithJSONrepresentations: POJObasedJSONbindingsupport JAXBbasedJSONbindingsupport LowlevelJSONparsing&processingsupport ThefirstmethodisprettygenericandallowsyoutomapanyJavaObjecttoJSONandviceversa.TheothertwoapproacheslimityouinJavatypesyour resourcemethodscouldproduceand/orconsume.JAXBbasedapproachisusefulifyouplantoutilizecertainJAXBfeaturesandsupportbothXMLand JSONrepresentations.Thelast,lowlevel,approachgivesyouthebestfinegrainedcontrolovertheoutcomingJSONdataformat.

8.1.1.1.POJOsupport
POJOsupportrepresentstheeasiestwaytoconvertyourJavaObjectstoJSONandback. MediamodulesthatsupportthisapproachareMOXyandJackson

8.1.1.2.JAXBbasedJSONsupport
Takingthisapproachwillsaveyoualotoftime,ifyouwanttoeasilyproduce/consumebothJSONandXMLdataformat.WithJAXBbeansyouwillbeableto useathesameJavamodeltogenerateJSONaswellasXMLrepresentations.Anotheradvantageissimplicityofworkingwithsuchamodelandavailabilityof theAPIinJavaSEPlatform.JAXBleveragesannotatedPOJOsandthesecouldbehandledassimpleJavabeans. AdisadvantageofJAXBbasedapproachcouldbeifyouneedtoworkwithaveryspecificJSONformat.Thenitmightbedifficulttofindaproperwaytoget suchaformatproducedandconsumed.Thisisareasonwhyalotofconfigurationoptionsareprovided,sothatyoucancontrolhowJAXBbeansget serializedanddeserialized.Theextraconfigurationoptionshoweverrequiresyoutolearnmoredetailsabouttheframeworkyouareusing. FollowingisaverysimpleexampleofhowaJAXBbeancouldlooklike. Example8.1.SimpleJAXBbeanimplementation
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 @ X m l R o o t E l e m e n t p u b l i c c l a s s M y J a x b B e a n { p u b l i c S t r i n g n a m e p u b l i c i n t a g e p u b l i c M y J a x b B e a n ( ) { } / / J A X B n e e d s t h i s p u b l i c M y J a x b B e a n ( S t r i n g n a m e , i n t a g e ) { t h i s . n a m e = n a m e t h i s . a g e = a g e } }

UsingtheaboveJAXBbeanforproducingJSONdataformatfromyouresourcemethod,isthenassimpleas: Example8.2.JAXBbeanusedtogenerateJSONrepresentation
1 2 3 4 5 @ G E T @ P r o d u c e s ( " a p p l i c a t i o n / j s o n " ) p u b l i c M y J a x b B e a n g e t M y B e a n ( ) { r e t u r n n e w M y J a x b B e a n ( " A g a m e m n o n " , 3 2 ) }

Notice,thatJSONspecificmimetypeisspecifiedin@ P r o d u c e s annotation,andthemethodreturnsaninstanceofM y J a x b B e a n ,whichJAXBisableto process.ResultingJSONinthiscasewouldlooklike:


{ " n a m e " : " A g a m e m n o n " , " a g e " : " 3 2 " }

AproperuseofJAXBannotationsitselfenablesyoutocontroloutputJSONformattocertainextent.Specifically,renamingandomittingitemsiseasytodo directlyjustbyusingJAXBannotations.Forexample,thefollowingexampledepictschangesintheabovementionedMyJaxbBeanthatwillresultin { " k i n g " : " A g a m e m n o n " } JSONoutput. Example8.3.TweakingJSONformatusingJAXB


1 2 3 4 5 6 7 8 9 1 0 1 1 @ X m l R o o t E l e m e n t p u b l i c c l a s s M y J a x b B e a n { @ X m l E l e m e n t ( n a m e = " k i n g " ) p u b l i c S t r i n g n a m e @ X m l T r a n s i e n t p u b l i c i n t a g e / / s e v e r a l l i n e s r e m o v e d }

MediamodulesthatsupportthisapproachareMOXy,Jackson,Jettison

8.1.1.3.LowlevelbasedJSONsupport
JSONProcessingAPIisanewstandardAPIforparsingandprocessingJSONstructuresinsimilarwaytowhatSAXandStAXparsersprovideforXML.The APIispartofJavaEE7andlater.AnothersuchJSONparsing/processingAPIisprovidedbyJettisonframework.BothAPIsprovidealowlevelaccessto producingandconsumingJSONdatastructures.ByadoptingthislowlevelapproachyouwouldbeworkingwithJ s o n O b j e c t (orJ S O N O b j e c t respectively) and/orJ s o n A r r a y (orJ S O N A r r a y respectively)classeswhenprocessingyourJSONdatarepresentations. ThebiggestadvantageoftheselowlevelAPIsisthatyouwillgainfullcontrolovertheJSONformatproducedandconsumed.Youwillalsobeabletoproduce andconsumeverylargeJSONstructuresusingstreamingJSONparser/generatorAPIs.Ontheotherhand,dealingwithyourdatamodelobjectswillprobably bealotmorecomplex,comparedtothePOJOorJAXBbasedbindingapproach.Differencesaredepictedatthefollowingcodesnippets. Let'sstartwithJAXBbasedapproach. Example8.4.JAXBbeancreation
1 M y J a x b B e a n m y B e a n = n e w M y J a x b B e a n ( " A g a m e m n o n " , 3 2 )

AboveyouconstructasimpleJAXBbean,whichcouldbewritteninJSONas{ " n a m e " : " A g a m e m n o n " , " a g e " : 3 2 } NowtobuildanequivalentJ s o n O b j e c t /J S O N O b j e c t (intermsofresultingJSONexpression),youwouldneedseveralmorelinesofcode.Thefollowing exampleillustrateshowtoconstructthesameJSONdatausingthestandardJavaEE7JSONProcessingAPI. Example8.5.ConstructingaJ s o n O b j e c t (JSONProcessing)
1 2 3 4 J s o n O b j e c t m y O b j e c t = J s o n . c r e a t e O b j e c t B u i l d e r ( ) . a d d ( " n a m e " , " A g a m e m n o n " ) . a d d ( " a g e " , 3 2 ) . b u i l d ( )

Andatlast,here'showthesameworkcanbedonewithJettisonAPI.

Example8.6.ConstructingaJ S O N O b j e c t (Jettison)
1 2 3 4 5 6 7 J S O N O b j e c t m y O b j e c t = n e w J S O N O b j e c t ( ) t r y { m y O b j e c t . p u t ( " n a m e " , " A g a m e m n o n " ) m y O b j e c t . p u t ( " a g e " , 3 2 ) } c a t c h ( J S O N E x c e p t i o n e x ) { L O G G E R . l o g ( L e v e l . S E V E R E , " E r r o r . . . " , e x ) }

MediamodulesthatsupportthelowlevelJSONparsingandgeneratingapproachareJavaAPIforJSONProcessing(JSONP)andJettison.Unlessyouhave astrongreasonforusingthenonstandardJettisonAPI,werecommendyoutousethenewstandardJavaAPIforJSONProcessing(JSONP)APIinstead.

8.1.2.MOXy
8.1.2.1.Dependency
TouseMOXyasyourJSONprovideryouneedtoaddj e r s e y m e d i a m o x y moduletoyourp o m . x m l file:
< d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . m e d i a < / g r o u p I d > < a r t i f a c t I d > j e r s e y m e d i a m o x y < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Ifyou'renotusingMavenmakesuretohaveallneededdependencies(seejerseymediamoxy)ontheclasspath.

8.1.2.2.Configureandregister
AsstatedintheSection4.1,AutoDiscoverableFeaturesaswellasearlierinthischapter,MOXymediamoduleisoneofthemoduleswhereyoudon'tneed toexplicitlyregisterit'sF e a t u r e s(M o x y J s o n F e a t u r e )inyourclient/serverConfigurableasthisfeatureisautomaticallydiscoveredandregisteredwhenyou addj e r s e y m e d i a m o x y moduletoyourclasspath. Theautodiscoverablej e r s e y m e d i a m o x y moduledefinesafewpropertiesthatcanbeusedtocontroltheautomaticregistrationofM o x y J s o n F e a t u r e (besidesthegenericCommonProperties.FEATURE_AUTO_DISCOVERY_DISABLEantheitsclient/servervariants): CommonProperties.MOXY_JSON_FEATURE_DISABLE ServerProperties.MOXY_JSON_FEATURE_DISABLE ClientProperties.MOXY_JSON_FEATURE_DISABLE

Note
AmanualregistrationofanyotherJerseyJSONproviderfeature(exceptforJavaAPIforJSONProcessing(JSONP))disablestheautomated enablingandconfigurationofM o x y J s o n F e a t u r e . ToconfigureMessageBodyReader<T>s/MessageBodyWriter<T>sprovidedbyMOXyyoucansimplycreateaninstanceofMoxyJsonConfigandsetvalues ofneededproperties.Formostcommonpropertiesyoucanuseaparticularmethodtosetthevalueofthepropertyoryoucanusemoregenericmethodsto settheproperty: MoxyJsonConfig#property(java.lang.String,java.lang.Object)setsapropertyvalueforbothMarshallerandUnmarshaller. MoxyJsonConfig#marshallerProperty(java.lang.String,java.lang.Object)setsapropertyvalueforMarshaller. MoxyJsonConfig#unmarshallerProperty(java.lang.String,java.lang.Object)setsapropertyvalueforUnmarshaller. Example8.7.MoxyJsonConfigSettingproperties.
1 2 3 4 5 6 f i n a l M a p < S t r i n g , S t r i n g > n a m e s p a c e P r e f i x M a p p e r = n e w H a s h M a p < S t r i n g , S t r i n g > ( ) n a m e s p a c e P r e f i x M a p p e r . p u t ( " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a i n s t a n c e " , " x s i " ) f i n a l M o x y J s o n C o n f i g c o n f i g u r a t i o n = n e w M o x y J s o n C o n f i g ( ) . s e t N a m e s p a c e P r e f i x M a p p e r ( n a m e s p a c e P r e f i x M a p p e r ) . s e t N a m e s p a c e S e p a r a t o r ( ' : ' )

InordertomakeM o x y J s o n C o n f i g visibleforMOXyyouneedtocreateandregisterC o n t e x t R e s o l v e r < T > inyourclient/servercode. Example8.8.C o n t e x t R e s o l v e r < M o x y J s o n C o n f i g >


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 @ P r o v i d e r p u b l i c c l a s s J s o n M o x y C o n f i g u r a t i o n C o n t e x t R e s o l v e r i m p l e m e n t s C o n t e x t R e s o l v e r < M o x y J s o n C o n f i g > { p r i v a t e f i n a l M o x y J s o n C o n f i g c o n f i g p u b l i c J s o n M o x y C o n f i g u r a t i o n C o n t e x t R e s o l v e r ( ) { f i n a l M a p < S t r i n g , S t r i n g > n a m e s p a c e P r e f i x M a p p e r = n e w H a s h M a p < S t r i n g , S t r i n g > ( ) n a m e s p a c e P r e f i x M a p p e r . p u t ( " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a i n s t a n c e " , " x s i " ) c o n f i g = M o x y J s o n C o n f i g ( ) . s e t N a m e s p a c e P r e f i x M a p p e r ( n a m e s p a c e P r e f i x M a p p e r ) . s e t N a m e s p a c e S e p a r a t o r ( ' : ' ) } @ O v e r r i d e p u b l i c M o x y J s o n C o n f i g g e t C o n t e x t ( C l a s s < ? > o b j e c t T y p e ) { r e t u r n c o n f i g } }

AnotherwaytopassconfigurationpropertiestotheunderlyingM O X y J s o n P r o v i d e r istosetthemdirectlyintoyourConfigurableinstance(seeanexample below).TheseareoverwrittenbypropertiessetintotheMoxyJsonConfig. Example8.9.SettingpropertiesforMOXyprovidersintoConfigurable


1 2 3 n e w R e s o u r c e C o n f i g ( ) . p r o p e r t y ( M a r s h a l l e r P r o p e r t i e s . J S O N _ N A M E S P A C E _ S E P A R A T O R , " . " ) / / f u r t h e r c o n f i g u r a t i o n

TherearesomepropertiesforwhichJerseysetsthedefaultvaluewhenMessageBodyReader<T>/MessageBodyWriter<T>fromMOXyisusedandtheyare: Table8.1.DefaultpropertyvaluesforMOXyMessageBodyReader<T>/MessageBodyWriter<T>
j a v a x . x m l . b i n d . M a r s h a l l e r # J A X B _ F O R M A T T E D _ O U T P U T o r g . e c l i p s e . p e r s i s t e n c e . j a x b . J A X B C o n t e x t P r o p e r t i e s # J S O N _ I N C L U D E _ R O O T f a l s e f a l s e

o r g . e c l i p s e . p e r s i s t e n c e . j a x b . M a r s h a l l e r P r o p e r t i e s # J S O N _ M A R S H A L _ E M P T Y _ C O L L E C T I O N St r u e o r g . e c l i p s e . p e r s i s t e n c e . j a x b . J A X B C o n t e x t P r o p e r t i e s # J S O N _ N A M E S P A C E _ S E P A R A T O R o r g . e c l i p s e . p e r s i s t e n c e . o x m . X M L C o n s t a n t s # D O T

Example8.10.BuildingclientwithMOXyJSONfeatureenabled.
1 2 3 4 5 6 7 f i n a l C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) / / T h e l i n e b e l l o w t h a t r e g i s t e r s M O X y f e a t u r e c a n b e / / o m i t t e d i f F E A T U R E _ A U T O _ D I S C O V E R Y _ D I S A B L E i s / / n o t d i s a b l e d . . r e g i s t e r ( M o x y J s o n F e a t u r e . c l a s s ) . r e g i s t e r ( J s o n M o x y C o n f i g u r a t i o n C o n t e x t R e s o l v e r . c l a s s ) . b u i l d ( )

Example8.11.CreatingJAXRSapplicationwithMOXyJSONfeatureenabled.
1 2 3 4 5 6 7 8 / / C r e a t e J A X R S a p p l i c a t i o n . f i n a l A p p l i c a t i o n a p p l i c a t i o n = n e w R e s o u r c e C o n f i g ( ) . p a c k a g e s ( " o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . j s o n m o x y " ) / / T h e l i n e b e l l o w t h a t r e g i s t e r s M O X y f e a t u r e c a n b e / / o m i t t e d i f F E A T U R E _ A U T O _ D I S C O V E R Y _ D I S A B L E i s / / n o t d i s a b l e d . . r e g i s t e r ( M o x y J s o n F e a t u r e . c l a s s ) . r e g i s t e r ( J s o n M o x y C o n f i g u r a t i o n C o n t e x t R e s o l v e r . c l a s s )

8.1.2.3.Examples
JerseyprovidesanJSONMOXyexampleonhowtouseMOXytoconsume/produceJSON.

8.1.3.JavaAPIforJSONProcessing(JSONP)
8.1.3.1.Dependency
TouseJSONPasyourJSONprovideryouneedtoaddj e r s e y m e d i a j s o n p r o c e s s i n g moduletoyourp o m . x m l file:
< d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . m e d i a < / g r o u p I d > < a r t i f a c t I d > j e r s e y m e d i a j s o n p r o c e s s i n g < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Ifyou'renotusingMavenmakesuretohaveallneededdependencies(seejerseymediajsonprocessing)ontheclasspath.

8.1.3.2.Configureandregister
AsstatedinSection4.1,AutoDiscoverableFeaturesJSONProcessingmediamoduleisoneofthemoduleswhereyoudon'tneedtoexplicitlyregisterit's F e a t u r e s(J s o n P r o c e s s i n g F e a t u r e )inyourclient/serverConfigurableasthisfeatureisautomaticallydiscoveredandregisteredwhenyouaddj e r s e y m e d i a j s o n p r o c e s s i n g moduletoyourclasspath. Asfortheothermodules,j e r s e y m e d i a j s o n p r o c e s s i n g hasalsofewpropertiesthatcanaffecttheregistrationofJ s o n P r o c e s s i n g F e a t u r e (besides CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLEandthelike): CommonProperties.JSON_PROCESSING_FEATURE_DISABLE ServerProperties.JSON_PROCESSING_FEATURE_DISABLE ClientProperties.JSON_PROCESSING_FEATURE_DISABLE ToconfigureMessageBodyReader<T>s/MessageBodyWriter<T>sprovidedbyJSONPyoucansimplyaddvaluesforsupportedpropertiesintothe Configurationinstance(client/server).Currentlysupportedaretheseproperties:
J s o n G e n e r a t o r . P R E T T Y _ P R I N T I N G ("j a v a x . j s o n . s t r e a m . J s o n G e n e r a t o r . p r e t t y P r i n t i n g ")

Example8.12.BuildingclientwithJSONProcessingJSONfeatureenabled.
1 2 3 4 5 6 C l i e n t B u i l d e r . n e w C l i e n t ( n e w C l i e n t C o n f i g ( ) / / T h e l i n e b e l l o w t h a t r e g i s t e r s J S O N P r o c e s s i n g f e a t u r e c a n b e / / o m i t t e d i f F E A T U R E _ A U T O _ D I S C O V E R Y _ D I S A B L E i s n o t d i s a b l e d . . r e g i s t e r ( J s o n P r o c e s s i n g F e a t u r e . c l a s s ) . p r o p e r t y ( J s o n G e n e r a t o r . P R E T T Y _ P R I N T I N G , t r u e ) )

Example8.13.CreatingJAXRSapplicationwithJSONProcessingJSONfeatureenabled.
1 2 3 4 5 6 7 / / C r e a t e J A X R S a p p l i c a t i o n . f i n a l A p p l i c a t i o n a p p l i c a t i o n = n e w R e s o u r c e C o n f i g ( ) / / T h e l i n e b e l l o w t h a t r e g i s t e r s J S O N P r o c e s s i n g f e a t u r e c a n b e / / o m i t t e d i f F E A T U R E _ A U T O _ D I S C O V E R Y _ D I S A B L E i s n o t d i s a b l e d . . r e g i s t e r ( J s o n P r o c e s s i n g F e a t u r e . c l a s s ) . p a c k a g e s ( " o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . j s o n p " ) . p r o p e r t y ( J s o n G e n e r a t o r . P R E T T Y _ P R I N T I N G , t r u e )

8.1.3.3.Examples
JerseyprovidesanJSONProcessingexampleonhowtouseJSONProcessingtoconsume/produceJSON.

8.1.4.Jackson
8.1.4.1.Dependency
TouseJacksonasyourJSONprovideryouneedtoaddj e r s e y m e d i a j s o n j a c k s o n moduletoyourp o m . x m l file:
< d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . m e d i a < / g r o u p I d > < a r t i f a c t I d > j e r s e y m e d i a j s o n j a c k s o n < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Ifyou'renotusingMavenmakesuretohaveallneededdependencies(seejerseymediajsonjackson)ontheclasspath.

8.1.4.2.Configureandregister
JacksonJSONprocessorcouldbecontrolledviaprovidingacustomJacksonObjectMapperinstance.Thiscouldbehandyifyouneedtoredefinethedefault JacksonbehaviourandtofinetunehowyourJSONdatastructureslooklike.DetaileddescriptionofallJacksonfeaturesisoutofscopeofthisguide.The examplebellowgivesyouahintonhowtowireyourO b j e c t M a p p e r instanceintoyourJerseyapplication. InordertouseJacksonasyourJSON(JAXB/POJO)provideryouneedtoregisterJacksonFeatureandaC o n t e x t R e s o l v e r < T > forO b j e c t M a p p e r (if needed)inyourConfigurable(client/server). Example8.14.C o n t e x t R e s o l v e r < O b j e c t M a p p e r >
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 @ P r o v i d e r p u b l i c c l a s s M y O b j e c t M a p p e r P r o v i d e r i m p l e m e n t s C o n t e x t R e s o l v e r < O b j e c t M a p p e r > { f i n a l O b j e c t M a p p e r d e f a u l t O b j e c t M a p p e r f i n a l O b j e c t M a p p e r c o m b i n e d O b j e c t M a p p e r p u b l i c M y O b j e c t M a p p e r P r o v i d e r ( ) { d e f a u l t O b j e c t M a p p e r = c r e a t e D e f a u l t M a p p e r ( ) c o m b i n e d O b j e c t M a p p e r = c r e a t e C o m b i n e d O b j e c t M a p p e r ( ) } @ O v e r r i d e p u b l i c O b j e c t M a p p e r g e t C o n t e x t ( C l a s s < ? > t y p e ) { i f ( t y p e = = C o m b i n e d A n n o t a t i o n B e a n . c l a s s ) { r e t u r n c o m b i n e d O b j e c t M a p p e r } e l s e { r e t u r n d e f a u l t O b j e c t M a p p e r } } p r i v a t e s t a t i c O b j e c t M a p p e r c r e a t e D e f a u l t M a p p e r ( ) { f i n a l O b j e c t M a p p e r r e s u l t = n e w O b j e c t M a p p e r ( ) r e s u l t . c o n f i g u r e ( F e a t u r e . I N D E N T _ O U T P U T , t r u e ) r e t u r n r e s u l t } / / . . . }

Example8.15.BuildingclientwithJacksonJSONfeatureenabled.
1 2 3 4 f i n a l C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . r e g i s t e r ( M y O b j e c t M a p p e r P r o v i d e r . c l a s s ) / / N o n e e d t o r e g i s t e r t h i s p r o v i d e r i f n o s p e c i a l c o n f i g u r a t i o n i s r e q u i r e d . . r e g i s t e r ( J a c k s o n F e a t u r e . c l a s s ) . b u i l d ( )

Example8.16.CreatingJAXRSapplicationwithJacksonJSONfeatureenabled.
1 2 3 4 5 / / C r e a t e J A X R S a p p l i c a t i o n . f i n a l A p p l i c a t i o n a p p l i c a t i o n = n e w R e s o u r c e C o n f i g ( ) . p a c k a g e s ( " o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . j a c k s o n " ) . r e g i s t e r ( M y O b j e c t M a p p e r P r o v i d e r . c l a s s ) / / N o n e e d t o r e g i s t e r t h i s p r o v i d e r i f n o s p e c i a l c o n f i g u r a t i o n i s r e q u i r e d . . r e g i s t e r ( J a c k s o n F e a t u r e . c l a s s )

8.1.4.3.Examples
JerseyprovidesanJSONJacksonexampleonhowtouseJacksontoconsume/produceJSON.

8.1.5.Jettison
JAXBapproachfor(de)serializingJSONinJettisonmoduleprovides,inadditiontousingpureJAXB,configurationoptionsthatcouldbesetonan JettisonConfiginstance.TheinstancecouldbethenfurtherusedtocreateaJettisonJaxbContext,whichservesasamainconfigurationpointinthisarea.To passyourspecializedJ e t t i s o n J a x b C o n t e x t toJersey,youwillfinallyneedtoimplementaJAXBContextContextResolver<T>(seebelow).

8.1.5.1.Dependency
TouseJettisonasyourJSONprovideryouneedtoaddj e r s e y m e d i a j s o n j e t t i s o n moduletoyourp o m . x m l file:
< d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . m e d i a < / g r o u p I d > < a r t i f a c t I d > j e r s e y m e d i a j s o n j e t t i s o n < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Ifyou'renotusingMavenmakesuretohaveallneededdependencies(seejerseymediajsonjettison)ontheclasspath.

8.1.5.2.JSONNotations

J e t t i s o n C o n f i g allowsyoutousetwoJSONnotations.EachofthesenotationsserializesJSONinadifferentway.Followingisalistofsupportednotations:

JETTISON_MAPPED(defaultnotation) BADGERFISH Youmightwanttouseoneofthesenotations,whenworkingwithmorecomplexXMLdocuments.NamelywhenyoudealwithmultipleXMLnamespacesin yourJAXBbeans. Individualnotationsandtheirfurtherconfigurationoptionsaredescribedbellow.RatherthenexplainingrulesformappingXMLconstructsintoJSON,the notationswillbedescribedusingasimpleexample.FollowingareJAXBbeans,whichwillbeused. Example8.17.JAXBbeansforJSONsupportednotationsdescription,simpleaddressbean


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 @ X m l R o o t E l e m e n t p u b l i c c l a s s A d d r e s s { p u b l i c S t r i n g s t r e e t p u b l i c S t r i n g t o w n p u b l i c A d d r e s s ( ) { } p u b l i c A d d r e s s ( S t r i n g s t r e e t , S t r i n g t o w n ) { t h i s . s t r e e t = s t r e e t t h i s . t o w n = t o w n } }

Example8.18.JAXBbeansforJSONsupportednotationsdescription,contactbean
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 @ X m l R o o t E l e m e n t p u b l i c c l a s s C o n t a c t { p u b l i c i n t i d p u b l i c S t r i n g n a m e p u b l i c L i s t < A d d r e s s > a d d r e s s e s p u b l i c C o n t a c t ( ) { } p u b l i c C o n t a c t ( i n t i d , S t r i n g n a m e , L i s t < A d d r e s s > a d d r e s s e s ) { t h i s . n a m e = n a m e t h i s . i d = i d t h i s . a d d r e s s e s = ( a d d r e s s e s ! = n u l l ) ? n e w L i n k e d L i s t < A d d r e s s > ( a d d r e s s e s ) : n u l l } }

Followingtextwillbemainlyworkingwithacontactbeaninitializedwith: Example8.19.JAXBbeansforJSONsupportednotationsdescription,initialization
1 2 A d d r e s s [ ] a d d r e s s e s = { n e w A d d r e s s ( " L o n g S t r e e t 1 " , " S h o r t V i l l a g e " ) } C o n t a c t c o n t a c t = n e w C o n t a c t ( 2 , " B o b " , A r r a y s . a s L i s t ( a d d r e s s e s ) )

I.e.contactbeanwithi d = 2 ,n a m e = " B o b " containingasingleaddress(s t r e e t = " L o n g S t r e e t 1 " ,t o w n = " S h o r t V i l l a g e " ). AllbellowdescribedconfigurationoptionsaredocumentedalsoinapidocsatJettisonConfig.

8.1.5.2.1.Jettisonmappednotation
IfyouneedtodealwithvariousXMLnamespaces,youwillfindJettisonm a p p e d notationprettyuseful.Letsdefineaparticularnamespacefori d item:
1 2 3 4 . . . @ X m l E l e m e n t ( n a m e s p a c e = " h t t p : / / e x a m p l e . c o m " ) p u b l i c i n t i d . . .

ThenyousimplyconfigureamappingfromXMLnamespaceintoJSONprefixasfollows: Example8.20.XMLnamespacetoJSONmappingconfigurationforJettisonbasedm a p p e d notation


1 2 3 4 5 M a p < S t r i n g , S t r i n g > n s 2 j s o n = n e w H a s h M a p < S t r i n g , S t r i n g > ( ) n s 2 j s o n . p u t ( " h t t p : / / e x a m p l e . c o m " , " e x a m p l e " ) c o n t e x t = n e w J e t t i s o n J a x b C o n t e x t ( J e t t i s o n C o n f i g . m a p p e d J e t t i s o n ( ) . x m l 2 J s o n N s ( n s 2 j s o n ) . b u i l d ( ) , t y p e s )

ResultingJSONwilllooklikeintheexamplebellow. Example8.21.JSONexpressionwithXMLnamespacesmappedintoJSON
1 2 3 4 5 6 7 8 9 1 0 { " c o n t a c t " : { " e x a m p l e . i d " : 2 , " n a m e " : " B o b " , " a d d r e s s e s " : { " s t r e e t " : " L o n g S t r e e t 1 " , " t o w n " : " S h o r t V i l l a g e " } } }

Pleasenote,thati d itembecamee x a m p l e . i d basedontheXMLnamespacemapping.IfyouhavemoreXMLnamespacesinyourXML,youwillneedto configureappropriatemappingforallofthem. AnotherconfigurableoptionintroducedinJerseyversion2.2isrelatedtoserializationofJSONarrayswithJettison'smappednotation.Whenserializing elementsrepresentingsingleitemlists/arrays,youmightwanttoutilisethefollowingJerseyconfigurationmethodtoexplicitlynamewhichelementstotreatas arraysnomatterwhattheactualcontentis. Example8.22.JSONArrayconfigurationforJettisonbasedm a p p e d notation

1 2 3

c o n t e x t = n e w J e t t i s o n J a x b C o n t e x t ( J e t t i s o n C o n f i g . m a p p e d J e t t i s o n ( ) . s e r i a l i z e A s A r r a y ( " n a m e " ) . b u i l d ( ) , t y p e s )

ResultingJSONwilllooklikeintheexamplebellow,unimportantlinesremovedforsanity. Example8.23.JSONexpressionwithJSONarraysexplicitlyconfiguredviaJersey
1 2 3 4 5 6 7 { " c o n t a c t " : { . . . " n a m e " : [ " B o b " ] , . . . } }

8.1.5.2.2.Badgerfishnotation
FromJSONandJavaScriptperspective,thisnotationisdefinitelytheworstreadableone.Youwillprobablynotwanttouseit,unlessyouneedtomakesure yourJAXBbeanscouldbeflawlesslywrittenandreadbacktoandfromJSON,withoutbotheringwithanyformattingconfiguration,namespaces,etc.
J e t t i s o n C o n f i g instanceusingb a d g e r f i s h notationcouldbebuiltwith 1 J e t t i s o n C o n f i g . b a d g e r F i s h ( ) . b u i l d ( )

andtheJSONoutputJSONwillbeasfollows. Example8.24.JSONexpressionproducedusingb a d g e r f i s h notation


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 { " c o n t a c t " : { " i d " : { " $ " : " 2 " } , " n a m e " : { " $ " : " B o b " } , " a d d r e s s e s " : { " s t r e e t " : { " $ " : " L o n g S t r e e t 1 " } , " t o w n " : { " $ " : " S h o r t V i l l a g e " } } } }

8.1.5.3.Configureandregister
InordertouseJettisonasyourJSON(JAXB/POJO)provideryouneedtoregisterJettisonFeatureandaC o n t e x t R e s o l v e r < T > forJ A X B C o n t e x t (ifneeded) inyourConfigurable(client/server). Example8.25.C o n t e x t R e s o l v e r < O b j e c t M a p p e r >
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 @ P r o v i d e r p u b l i c c l a s s J a x b C o n t e x t R e s o l v e r i m p l e m e n t s C o n t e x t R e s o l v e r < J A X B C o n t e x t > { p r i v a t e f i n a l J A X B C o n t e x t c o n t e x t p r i v a t e f i n a l S e t < C l a s s < ? > > t y p e s p r i v a t e f i n a l C l a s s < ? > [ ] c T y p e s = { F l i g h t s . c l a s s , F l i g h t T y p e . c l a s s , A i r c r a f t T y p e . c l a s s } p u b l i c J a x b C o n t e x t R e s o l v e r ( ) t h r o w s E x c e p t i o n { t h i s . t y p e s = n e w H a s h S e t < C l a s s < ? > > ( A r r a y s . a s L i s t ( c T y p e s ) ) t h i s . c o n t e x t = n e w J e t t i s o n J a x b C o n t e x t ( J e t t i s o n C o n f i g . D E F A U L T , c T y p e s ) } @ O v e r r i d e p u b l i c J A X B C o n t e x t g e t C o n t e x t ( C l a s s < ? > o b j e c t T y p e ) { r e t u r n ( t y p e s . c o n t a i n s ( o b j e c t T y p e ) ) ? c o n t e x t : n u l l } }

Example8.26.BuildingclientwithJettisonJSONfeatureenabled.
1 2 3 4 f i n a l C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . r e g i s t e r ( J a x b C o n t e x t R e s o l v e r . c l a s s ) / / N o n e e d t o r e g i s t e r t h i s p r o v i d e r i f n o s p e c i a l c o n f i g u r a t i o n i s r e q u i r e d . . r e g i s t e r ( J e t t i s o n F e a t u r e . c l a s s ) . b u i l d ( )

Example8.27.CreatingJAXRSapplicationwithJettisonJSONfeatureenabled.
1 2 3 4 5 / / C r e a t e J A X R S a p p l i c a t i o n . f i n a l A p p l i c a t i o n a p p l i c a t i o n = n e w R e s o u r c e C o n f i g ( ) . p a c k a g e s ( " o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . j e t t i s o n " ) . r e g i s t e r ( J a x b C o n t e x t R e s o l v e r . c l a s s ) / / N o n e e d t o r e g i s t e r t h i s p r o v i d e r i f n o s p e c i a l c o n f i g u r a t i o n i s r e q u i r e d . . r e g i s t e r ( J e t t i s o n F e a t u r e . c l a s s )

8.1.5.4.Examples
JerseyprovidesanJSONJettisonexampleonhowtouseJettisontoconsume/produceJSON.

8.1.6.@ J S O N P JSONwithPaddingSupport
JerseyprovidesoutoftheboxsupportforJSONPJSONwithpadding.Thefollowingconditionshastobemettotakeadvantageofthiscapability: Resourcemethod,whichshouldreturnwrappedJSON,needstobeannotatedwith@JSONPannotation. MessageBodyWriter<T>fora p p l i c a t i o n / j s o n mediatype,whichalsoacceptsthereturntypeoftheresourcemethod,needstoberegistered(see JSONsectionofthischapter). User'srequesthastocontainA c c e p t headerwithoneoftheJavaScriptmediatypesdefined(seebelow). Acceptablemediatypescompatiblewith@ J S O N P are:a p p l i c a t i o n / j a v a s c r i p t ,a p p l i c a t i o n / x j a v a s c r i p t ,a p p l i c a t i o n / e c m a s c r i p t , t e x t / j a v a s c r i p t ,t e x t / x j a v a s c r i p t ,t e x t / e c m a s c r i p t ,t e x t / j s c r i p t . Example8.28.Simplestcaseofusing@ J S O N P
1 2 3 4 5 6 @ G E T @ J S O N P @ P r o d u c e s ( { " a p p l i c a t i o n / j s o n " , " a p p l i c a t i o n / j a v a s c r i p t " } ) p u b l i c J a x b B e a n g e t S i m p l e J S O N P ( ) { r e t u r n n e w J a x b B e a n ( " j s o n p " ) }

AssumethatwehaveregisteredaJSONprovidersandthattheJ a x b B e a n lookslike: Example8.29.JaxbBeanfor@JSONPexample


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 @ X m l R o o t E l e m e n t p u b l i c c l a s s J a x b B e a n { p r i v a t e S t r i n g v a l u e p u b l i c J a x b B e a n ( ) { } p u b l i c J a x b B e a n ( f i n a l S t r i n g v a l u e ) { t h i s . v a l u e = v a l u e } p u b l i c S t r i n g g e t V a l u e ( ) { r e t u r n v a l u e } p u b l i c v o i d s e t V a l u e ( f i n a l S t r i n g v a l u e ) { t h i s . v a l u e = v a l u e } }

WhenyousendaG E T requestwithA c c e p t headersettoa p p l i c a t i o n / j a v a s c r i p t you'llgetaresultentitythatlooklike:


1 2 3 c a l l b a c k ( { " v a l u e " : " j s o n p " , } )

Thereare,ofcourse,waystoconfigurewrappingmethodofthereturnedentitywhichdefaultstoc a l l b a c k asyoucanseeinthepreviousexample.@ J S O N P hastwoparametersthatcanbeconfigured:c a l l b a c k andq u e r y P a r a m .c a l l b a c k standsforthenameoftheJavaScriptcallbackfunctiondefinedbythe application.Thesecondparameter,q u e r y P a r a m ,definesthenameofthequeryparameterholdingthenameofthecallbackfunctiontobeused(ifpresentin therequest).Valueofq u e r y P a r a m defaultsto_ _ c a l l b a c k soevenifyoudonotsetthenameofthequeryparameteryourself,clientcanalwaysaffectthe resultnameofthewrappingJavaScriptcallbackmethod.

Note
q u e r y P a r a m value(ifset)alwaystakesprecedenceoverc a l l b a c k value.

Letsmodifyourexamplealittlebit: Example8.30.Exampleof@ J S O N P withconfiguredparameters.


1 2 3 4 5 6 @ G E T @ P r o d u c e s ( { " a p p l i c a t i o n / j s o n " , " a p p l i c a t i o n / j a v a s c r i p t " } ) @ J S O N P ( c a l l b a c k = " e v a l " , q u e r y P a r a m = " j s o n p C a l l b a c k " ) p u b l i c J a x b B e a n g e t S i m p l e J S O N P ( ) { r e t u r n n e w J a x b B e a n ( " j s o n p " ) }

Andmaketworequests:
c u r l X G E T h t t p : / / l o c a l h o s t : 8 0 8 0 / j s o n p

willreturn
1 2 3 e v a l ( { " v a l u e " : " j s o n p " , } )

andthe
c u r l X G E T h t t p : / / l o c a l h o s t : 8 0 8 0 / j s o n p ? j s o n p C a l l b a c k = a l e r t

willreturn
1 2 3 a l e r t ( { " v a l u e " : " j s o n p " , } )

Example.YoucantakealookataprovidedexampleavailableatJSONwithPaddingexample.

8.2.XML
Asyouprobablyalreadyknow,JerseyusesM e s s a g e B o d y W r i t e r < T > sandM e s s a g e B o d y R e a d e r < T > stoparseincomingrequestsandcreateoutgoing responses.Everyusercancreateitsownrepresentationbut...thisisnotrecommendedwayhowtodothings.XMLisprovenstandardforinterchanging information,especiallyinwebservices.JerseyssupportslowleveldatatypesusedfordirectmanipulationandJAXBXMLentities.

8.2.1.LowlevelXMLsupport
Jerseycurrentlysupportseverallowleveldatatypes:StreamSource,SAXSource,DOMSourceandDocument.Youcanusethesetypesasthereturntypeor asamethod(resource)parameter.Letssaywewanttotestthisfeatureandwehavehelloworldexampleasastartingpoint.Allweneedtodoisaddmethods (resources)whichconsumesandproducesXMLandtypesmentionedabovewillbeused. Example8.31.LowlevelXMLtestmethodsaddedtoH e l l o W o r l d R e s o u r c e . j a v a
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 @ P O S T @ P a t h ( " S t r e a m S o u r c e " ) p u b l i c S t r e a m S o u r c e g e t S t r e a m S o u r c e ( S t r e a m S o u r c e s t r e a m S o u r c e ) { r e t u r n s t r e a m S o u r c e } @ P O S T @ P a t h ( " S A X S o u r c e " ) p u b l i c S A X S o u r c e g e t S A X S o u r c e ( S A X S o u r c e s a x S o u r c e ) { r e t u r n s a x S o u r c e } @ P O S T @ P a t h ( " D O M S o u r c e " ) p u b l i c D O M S o u r c e g e t D O M S o u r c e ( D O M S o u r c e d o m S o u r c e ) { r e t u r n d o m S o u r c e } @ P O S T @ P a t h ( " D o c u m e n t " ) p u b l i c D o c u m e n t g e t D o c u m e n t ( D o c u m e n t d o c u m e n t ) { r e t u r n d o c u m e n t }

BothM e s s a g e B o d y W r i t e r < T > andM e s s a g e B o d y R e a d e r < T > areusedinthiscase,allweneedisaP O S T requestwithsomeXMLdocumentasarequest entity.Tokeepthisassimpleaspossibleonlyrootelementwithnocontentwillbesent:" < t e s t / > " .YoucancreateJAXRSclienttodothatorusesome othertool,forexamplec u r l :
c u r l v h t t p : / / l o c a l h o s t : 8 0 8 0 / b a s e / h e l l o w o r l d / S t r e a m S o u r c e d " < t e s t / > "

YoushouldgetexactlythesameXMLfromourserviceasispresentintherequestinthiscase,XMLheadersareaddedtoresponsebutcontentstays.Feel freetoiteratethroughallresources.

8.2.2.GettingstartedwithJAXB
GoodstartforpeoplewhichalreadyhavesomeexperiencewithJAXBannotationsisJAXBexample.Youcanseevarioususecasesthere.Thistextismainly meantforthosewhodon'thavepriorexperiencewithJAXB.Don'texpectthatallpossibleannotationsandtheircombinationswillbecoveredinthischapter, JAXB(JSR222implementation)isprettycomplexandcomprehensive.ButifyoujustwanttoknowhowyoucaninterchangeXMLmessageswithyourREST service,youarelookingattherightchapter. Letsstartwithsimpleexample.LetssaywehaveclassP l a n e t andservicewhichproduces"Planets". Example8.32.Planetclass
1 2 3 4 5 6 @ X m l R o o t E l e m e n t p u b l i c c l a s s P l a n e t { p u b l i c i n t i d p u b l i c S t r i n g n a m e p u b l i c d o u b l e r a d i u s }

Example8.33.Resourceclass
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 @ P a t h ( " p l a n e t " ) p u b l i c c l a s s R e s o u r c e { @ G E T @ P r o d u c e s ( M e d i a T y p e . A P P L I C A T I O N _ X M L ) p u b l i c P l a n e t g e t P l a n e t ( ) { f i n a l P l a n e t p l a n e t = n e w P l a n e t ( ) p l a n e t . i d = 1 p l a n e t . n a m e = " E a r t h " p l a n e t . r a d i u s = 1 . 0 r e t u r n p l a n e t } }

YoucanseethereissomeextraannotationdeclaredonP l a n e t class,particularly@XmlRootElement.ThisisanJAXBannotationwhichmapsjavaclassesto XMLelements.Wedon'tneedtospecifyanythingelse,becauseP l a n e t isverysimpleclassandallfieldsarepublic.Inthiscase,XMLelementnamewillbe derivedfromtheclassnameoryoucansetthenameproperty:@ X m l R o o t E l e m e n t ( n a m e = " y o u r N a m e " ) . OurresourceclasswillrespondtoG E T / p l a n e t with


1 2 3 4 5 6 < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " s t a n d a l o n e = " y e s " ? > < p l a n e t > < i d > 1 < / i d > < n a m e > E a r t h < / n a m e > < r a d i u s > 1 . 0 < / r a d i u s > < / p l a n e t >

whichmightbeexactlywhatwewant...ornot.Orwemightnotreallycare,becausewecanuseJAXRSclientformakingrequeststothisresourceandthisis easyas:
P l a n e t p l a n e t = w e b T a r g e t . p a t h ( " p l a n e t " ) . r e q u e s t ( M e d i a T y p e . A P P L I C A T I O N _ X M L _ T Y P E ) . g e t ( P l a n e t . c l a s s )

ThereisprecreatedW e b T a r g e t objectwhichpointstoourapplicationscontextrootandwesimplyaddpath(inourcaseitsp l a n e t ),acceptheader(not mandatory,butservicecouldprovidedifferentcontentbasedonthisheaderforexamplet e x t / h t m l canbeservedforwebbrowsers)andattheendwe specifythatweareexpectingP l a n e t classviaG E T request. TheremaybeneedfornotjustproducingXML,wemightwanttoconsumeitaswell.

Example8.34.MethodforconsumingPlanet
1 2 3 4 5 @ P O S T @ C o n s u m e s ( M e d i a T y p e . A P P L I C A T I O N _ X M L ) p u b l i c v o i d s e t P l a n e t ( P l a n e t p l a n e t ) { S y s t e m . o u t . p r i n t l n ( " s e t P l a n e t " + p l a n e t ) }

Aftervalidrequestismade,servicewillprintoutstringrepresentationofP l a n e t ,whichcanlooklikeP l a n e t { i d = 2 , n a m e = ' M a r s ' , r a d i u s = 1 . 5 1 } .With JAXRSclientyoucando:


w e b T a r g e t . p a t h ( " p l a n e t " ) . p o s t ( p l a n e t )

Ifthereisaneedforsomeother(nondefault)XMLrepresentation,otherJAXBannotationswouldneedtobeused.Thisprocessisusuallysimplifiedby generatingjavasourcefromXMLSchemawhichisdonebyx j c whichisXMLtojavacompileranditispartofJAXB.

8.2.3.POJOs
Sometimesyoucan't/don'twanttoaddJAXBannotationstosourcecodeandyoustillwanttohaveresourcesconsumingandproducingXMLrepresentation ofyourclasses.Inthiscase,JAXBElementclassshouldhelpyou.Let'sredoplanetresourcebutthistimewewon'thavean@XmlRootElementannotationon P l a n e t class. Example8.35.ResourceclassJAXBElement
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 @ P a t h ( " p l a n e t " ) p u b l i c c l a s s R e s o u r c e { @ G E T @ P r o d u c e s ( M e d i a T y p e . A P P L I C A T I O N _ X M L ) p u b l i c J A X B E l e m e n t < P l a n e t > g e t P l a n e t ( ) { P l a n e t p l a n e t = n e w P l a n e t ( ) p l a n e t . i d = 1 p l a n e t . n a m e = " E a r t h " p l a n e t . r a d i u s = 1 . 0 r e t u r n n e w J A X B E l e m e n t < P l a n e t > ( n e w Q N a m e ( " p l a n e t " ) , P l a n e t . c l a s s , p l a n e t ) } @ P O S T @ C o n s u m e s ( M e d i a T y p e . A P P L I C A T I O N _ X M L ) p u b l i c v o i d s e t P l a n e t ( J A X B E l e m e n t < P l a n e t > p l a n e t ) { S y s t e m . o u t . p r i n t l n ( " s e t P l a n e t " + p l a n e t . g e t V a l u e ( ) ) } }

Asyoucansee,everythingislittlemorecomplicatedwithJ A X B E l e m e n t .ThisisbecausenowyouneedtoexplicitlysetelementnameforP l a n e t classXML representation.Clientsideisevenmorecomplicatedthanserversidebecauseyoucan'tdoJ A X B E l e m e n t < P l a n e t > soJAXRSclientAPIprovideswayhow toworkarounditbydeclaringsubclassofG e n e r i c T y p e < T > . Example8.36.ClientsideJAXBElement
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 / / G E T G e n e r i c T y p e < J A X B E l e m e n t < P l a n e t > > p l a n e t T y p e = n e w G e n e r i c T y p e < J A X B E l e m e n t < P l a n e t > > ( ) { } P l a n e t p l a n e t = ( P l a n e t ) w e b T a r g e t . p a t h ( " p l a n e t " ) . r e q u e s t ( M e d i a T y p e . A P P L I C A T I O N _ X M L _ T Y P E ) . g e t ( p l a n e t T y p e ) . g e t V a l u e ( ) S y s t e m . o u t . p r i n t l n ( " # # # " + p l a n e t ) / / P O S T p l a n e t = n e w P l a n e t ( ) / / . . . w e b T a r g e t . p a t h ( " p l a n e t " ) . p o s t ( n e w J A X B E l e m e n t < P l a n e t > ( n e w Q N a m e ( " p l a n e t " ) , P l a n e t . c l a s s , p l a n e t ) )

8.2.4.UsingcustomJAXBContext
InsomescenariosyoucantakeadvantageofusingcustomJAXBContext.CreatingJ A X B C o n t e x t isanexpensiveoperationandifyoualreadyhaveone created,sameinstancecanbeusedbyJersey.OtherpossibleusecaseforthisiswhenyouneedtosetsomespecificthingstoJ A X B C o n t e x t ,forexampleto setadifferentclassloader. Example8.37.PlanetJAXBContextProvider
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 @ P r o v i d e r p u b l i c c l a s s P l a n e t J A X B C o n t e x t P r o v i d e r i m p l e m e n t s C o n t e x t R e s o l v e r < J A X B C o n t e x t > { p r i v a t e J A X B C o n t e x t c o n t e x t = n u l l p u b l i c J A X B C o n t e x t g e t C o n t e x t ( C l a s s < ? > t y p e ) { i f ( t y p e ! = P l a n e t . c l a s s ) { r e t u r n n u l l / / w e d o n ' t s u p p o r t n o t h i n g e l s e t h a n P l a n e t } i f ( c o n t e x t = = n u l l ) { t r y { c o n t e x t = J A X B C o n t e x t . n e w I n s t a n c e ( P l a n e t . c l a s s ) } c a t c h ( J A X B E x c e p t i o n e ) { / / l o g w a r n i n g / e r r o r n u l l w i l l b e r e t u r n e d w h i c h i n d i c a t e s t h a t t h i s / / p r o v i d e r w o n ' t / c a n ' t b e u s e d . } } r e t u r n c o n t e x t } }

SampleaboveshowssimpleJ A X B C o n t e x t creation,allyouneedtodoisputthis@ P r o v i d e r annotatedclasssomewherewhereJerseycanfindit.Users sometimeshaveproblemswithusingproviderclassesonclientside,sojusttoreminderyouhavetodeclarethemintheclientconfig(clientdoesnotdo anythinglikepackagescanningdonebyserver).

Example8.38.UsingProviderwithJAXRSclient
1 2 3 4 C l i e n t C o n f i g c o n f i g = n e w C l i e n t C o n f i g ( ) c o n f i g . r e g i s t e r ( P l a n e t J A X B C o n t e x t P r o v i d e r . c l a s s ) C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( c o n f i g )

8.2.5.MOXy
IfyouwanttouseMOXyasyourJAXBimplementationinsteadofJAXBRIyouhavetwooptions.YoucaneitherusethestandardJAXBmechanismstodefine theJ A X B C o n t e x t F a c t o r y fromwhichaJ A X B C o n t e x t instancewouldbeobtained(formoreonthistopic,readJavaDoconJAXBContext)oryoucanadd j e r s e y m e d i a m o x y moduletoyourprojectandregister/configureMoxyXmlFeatureclass/instanceintheConfigurable. Example8.39.Addj e r s e y m e d i a m o x y dependency.
1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . m e d i a < / g r o u p I d > < a r t i f a c t I d > j e r s e y m e d i a m o x y < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Example8.40.RegistertheM o x y X m l F e a t u r e class.
1 2 3 f i n a l R e s o u r c e C o n f i g c o n f i g = n e w R e s o u r c e C o n f i g ( ) . p a c k a g e s ( " o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . x m l m o x y " ) . r e g i s t e r ( M o x y X m l F e a t u r e . c l a s s )

Example8.41.ConfigureandregisteranM o x y X m l F e a t u r e instance.
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 / / C o n f i g u r e P r o p e r t i e s . f i n a l M a p < S t r i n g , O b j e c t > p r o p e r t i e s = n e w H a s h M a p < S t r i n g , O b j e c t > ( ) / / . . . / / O b t a i n a C l a s s L o a d e r y o u w a n t t o u s e . f i n a l C l a s s L o a d e r c l a s s L o a d e r = T h r e a d . c u r r e n t T h r e a d ( ) . g e t C o n t e x t C l a s s L o a d e r ( ) f i n a l R e s o u r c e C o n f i g c o n f i g = n e w R e s o u r c e C o n f i g ( ) . p a c k a g e s ( " o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . x m l m o x y " ) . r e g i s t e r ( n e w M o x y X m l F e a t u r e ( p r o p e r t i e s , c l a s s L o a d e r , t r u e , / / F l a g t o d e t e r m i n e w h e t h e r e c l i p s e l i n k o x m . x m l f i l e s h o u l d b e u s e d f o r l o o k u p . C u s t o m C l a s s A . c l a s s , C u s t o m C l a s s B . c l a s s / / C l a s s e s t o b e b o u n d . ) )

8.3.Multipart
8.3.1.Overview
Theclassesinthismoduleprovideanintegrationofm u l t i p a r t / * requestandresponsebodiesinaJAXRSruntimeenvironment.Thesetofregistered providersisleveraged,inthatthecontenttypeforabodypartofsuchamessagereusesthesameM e s s a g e B o d y R e a d e r < T > /M e s s a g e B o d y W r i t e r < T > implementationsaswouldbeusedforthatcontenttypeasastandaloneentity. ThefollowinglistofgeneralMIMEMultiPartfeaturesiscurrentlysupported: TheM I M E V e r s i o n : 1 . 0 HTTPheaderisincludedongeneratedresponses.Itisaccepted,butnotrequired,onprocessedrequests. AMessageBodyReader<T>implementationforconsumingMIMEMultiPartentities. AM e s s a g e B o d y W r i t e r < T > implementationforproducingMIMEMultiPartentities.Theappropriate@ P r o v i d e r isusedtoserializeeachbodypart, basedonitsmediatype. Optionalcreationofanappropriateb o u n d a r y parameteronageneratedC o n t e n t T y p e header,ifnotalreadypresent. FormoreinformationrefertoMultiPart.

8.3.1.1.Dependency
Tousemultipartfeaturesyouneedtoaddj e r s e y m e d i a m u l t i p a r t moduletoyourp o m . x m l file:
1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . m e d i a < / g r o u p I d > < a r t i f a c t I d > j e r s e y m e d i a m u l t i p a r t < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Ifyou'renotusingMavenmakesuretohaveallneededdependencies(seejerseymediamultipart)ontheclasspath.

8.3.1.2.Registration
Beforeyoucanusecapabilitiesofthej e r s e y m e d i a m u l t i p a r t moduleinyourclient/servercode,youneedtoregisterMultiPartFeature. Example8.42.BuildingclientwithMultiPartfeatureenabled.
1 2 3 f i n a l C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . r e g i s t e r ( M u l t i P a r t F e a t u r e . c l a s s ) . b u i l d ( )

Example8.43.CreatingJAXRSapplicationwithMultiPartfeatureenabled.
1 2 3 / / C r e a t e J A X R S a p p l i c a t i o n . f i n a l A p p l i c a t i o n a p p l i c a t i o n = n e w R e s o u r c e C o n f i g ( ) . p a c k a g e s ( " o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . m u l t i p a r t " )

. r e g i s t e r ( M u l t i P a r t F e a t u r e . c l a s s )

8.3.1.3.Examples
Jerseyprovidesanmultipartwebappexampleonhowtousemultipartfeatures.

8.3.2.Client
MultiPartclass(orit'ssubclasses)canbeusedasanentrypointtousingj e r s e y m e d i a m u l t i p a r t moduleontheclientside.ThisclassrepresentsaMIME multipartmessageandisabletoholdanarbitrarynumberofBodyParts.Defaultmediatypeismultipart/mixedforM u l t i P a r t entityandt e x t / p l a i n for B o d y P a r t . Example8.44.M u l t i P a r t entity
1 2 3 4 5 6 7 8 9 f i n a l M u l t i P a r t m u l t i P a r t E n t i t y = n e w M u l t i P a r t ( ) . b o d y P a r t ( n e w B o d y P a r t ( ) . e n t i t y ( " h e l l o " ) ) . b o d y P a r t ( n e w B o d y P a r t ( n e w J a x b B e a n ( " x m l " ) , M e d i a T y p e . A P P L I C A T I O N _ X M L _ T Y P E ) ) . b o d y P a r t ( n e w B o d y P a r t ( n e w J a x b B e a n ( " j s o n " ) , M e d i a T y p e . A P P L I C A T I O N _ J S O N _ T Y P E ) ) f i n a l W e b T a r g e t t a r g e t = / / C r e a t e W e b T a r g e t . f i n a l R e s p o n s e r e s p o n s e = t a r g e t . r e q u e s t ( ) . p o s t ( E n t i t y . e n t i t y ( m u l t i P a r t E n t i t y , m u l t i P a r t E n t i t y . g e t M e d i a T y p e ( ) ) )

Ifyousendam u l t i P a r t E n t i t y totheservertheentitywithC o n t e n t T y p e headerinHTTPmessagewouldlooklike(don'tforgettoregisteraJSON provider): Example8.45.M u l t i P a r t entityinHTTPmessage.


C o n t e n t T y p e : m u l t i p a r t / m i x e d b o u n d a r y = B o u n d a r y _ 1 _ 8 2 9 0 7 7 7 7 6 _ 1 3 6 9 1 2 8 1 1 9 8 7 8 B o u n d a r y _ 1 _ 8 2 9 0 7 7 7 7 6 _ 1 3 6 9 1 2 8 1 1 9 8 7 8 C o n t e n t T y p e : t e x t / p l a i n h e l l o B o u n d a r y _ 1 _ 8 2 9 0 7 7 7 7 6 _ 1 3 6 9 1 2 8 1 1 9 8 7 8 C o n t e n t T y p e : a p p l i c a t i o n / x m l < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " s t a n d a l o n e = " y e s " ? > < j a x b B e a n > < v a l u e > x m l < / v a l u e > < / j a x b B e a n > B o u n d a r y _ 1 _ 8 2 9 0 7 7 7 7 6 _ 1 3 6 9 1 2 8 1 1 9 8 7 8 C o n t e n t T y p e : a p p l i c a t i o n / j s o n { " v a l u e " : " j s o n " } B o u n d a r y _ 1 _ 8 2 9 0 7 7 7 7 6 _ 1 3 6 9 1 2 8 1 1 9 8 7 8

Whenworkingwithforms(e.g.mediatypem u l t i p a r t / f o r m d a t a )andvariousfieldsinthem,thereisamoreconvenientclasstobeused FormDataMultiPart.ItautomaticallysetsthemediatypefortheF o r m D a t a M u l t i P a r t entitytom u l t i p a r t / f o r m d a t a andC o n t e n t D i s p o s i t i o n headerto F o r m D a t a B o d y P a r t bodyparts. Example8.46.F o r m D a t a M u l t i P a r t entity


1 2 3 4 5 6 7 f i n a l F o r m D a t a M u l t i P a r t m u l t i p a r t = n e w F o r m D a t a M u l t i P a r t ( ) . f i e l d ( " h e l l o " , " h e l l o " ) . f i e l d ( " x m l " , n e w J a x b B e a n ( " x m l " ) ) . f i e l d ( " j s o n " , n e w J a x b B e a n ( " j s o n " ) , M e d i a T y p e . A P P L I C A T I O N _ J S O N _ T Y P E ) f i n a l W e b T a r g e t t a r g e t = / / C r e a t e W e b T a r g e t . f i n a l R e s p o n s e r e s p o n s e = t a r g e t . r e q u e s t ( ) . p o s t ( E n t i t y . e n t i t y ( m u l t i p a r t , m u l t i p a r t . g e t M e d i a T y p e ( ) ) )

ToillustratethedifferencewhenusingF o r m D a t a M u l t i P a r t insteadofF o r m D a t a B o d y P a r t youcantakealookattheF o r m D a t a M u l t i P a r t entityfromHTML message: Example8.47.F o r m D a t a M u l t i P a r t entityinHTTPmessage.


C o n t e n t T y p e : m u l t i p a r t / f o r m d a t a b o u n d a r y = B o u n d a r y _ 1 _ 5 1 1 2 6 2 2 6 1 _ 1 3 6 9 1 4 3 4 3 3 6 0 8 B o u n d a r y _ 1 _ 5 1 1 2 6 2 2 6 1 _ 1 3 6 9 1 4 3 4 3 3 6 0 8 C o n t e n t T y p e : t e x t / p l a i n C o n t e n t D i s p o s i t i o n : f o r m d a t a n a m e = " h e l l o " h e l l o B o u n d a r y _ 1 _ 5 1 1 2 6 2 2 6 1 _ 1 3 6 9 1 4 3 4 3 3 6 0 8 C o n t e n t T y p e : a p p l i c a t i o n / x m l C o n t e n t D i s p o s i t i o n : f o r m d a t a n a m e = " x m l " < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " s t a n d a l o n e = " y e s " ? > < j a x b B e a n > < v a l u e > x m l < / v a l u e > < / j a x b B e a n > B o u n d a r y _ 1 _ 5 1 1 2 6 2 2 6 1 _ 1 3 6 9 1 4 3 4 3 3 6 0 8 C o n t e n t T y p e : a p p l i c a t i o n / j s o n C o n t e n t D i s p o s i t i o n : f o r m d a t a n a m e = " j s o n " { " v a l u e " : " j s o n " } B o u n d a r y _ 1 _ 5 1 1 2 6 2 2 6 1 _ 1 3 6 9 1 4 3 4 3 3 6 0 8

Acommonusecaseformanyusersissendingfilesfromclienttoserver.Forthispurposeyoucanuseclassesfrom o r g . g l a s s f i s h . j e r s e y . j e r s e y . m e d i a . m u l t i p a r t package,suchasFileDataBodyPartorStreamDataBodyPart. Example8.48.Multipartsendingfiles.


1 2 3 4 5 6 / / M e d i a T y p e o f t h e b o d y p a r t w i l l b e d e r i v e d f r o m t h e f i l e . f i n a l F i l e D a t a B o d y P a r t f i l e P a r t = n e w F i l e D a t a B o d y P a r t ( " m y _ p o m " , n e w F i l e ( " p o m . x m l " ) ) f i n a l F o r m D a t a M u l t i P a r t m u l t i p a r t = n e w F o r m D a t a M u l t i P a r t ( ) . f i e l d ( " f o o " , " b a r " ) . b o d y P a r t ( f i l e P a r t )

7 8 9 1 0

f i n a l W e b T a r g e t t a r g e t = / / C r e a t e W e b T a r g e t . f i n a l R e s p o n s e r e s p o n s e = t a r g e t . r e q u e s t ( ) . p o s t ( E n t i t y . e n t i t y ( m u l t i p a r t , m u l t i p a r t . g e t M e d i a T y p e ( ) ) )

8.3.3.Server
Returningamultipartresponsefromservertoclientisnotmuchdifferentfromthepartsdescribedintheclientsectionabove.Toobtainamultipartentity,sent byaclient,intheapplicationyoucanusetwoapproaches: InjectingthewholeMultiPartentity. Injectingparticularpartsofaf o r m d a t a multipartrequestvia@FormDataParamannotation.

8.3.3.1.InjectingandreturningtheM u l t i P a r t entity
WorkingwithM u l t i P a r t typesisnodifferentfrominjecting/returningotherentitytypes.JerseyprovidesM e s s a g e B o d y R e a d e r < T > forreadingtherequest entityandinjectingthisentityintoamethodparameterofaresourcemethodandM e s s a g e B o d y W r i t e r < T > forwritingoutputentities.Youcanexpectthat eitherM u l t i P a r t orF o r m D a t a M u l t i P a r t (m u l t i p a r t / f o r m d a t a mediatype)objecttobeinjectedintoaresourcemethod. Example8.49.ResourcemethodusingM u l t i P a r t asinputparameter/returnvalue.
1 2 3 4 5 @ P O S T @ P r o d u c e s ( " m u l t i p a r t / m i x e d " ) p u b l i c M u l t i P a r t p o s t ( f i n a l F o r m D a t a M u l t i P a r t m u l t i P a r t ) { r e t u r n m u l t i P a r t }

8.3.3.2.Injectingwith@ F o r m D a t a P a r a m
Ifyoujustneedtobinthenamedbodypart(s)ofam u l t i p a r t / f o r m d a t a requestentitybodytoaresourcemethodparameteryoucanuse @FormDataParamannotation. Thisannotationinconjunctionwiththemediatypem u l t i p a r t / f o r m d a t a shouldbeusedforsubmittingandconsumingformsthatcontainfiles,nonASCII data,andbinarydata. Thetypeoftheannotatedparametercanbeoneofthefollowing(formoredetaileddescriptionseejavadocto@FormDataParam):
F o r m D a t a B o d y P a r t Thevalueoftheparameterwillbethefirstnamedbodypartorn u l l ifsuchanamedbodypartisnotpresent.

AL i s t orC o l l e c t i o n ofF o r m D a t a B o d y P a r t .Thevalueoftheparameterwilloneormorenamedbodypartswiththesamenameorn u l l ifsucha namedbodypartisnotpresent.


F o r m D a t a C o n t e n t D i s p o s i t i o n Thevalueoftheparameterwillbethecontentdispositionofthefirstnamedbodypartpartorn u l l ifsuchanamed

bodypartisnotpresent. AL i s t orC o l l e c t i o n ofF o r m D a t a C o n t e n t D i s p o s i t i o n .Thevalueoftheparameterwilloneormorecontentdispositionsofthenamedbodyparts withthesamenameorn u l l ifsuchanamedbodypartisnotpresent. Atypeforwhichamessagebodyreaderisavailablegiventhemediatypeofthefirstnamedbodypart.Thevalueoftheparameterwillbetheresultof readingusingthemessagebodyreadergiventhetypeT ,themediatypeofthenamedpart,andthebytesofthenamedbodypartasinput. Ifthereisnonamedpartpresentandthereisadefaultvaluepresentasdeclaredby@DefaultValuethenthemediatypewillbesettot e x t / p l a i n . ThevalueoftheparameterwillbetheresultofreadingusingthemessagebodyreadergiventhetypeT ,themediatypet e x t / p l a i n ,andtheUTF8 encodedbytesofthedefaultvalueasinput. IfthereisnomessagebodyreaderavailableandthetypeT conformstoatypespecifiedby@FormParamthenprocessingisperformedasspecifiedby @ F o r m P a r a m ,wherethevaluesoftheformparameterareS t r i n g instancesproducedbyreadingthebytesofthenamedbodypartsutilizinga messagebodyreaderfortheS t r i n g typeandthemediatypet e x t / p l a i n . Ifthereisnonamedpartpresentthenprocessingisperformedasspecifiedby@ F o r m P a r a m . Example8.50.Useof@ F o r m D a t a P a r a m annotation
1 2 3 4 5 6 7 8 9 1 0 @ P O S T @ C o n s u m e s ( M e d i a T y p e . M U L T I P A R T _ F O R M _ D A T A _ T Y P E ) p u b l i c S t r i n g p o s t F o r m ( @ D e f a u l t V a l u e ( " t r u e " ) @ F o r m D a t a P a r a m ( " e n a b l e d " ) b o o l e a n e n a b l e d , @ F o r m D a t a P a r a m ( " d a t a " ) F i l e D a t a b e a n , @ F o r m D a t a P a r a m ( " f i l e " ) I n p u t S t r e a m f i l e , @ F o r m D a t a P a r a m ( " f i l e " ) F o r m D a t a C o n t e n t D i s p o s i t i o n f i l e D i s p o s i t i o n ) { / / . . . }

Intheexampleabovetheserverconsumesam u l t i p a r t / f o r m d a t a requestentitybodythatcontainsoneoptionalnamedbodyparte n a b l e d andtwo requirednamedbodypartsd a t a andf i l e . Theoptionalparte n a b l e d isprocessedasab o o l e a n value,ifthepartisabsentthenthevaluewillbet r u e . Thepartd a t a isprocessedasaJAXBbeanandcontainssomemetadataaboutthefollowingpart. Thepartf i l e isafilethatisuploaded,thisisprocessedasanI n p u t S t r e a m .AdditionalinformationaboutthefilefromtheC o n t e n t D i s p o s i t i o n header canbeaccessedbytheparameterf i l e D i s p o s i t i o n .

Tip
@ F o r m D a t a P a r a m annotationcanbealsousedonfields.

Chapter9.FiltersandInterceptors
TableofContents 9.1.Introduction 9.2.Filters

9.2.1.Serverfilters 9.2.2.Clientfillers 9.3.Interceptors 9.4.Filterandinterceptorexecutionorder 9.5.Namebinding 9.6.Dynamicbinding 9.7.Priorities

9.1.Introduction
Thischapterdescribesfilters,interceptorsandtheirconfiguration.Filtersandinterceptorscanbeusedonbothsides,ontheclientandtheserverside.Filters canmodifyinboundandoutboundrequestsandresponsesincludingmodificationofheaders,entityandotherrequest/responseparameters.Interceptorsare usedprimarilyformodificationofentityinputandoutputstreams.Youcanuseinterceptorsforexampletozipandunzipoutputandinputentitystreams.

9.2.Filters
Filterscanbeusedwhenyouwanttomodifyanyrequestorresponseparameterslikeheaders.Forexampleyouwouldliketoaddaresponseheader"X PoweredBy"toeachgeneratedresponse.Insteadofaddingthisheaderineachresourcemethodyouwouldusearesponsefiltertoaddthisheader. Therearefiltersontheserversideandtheclientside. Serverfilters:
ContainerRequestFilter ContainerResponseFilter

Clientfilters:
ClientResponseFilter ClientResponseFilter

9.2.1.Serverfilters
Thefollowingexampleshowsasimplecontainerresponsefilteraddingaheadertoeachresponse. Example9.1.Containerresponsefilter
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 i m p o r t j a v a . i o . I O E x c e p t i o n i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e q u e s t C o n t e x t i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e s p o n s e C o n t e x t i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e s p o n s e F i l t e r i m p o r t j a v a x . w s . r s . c o r e . R e s p o n s e p u b l i c c l a s s P o w e r e d B y R e s p o n s e F i l t e r i m p l e m e n t s C o n t a i n e r R e s p o n s e F i l t e r { @ O v e r r i d e p u b l i c v o i d f i l t e r ( C o n t a i n e r R e q u e s t C o n t e x t r e q u e s t C o n t e x t , C o n t a i n e r R e s p o n s e C o n t e x t r e s p o n s e C o n t e x t ) t h r o w s I O E x c e p t i o n { r e s p o n s e C o n t e x t . g e t H e a d e r s ( ) . a d d ( " X P o w e r e d B y " , " J e r s e y : ) " ) } }

IntheexampleabovetheP o w e r e d B y R e s p o n s e F i l t e r alwaysaddsaheader"XPoweredBy"totheresponse.Thefiltermustinheritfromthe ContainerResponseFilterandmustberegisteredasaprovider.Thefilterwillbeexecutedforeveryresponsewhichisinmostcasesaftertheresource methodisexecuted.Responsefiltersareexecutedeveniftheresourcemethodisnotrun,forexamplewhentheresourcemethodisnotfoundand404"Not found"responsecodeisreturnedbytheJerseyruntime.Inthiscasethefilterwillbeexecutedandwillprocessthe404response. Thef i l t e r ( ) methodhastwoarguments,thecontainerrequestandcontainerresponse.TheContainerRequestContextisaccessibleonlyforreadonly purposesasthefilterisexecutedalreadyinresponsephase.ThemodificationscanbedoneintheContainerResponseContext. Thefollowingexampleshowstheusageofarequestfilter. Example9.2.Containerrequestfilter
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 i m p o r t j a v a . i o . I O E x c e p t i o n i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e q u e s t C o n t e x t i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e q u e s t F i l t e r i m p o r t j a v a x . w s . r s . c o r e . R e s p o n s e i m p o r t j a v a x . w s . r s . c o r e . S e c u r i t y C o n t e x t p u b l i c c l a s s A u t h o r i z a t i o n R e q u e s t F i l t e r i m p l e m e n t s C o n t a i n e r R e q u e s t F i l t e r { @ O v e r r i d e p u b l i c v o i d f i l t e r ( C o n t a i n e r R e q u e s t C o n t e x t r e q u e s t C o n t e x t ) t h r o w s I O E x c e p t i o n { f i n a l S e c u r i t y C o n t e x t s e c u r i t y C o n t e x t = r e q u e s t C o n t e x t . g e t S e c u r i t y C o n t e x t ( ) i f ( s e c u r i t y C o n t e x t = = n u l l | | ! s e c u r i t y C o n t e x t . i s U s e r I n R o l e ( " p r i v i l e g e d " ) ) { r e q u e s t C o n t e x t . a b o r t W i t h ( R e s p o n s e . s t a t u s ( R e s p o n s e . S t a t u s . U N A U T H O R I Z E D ) . e n t i t y ( " U s e r c a n n o t a c c e s s t h e r e s o u r c e . " ) . b u i l d ( ) ) } } }

TherequestfilterissimilartotheresponsefilterbutdoesnothaveaccesstotheContainerResponseContextasnoresponseisaccessibleyet.Responsefilter inheritsfromClientResponseFilter.Requestfilterisexecutedbeforetheresourcemethodisrunandbeforetheresponseiscreated.Thefilterhaspossibility tomanipulatetherequestparametersincludingrequestheadersorentity. TheA u t h o r i z a t i o n R e q u e s t F i l t e r intheexamplecheckswhethertheauthenticateduserisintheprivilegedrole.Ifitisnotthentherequestisabortedby callingC o n t a i n e r R e q u e s t C o n t e x t . a b o r t W i t h ( R e s p o n s e r e s p o n s e ) method.Themethodisintendedtobecalledfromtherequestfilterinsituationwhen therequestshouldnotbeprocessedfurtherinthestandardprocessingchain.Whenthef i l t e r methodisfinishedtheresponsepassedasaparameterto thea b o r t W i t h methodisusedtorespondtotherequest.Responsefilters,ifanyareregistered,willbeexecutedandwillhavepossibilitytoprocessthe abortedresponse.

9.2.1.1.Prematchingandpostmatchingfilters
Alltherequestfiltersshownabovewasimplementedaspostmatchingfilters.Itmeansthatthefilterswouldbeappliedonlyafterasuitableresourcemethod hasbeenselectedtoprocesstheactualrequesti.e.afterrequestmatchinghappens.Requestmatchingistheprocessoffindingaresourcemethodthat shouldbeexecutedbasedontherequestpathandotherrequestparameters.Sincepostmatchingrequestfiltersareinvokedwhenaparticularresource methodhasalreadybeenselected,suchfilterscannotinfluencetheresouremethodmatchingprocess. Toovercometheabovedescribedlimitation,thereisapossibilitytomarkaserverrequestfilterasaprematchingfilter,i.e.toannotatethefilterclasswiththe @PreMatchingannotation.Prematchingfiltersarerequestfiltersthatareexecutedbeforetherequestmatchingisstarted.Thankstothis,prematching requestfiltershavethepossibilitytoinfluencewhichmethodwillbematched.Suchaprematchingrequestfilterexampleisshownhere: Example9.3.Prematchingrequestfilter
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 . . . i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e q u e s t C o n t e x t i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e q u e s t F i l t e r i m p o r t j a v a x . w s . r s . c o n t a i n e r . P r e M a t c h i n g . . . @ P r e M a t c h i n g p u b l i c c l a s s P r e M a t c h i n g F i l t e r i m p l e m e n t s C o n t a i n e r R e q u e s t F i l t e r { @ O v e r r i d e p u b l i c v o i d f i l t e r ( C o n t a i n e r R e q u e s t C o n t e x t r e q u e s t C o n t e x t ) t h r o w s I O E x c e p t i o n { / / c h a n g e a l l P U T m e t h o d s t o P O S T i f ( r e q u e s t C o n t e x t . g e t M e t h o d ( ) . e q u a l s ( " P U T " ) ) { r e q u e s t C o n t e x t . s e t M e t h o d ( " P O S T " ) } } }

TheP r e M a t c h i n g F i l t e r isasimpleprematchingfilterwhichchangesallPUTHTTPmethodstoPOST.Thismightbeusefulwhenyouwanttoalways handlethesePUTandPOSTHTTPmethodswiththesameJavacode.AftertheP r e M a t c h i n g F i l t e r hasbeeninvoked,therestoftherequestprocessing willbehaveasifthePOSTHTTPmethodwasoriginallyused.Youcannotdothisinpostmatchingfilters(standardfilterswithout@ P r e M a t c h i n g annotation) astheresourcemethodisalreadymatched(selected).AnattempttotweaktheoriginalHTTPmethodinapostmatchingfilterwouldcausean I l l e g a l A r g u m e n t E x c e p t i o n . Aswrittenabove,prematchingfilterscanfullyinfluencetherequestmatchingprocess,whichmeansyoucanevenmodifyrequestURIinaprematchingfilter byinvokingthes e t R e q u e s t U r i ( U R I ) methodofC o n t a i n e r R e q u e s t F i l t e r sothatadifferentresourcewouldbematched. Likeinpostmatchingfiltersyoucanabortaresponseinprematchingfilterstoo.

9.2.2.Clientfillers
Clientfiltersaresimilartocontainerfilters.TheresponsecanalsobeabortedintheClientRequestFilterwhichwouldcausethatnorequestwillactuallybesent totheserveratall.Anewresponseispassedtothea b o r t method.Thisresponsewillbeusedanddeliveredasaresultoftherequestinvocation.Sucha responsegoesthroughtheclientresponsefilters.Thisissimilartowhathappensontheserverside.Theprocessisshowninthefollowingexample: Example9.4.Clientrequestfilter
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 p u b l i c c l a s s C h e c k R e q u e s t F i l t e r i m p l e m e n t s C l i e n t R e q u e s t F i l t e r { @ O v e r r i d e p u b l i c v o i d f i l t e r ( C l i e n t R e q u e s t C o n t e x t r e q u e s t C o n t e x t ) t h r o w s I O E x c e p t i o n { i f ( r e q u e s t C o n t e x t . g e t H e a d e r s ( ) . g e t ( " C l i e n t N a m e " ) = = n u l l ) { r e q u e s t C o n t e x t . a b o r t W i t h ( R e s p o n s e . s t a t u s ( R e s p o n s e . S t a t u s . B A D _ R E Q U E S T ) . e n t i t y ( " C l i e n t N a m e h e a d e r m u s t b e d e f i n e d . " ) . b u i l d ( ) ) } } }

TheC h e c k R e q u e s t F i l t e r validatestheoutgoingrequest.ItischeckedforpresenceofaC l i e n t N a m e header.Iftheheaderisnotpresenttherequestwill beabortedwithamadeupresponsewithanappropriatecodeandmessageintheentitybody.Thiswillcausethattheoriginalrequestwillnotbeeffectivelly senttotheserverbuttheactualinvocationwillstillendupwitharesponseasifitwouldbegeneratedbytheserverside.Iftherewouldbeanyclientresponse filteritwouldbeexecutedonthisresponse. Tosummarizetheworkflow,foranyclientrequestinvokedfromtheclientAPItheclientrequestfilters(ClientRequestFilter)areexecutedthatcould manipulatetherequest.Ifnotaborted,theoutcomingrequestisthenphysicallysentovertotheserversideandoncearesponseisreceivedbackfromthe servertheclientresponsefilters(ClientResponseFilter)areexecutedthatmightagainmanipulatethereturnedresponse.Finallytheresponseispassedback tothecodethatinvokedtherequest.Iftherequestwasabortedinanyclientrequestfilterthentheclient/servercommunicationisskippedandtheaborted responseisusedintheresponsefilters.

9.3.Interceptors
InterceptorsshareacommonAPIfortheserverandtheclientside.Whereasfiltersareprimarilyintendedtomanipulaterequestandresponseparameters likeHTTPheaders,URIsand/orHTTPmethods,interceptorsareintendedtomanipulateentities,viamanipulatingentityinput/outputstreams.Ifyoufor exampleneedtoencodeentitybodyofaclientrequestthenyoucouldimplementaninterceptortodotheworkforyou. Therearetwokindsofinterceptors,ReaderInterceptorandWriterInterceptor.Readerinterceptorsareusedtomanipulateinboundentitystreams.Theseare thestreamscomingfromthe"wire".So,usingareaderinterceptoryoucanmanipulaterequestentitystreamontheserverside(whereanentityisreadfrom theclientrequest)andresponseentitystreamontheclientside(whereanentityisreadfromtheserverresponse).Writerinterceptorsareusedforcases whereentityiswrittentothe"wire"whichontheservermeanswhenwritingoutaresponseentityandontheclientsidewhenwritingrequestentityfora requesttobesentouttotheserver.Writerandreaderinterceptorsareexecutedbeforemessagebodyreadersorwritersareexecutedandtheirprimary intentionistowraptheentitystreamsthatwillbeusedinmessagebodyreaderandwriters. ThefollowingexampleshowsawriterinterceptorthatenablesGZIPcompressionofthewholeentitybody. Example9.5.GZIPwriterinterceptor
1 2 3 4 5 p u b l i c c l a s s G Z I P W r i t e r I n t e r c e p t o r i m p l e m e n t s W r i t e r I n t e r c e p t o r { @ O v e r r i d e p u b l i c v o i d a r o u n d W r i t e T o ( W r i t e r I n t e r c e p t o r C o n t e x t c o n t e x t ) t h r o w s I O E x c e p t i o n , W e b A p p l i c a t i o n E x c e p t i o n {

6 7 8 9 1 0

f i n a l O u t p u t S t r e a m o u t p u t S t r e a m = c o n t e x t . g e t O u t p u t S t r e a m ( ) c o n t e x t . s e t O u t p u t S t r e a m ( n e w G Z I P O u t p u t S t r e a m ( o u t p u t S t r e a m ) ) c o n t e x t . p r o c e e d ( ) } }

TheinterceptorgetsaoutputstreamfromtheWriterInterceptorContextandsetsanewonewhichisaGZIPwrapperoftheoriginaloutputstream.Afterall interceptorsareexecutedtheoutputstreamlastlysettotheW r i t e r I n t e r c e p t o r C o n t e x t willbeusedforserializationoftheentity.Intheexampleabovethe entitybyteswillbewrittentotheGZIPOutputStreamwhichwillcompressthestreamdataandwritethemtotheoriginaloutputstream.Theoriginalstreamis alwaysthestreamwhichwritesthedatatothe"wire".Whentheinterceptorisusedontheserver,theoriginaloutputstreamisthestreamintowhichwrites datatotheunderlyingservercontainerstreamthatsendstheresponsetotheclient. Theinterceptorswrapthestreamsandtheyitselfworkaswrappers.Thismeansthateachinterceptorisawrapperofanotherinterceptoranditis responsibilityofeachinterceptorimplementationtocallthewrappedinterceptor.Thisisachievedbycallingthep r o c e e d ( ) methodonthe W r i t e r I n t e r c e p t o r C o n t e x t .Thismethodwillcallthenextregisteredinterceptorinthechain,soeffectivellythiswillcallallremainingregistered interceptors.Callingp r o c e e d ( ) fromthelastinterceptorinthechainwillcalltheappropriatemessagebodyreader.Thereforeeveryinterceptormustcallthe p r o c e e d ( ) methodotherwisetheentitywouldnotbewritten.Thewrappingprincipleisreflectedalsointhemethodname,aroundWriteTo,whichsaysthatthe methodiswrappingthewritingoftheentity. ThemethodaroundWriteTo()getsW r i t e r I n t e r c e p t o r C o n t e x t asaparameter.Thiscontextcontainsgettersandsettersforheaderparameters,request properties,entity,entitystreamandotherproperties.ThesearethepropertieswhichwillbepassedtothefinalM e s s a g e B o d y W r i t e r < T > .Interceptorsare allowedtomodifyalltheseproperties.ThiscouldinfluencewritingofanentitybyM e s s a g e B o d y W r i t e r < T > andevenselectionofsuchawriter.Bychanging mediatype(W r i t e r I n t e r c e p t o r C o n t e x t .setMediaType())theinterceptorcancausethatdifferentmessagebodywriterwillbechosen.Theinterceptorcan alsocompletelyreplacetheentityifitisneeded.However,formodificationofheaders,requestpropertiesandsuch,thefiltersareusuallymorepreferable choice.Interceptorsareexecutedonlywhenthereisanyentityandwhentheentityistobewritten.So,whenyoualwayswanttoaddanewheadertoa responsenomatterwhat,usefiltersasinterceptorsmightnotbeexecutedwhennoentityispresent.Interceptorsshouldmodifypropertiesonlyforentity serializationanddeserializationpurposes. Let'snowlookatanexampleofaW r i t e r I n t e r c e p t o r Example9.6.GZIPreaderinterceptor
1 2 3 4 5 6 7 8 9 1 0 p u b l i c c l a s s G Z I P R e a d e r I n t e r c e p t o r i m p l e m e n t s R e a d e r I n t e r c e p t o r { @ O v e r r i d e p u b l i c O b j e c t a r o u n d R e a d F r o m ( R e a d e r I n t e r c e p t o r C o n t e x t c o n t e x t ) t h r o w s I O E x c e p t i o n , W e b A p p l i c a t i o n E x c e p t i o n { f i n a l I n p u t S t r e a m o r i g i n a l I n p u t S t r e a m = c o n t e x t . g e t I n p u t S t r e a m ( ) c o n t e x t . s e t I n p u t S t r e a m ( n e w G Z I P I n p u t S t r e a m ( o r i g i n a l I n p u t S t r e a m ) ) r e t u r n c o n t e x t . p r o c e e d ( ) } }

TheG Z I P R e a d e r I n t e r c e p t o r wrapstheoriginalinputstreamwiththeG Z I P I n p u t S t r e a m .Allfurtherreadsfromtheentitystreamwillcausethatdatawillbe decompressedbythisstream.Theinterceptormethoda r o u n d R e a d F r o m ( ) mustreturnanentity.Theentityisreturnedfromthep r o c e e d methodofthe ReaderInterceptorContext.Thep r o c e e d methodinternallycallsthewrappedinterceptorwhichmustalsoreturnanentity.Thep r o c e e d methodinvokedfrom thelastinterceptorinthechaincallsmessagebodyreaderwhichdeserializestheentityendreturnsit.Everyinterceptorcanchangethisentityifthereisa needbutinthemostcasesinterceptorswilljustreturntheentityasreturnedfromthep r o c e e d method. Asalreadymentionedabove,interceptorsshouldbeprimarilyusedtomanipulateentitybody.SimilartomethodsexposedbyW r i t e r I n t e r c e p t o r C o n t e x t theR e a d e r I n t e r c e p t o r C o n t e x t introducesasetofmethodsformodificationofrequest/responsepropertieslikeHTTPheaders,URIsand/orHTTP methods(excludinggettersandsettersforentityasentityhasnotbeenreadyet).AgainthesamerulesasforW r i t e r I n t e r c e p t o r appliesforchanging theseproperties(changeonlypropertiesinordertoinfluencereadingofanentity).

9.4.Filterandinterceptorexecutionorder
Let'slookcloseratthecontextofexecutionoffiltersandinterceptors.ThefollowingstepsdescribesscenariowhereaJAXRSclientmakesaPOSTrequestto theserver.Theserverreceivesanentityandsendsaresponsebackwiththesameentity.GZIPreaderandwriterinterceptorsareregisteredontheclientand theserver.Alsofiltersareregisteredonclientandserverwhichchangetheheadersofrequestandresponse. 1. Clientrequestinvoked:ThePOSTrequestwithattachedentityisbuiltontheclientandinvoked. 2. ClientRequestFilters:clientrequestfiltersareexecutedontheclientandtheymanipulatetherequestheaders. 3. ClientW r i t e r I n t e r c e p t o r :Astherequestcontainsanentity,writerinterceptorregisteredontheclientisexecutedbeforeaMessageBodyWriteris executed.ItwrapstheentityoutputstreamwiththeGZipOutputStream. 4. ClientMessageBodyWriter:messagebodywriterisexecutedontheclientwhichserializestheentityintothenewGZipOutputstream.Thisstreamzips thedataandsendsittothe"wire". 5. Server:serverreceivesarequest.Dataofentityiscompressedwhichmeansthatpurereadfromtheentityinputstreamwouldreturncompresseddata. 6. ServerprematchingContainerRequestFilters:ContainerRequestFiltersareexecutedthatcanmanipulateresourcemethodmatchingprocess. 7. Server:matching:resourcemethodmatchingisdone. 8. Server:postmatchingContainerRequestFilters:ContainerRequestFilterspostmatchingfiltersareexecuted.Thisincludeexecutionofallglobalfilters (withoutnamebinding)andfiltersnameboundtothematchedmethod. 9. ServerR e a d e r I n t e r c e p t o r :readerinterceptorsareexecutedontheserver.TheGZIPReaderInterceptorwrapstheinputstream(thestreamfromthe "wire")intotheGZipInputStreamandsetittocontext. 10. ServerMessageBodyReader:servermessagebodyreaderisexecutedanditdeserializestheentityfromnewGZipInputStream(getfromthecontext). Thismeansthereaderwillreadunzippeddataandnotthecompresseddatafromthe"wire". 11. Serverresourcemethodisexecuted:thedeserializedentityobjectispassedtothematchedresourcemethodasaparameter.Themethodreturnsthis entityasaresponseentity. 12. ServerContainerResponseFiltersareexecuted:responsefiltersareexecutedontheserverandtheymanipulatetheresponseheaders.Thisincludeall globalboundfilters(withoutnamebinding)andallfiltersnameboundtotheresourcemethod. 13. ServerW r i t e r I n t e r c e p t o r :isexecutedontheserver.ItwrapstheoriginaloutputstreamwithanewGZIPOuptutStream.Theoriginalstreamisthe streamthat"goestothewire"(outputstreamforresponsefromtheunderlyingservercontainer). 14. ServerMessageBodyWriter:messagebodywriterisexecutedontheserverwhichserializestheentityintotheGZIPOutputStream.Thisstream compressesthedataandwritesittotheoriginalstreamwhichsendsthiscompresseddatabacktotheclient. 15. Clientreceivestheresponse:theresponsecontainscompressedentitydata. 16. ClientClientResponseFilters:clientresponsefiltersareexecutedandtheymanipulatetheresponseheaders. 17. Clientresponseisreturned:thejavax.ws.rs.core.Responseisreturnedfromtherequestinvocation. 18. Clientcodecallsresponse.readEntity():readentityisexecutedontheclienttoextracttheentityfromtheresponse. 19. ClientR e a d e r I n t e r c e p t o r :theclientreaderinterceptorisexecutedwhenreadEntity(Class)iscalled.Theinterceptorwrapstheentityinputstream withGZIPInputStream.Thiswilldecompressthedatafromtheoriginalinputstream. 20. ClientMessageBodyReaders:clientmessagebodyreaderisinvokedwhichreadsdecompresseddatafromGZIPInputStreamanddeserializesthe entity. 21. Client:TheentityisreturnedfromthereadEntity(). Itisworthtomentionthatinthescenarioabovethereaderandwriterinterceptorsareinvokedonlyiftheentityispresent(itdoesnotmakesensetowrap entitystreamwhennoentitywillbewritten).Thesamebehaviouristhereformessagebodyreadersandwriters.Asmentionedabove,interceptorsare executedbeforethemessagebodyreader/writerasapartoftheirexecutionandtheycanwraptheinput/outputstreambeforetheentityisread/written.There areexceptionswheninterceptorsarenotrunbeforemessagebodyreader/writersbutthisisnotthecaseofsimplescenarioabove.Thishappensforexample

whentheentityisreadmanytimesfromclientresponseusinginternalbuffering.Thenthedataareinterceptedonlyonceandkept'decoded'inthebuffer.

9.5.Namebinding
Filtersandinterceptorscanbenamebound.NamebindingisaconceptthatallowstosaytoaJAXRSruntimethataspecificfilterorinterceptorwillbe executedonlyforaspecificresourcemethod.Whenafilteroraninterceptorislimitedonlytoaspecificresourcemethodwesaythatitisnamebound.Filters andinterceptorsthatdonothavesuchalimitationarecalledglobal. Filterorinterceptorcanbeassignedtoaresourcemethodusingthe@NameBindingannotation.Theannotationisusedasmetaannotationforotheruser implementedannotationsthatareappliedtoaprovidersandresourcemethods.Seethefollowingexample: Example9.7.@ N a m e B i n d i n g example
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 . . . i m p o r t j a v a . l a n g . a n n o t a t i o n . R e t e n t i o n i m p o r t j a v a . l a n g . a n n o t a t i o n . R e t e n t i o n P o l i c y i m p o r t j a v a . u t i l . z i p . G Z I P I n p u t S t r e a m i m p o r t j a v a x . w s . r s . G E T i m p o r t j a v a x . w s . r s . N a m e B i n d i n g i m p o r t j a v a x . w s . r s . P a t h i m p o r t j a v a x . w s . r s . P r o d u c e s . . . / / @ C o m p r e s s a n n o t a t i o n i s t h e n a m e b i n d i n g a n n o t a t i o n @ N a m e B i n d i n g @ R e t e n t i o n ( R e t e n t i o n P o l i c y . R U N T I M E ) p u b l i c @ i n t e r f a c e C o m p r e s s { } @ P a t h ( " h e l l o w o r l d " ) p u b l i c c l a s s H e l l o W o r l d R e s o u r c e { @ G E T @ P r o d u c e s ( " t e x t / p l a i n " ) p u b l i c S t r i n g g e t H e l l o ( ) { r e t u r n " H e l l o W o r l d ! " } @ G E T @ P a t h ( " t o o m u c h d a t a " ) @ C o m p r e s s p u b l i c S t r i n g g e t V e r y L o n g S t r i n g ( ) { S t r i n g s t r = . . . / / v e r y l o n g s t r i n g r e t u r n s t r } } / / i n t e r c e p t o r w i l l b e e x e c u t e d o n l y w h e n r e s o u r c e m e t h o d s / / a n n o t a t e d w i t h @ C o m p r e s s a n n o t a t i o n w i l l b e e x e c u t e d @ C o m p r e s s p u b l i c c l a s s G Z I P W r i t e r I n t e r c e p t o r i m p l e m e n t s W r i t e r I n t e r c e p t o r { @ O v e r r i d e p u b l i c v o i d a r o u n d W r i t e T o ( W r i t e r I n t e r c e p t o r C o n t e x t c o n t e x t ) t h r o w s I O E x c e p t i o n , W e b A p p l i c a t i o n E x c e p t i o n { f i n a l O u t p u t S t r e a m o u t p u t S t r e a m = c o n t e x t . g e t O u t p u t S t r e a m ( ) c o n t e x t . s e t O u t p u t S t r e a m ( n e w G Z I P O u t p u t S t r e a m ( o u t p u t S t r e a m ) ) c o n t e x t . p r o c e e d ( ) } }

Theexampleabovedefinesanew@ C o m p r e s s annotationwhichisanamebindingannotationasitisannotatedwith@ N a m e B i n d i n g .The@ C o m p r e s s is appliedontheresourcemethodg e t V e r y L o n g S t r i n g ( ) andontheinterceptorG Z I P W r i t e r I n t e r c e p t o r .Theinterceptorwillbeexecutedonlyifany resourcemethodwithsuchaannotationwillbeexecuted.Inourexamplecasetheinterceptorwillbeexecutedonlyfortheg e t V e r y L o n g S t r i n g ( ) method. Theinterceptorwillnotbeexecutedformethodg e t H e l l o ( ) .Inthisexamplethereasonisprobablyclear.Wewouldliketocompressonlylongdataandwe donotneedtocompresstheshortresponseof"HelloWorld!". Namebindingcanbeappliedonaresourceclass.IntheexampleH e l l o W o r l d R e s o u r c e wouldbeannotatedwith@ C o m p r e s s .Thiswouldmeanthatall resourcemethodswillusecompressioninthiscase. Theremightbemanynamebindingannotationsdefinedinanapplication.Whenanyprovider(filterorinterceptor)isannotatedwithmorethanonename bindingannotation,thenitwillbeexecutedforresourcemethodswhichcontainALLtheseannotations.So,forexampleifourinterceptorwouldbeannotated withanothernamebindingannotation@GZIPthentheresourcemethodwouldneedtohavebothannotationsattached,@Compressand@GZIP,otherwise theinterceptorwouldnotbeexecuted.Basedonthepreviousparagraphwecanevenusethecombinationwhentheresourcemethod g e t V e r y L o n g S t r i n g ( ) wouldbeannotatedwith@CompressandresourceclassH e l l o W o r l d R e s o u r c e wouldbeannotatedfromwith@GZIP.Thiswould alsotriggertheinterceptorasannotationsofresourcemethodsareaggregatedfromresourcemethodandfromresourceclass.Butthisisprobablyjustan edgecasewhichwillnotbeusedsooften. Notethatglobalfiltersareexecutedalways,soevenforresourcemethodswhichhaveanynamebindingannotations.

9.6.Dynamicbinding
Dynamicbindingisawayhowtoassignfiltersandinterceptorstotheresourcemethodsinadynamicmanner.Namebindingfromthepreviouschapteruses astaticapproachandchangestobindingrequiresourcecodechangeandrecompilation.Withdynamicbindingyoucanimplementcodewhichdefines bindingsduringtheapplicationinitializationtime.Thefollowingexampleshowshowtoimplementdynamicbinding. Example9.8.Dynamicbindingexample
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 . . . i m p o r t j a v a x . w s . r s . c o r e . F e a t u r e C o n t e x t i m p o r t j a v a x . w s . r s . c o n t a i n e r . D y n a m i c F e a t u r e . . . @ P a t h ( " h e l l o w o r l d " ) p u b l i c c l a s s H e l l o W o r l d R e s o u r c e { @ G E T @ P r o d u c e s ( " t e x t / p l a i n " ) p u b l i c S t r i n g g e t H e l l o ( ) { r e t u r n " H e l l o W o r l d ! " } @ G E T

1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7

@ P a t h ( " t o o m u c h d a t a " ) p u b l i c S t r i n g g e t V e r y L o n g S t r i n g ( ) { S t r i n g s t r = . . . / / v e r y l o n g s t r i n g r e t u r n s t r } } / / T h i s d y n a m i c b i n d i n g p r o v i d e r r e g i s t e r s G Z I P W r i t e r I n t e r c e p t o r / / o n l y f o r H e l l o W o r l d R e s o u r c e a n d m e t h o d s t h a t c o n t a i n / / " V e r y L o n g S t r i n g " i n t h e i r n a m e . I t w i l l b e e x e c u t e d d u r i n g / / a p p l i c a t i o n i n i t i a l i z a t i o n p h a s e . p u b l i c c l a s s C o m p r e s s i o n D y n a m i c B i n d i n g i m p l e m e n t s D y n a m i c F e a t u r e { @ O v e r r i d e p u b l i c v o i d c o n f i g u r e ( R e s o u r c e I n f o r e s o u r c e I n f o , F e a t u r e C o n t e x t c o n t e x t ) { i f ( H e l l o W o r l d R e s o u r c e . c l a s s . e q u a l s ( r e s o u r c e I n f o . g e t R e s o u r c e C l a s s ( ) ) & & r e s o u r c e I n f o . g e t R e s o u r c e M e t h o d ( ) . g e t N a m e ( ) . c o n t a i n s ( " V e r y L o n g S t r i n g " ) ) { c o n t e x t . r e g i s t e r ( G Z I P W r i t e r I n t e r c e p t o r . c l a s s ) } } }

TheexamplecontainsoneH e l l o W o r l d R e s o u r c e whichisknownfromthepreviousnamebindingexample.Thedifferenceisintheg e t V e r y L o n g S t r i n g method,whichnowdoesnotdefinethe@ C o m p r e s s namebindingannotations.ThebindingisdoneusingtheproviderwhichimplementsDynamicFeature interface.Theinterfacedefinesonec o n f i g u r e methodwithtwoarguments,R e s o u r c e I n f o andF e a t u r e C o n t e x t .R e s o u r c e I n f o containsinformation abouttheresourceandmethodtowhichthebindingcanbedone.Thec o n f i g u r e methodwillbeexecutedonceforeachresourcemethodthatisdefinedin theapplication.Intheexampleabovetheproviderwillbeexecutedtwice,oncefortheg e t H e l l o ( ) methodandonceforg e t V e r y L o n g S t r i n g ( ) (oncethe resourceInfowillcontaininformationaboutgetHello()methodandonceitwillpointtogetVeryLongString()).Ifadynamicbindingproviderwantstoregisterany providerfortheactualresourcemethoditwilldothatusingprovidedF e a t u r e C o n t e x t whichextendsJAXRSC o n f i g u r a b l e API.Allmethodsforregistration offilterorinterceptorclassesorinstancescanbeused.Suchdynamicallyregisteredfiltersorinterceptorswillbeboundonlytotheactualresourcemethod.In theexampleabovetheG Z I P W r i t e r I n t e r c e p t o r willbeboundonlytothemethodg e t V e r y L o n g S t r i n g ( ) whichwillcausethatdatawillbecompressed onlyforthismethodandnotforthemethodg e t H e l l o ( ) .ThecodeofG Z I P W r i t e r I n t e r c e p t o r isintheexamplesabove. Notethatfiltersandinterceptorsregisteredusingdynamicbindingareonlyadditionalfiltersrunfortheresourcemethod.Ifthereareanynamebound providersorglobalproviderstheywillstillbeexecuted.

9.7.Priorities
Incaseyouregistermorefiltersandinterceptorsyoumightwanttodefineanexactorderinwhichtheyshouldbeinvoked.Theordercanbecontrolledbythe @ P r i o r i t y annotationdefinedbythej a v a x . a n n o t a t i o n . P r i o r i t y class.Theannotationacceptsanintegerparameterofpriority.Providersusedin requestprocessing(C o n t a i n e r R e q u e s t F i l t e r ,C l i e n t R e q u e s t F i l t e r )aswellasentityinterceptors(R e a d e r I n t e r c e p t o r ,W r i t e r I n t e r c e p t o r )are sortedbasedonthepriorityinanascendingmanner.So,arequestfilterwithprioritydefinedwith@ P r i o r i t y ( 1 0 0 0 ) willbeexecutedbeforeanotherrequest filterwithprioritydefinedas@ P r i o r i t y ( 2 0 0 0 ) .Providersusedduringresponseprocessing(C o n t a i n e r R e s p o n s e F i l t e r ,C l i e n t R e s p o n s e F i l t e r )are executedinthereverseorder(usingdescendingmanner),soaproviderwiththeprioritydefinedwith@ P r i o r i t y ( 2 0 0 0 ) willbeexecutedbeforeanother providerwithprioritydefinedwith@ P r i o r i t y ( 1 0 0 0 ) . It'sagoodpracticetoassignaprioritytofiltersandinterceptors.UsePrioritiesclasswhichdefinesstandardizedprioritiesinJAXRSfordifferentusages, ratherthaninventingyourownpriorities.So,whenyouforexamplewriteanauthenticationfilteryouwouldassignapriority1000whichisthevalueof P r i o r i t i e s . A U T H E N T I C A T I O N .Thefollowingexampleshowsthefilterfromthebeginningofthischapterwithapriorityassigned. Example9.9.Prioritiesexample
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 . . . i m p o r t j a v a x . a n n o t a t i o n . P r i o r i t y i m p o r t j a v a x . w s . r s . P r i o r i t i e s . . . @ P r i o r i t y ( P r i o r i t i e s . H E A D E R _ D E C O R A T O R ) p u b l i c c l a s s R e s p o n s e F i l t e r i m p l e m e n t s C o n t a i n e r R e s p o n s e F i l t e r { @ O v e r r i d e p u b l i c v o i d f i l t e r ( C o n t a i n e r R e q u e s t C o n t e x t r e q u e s t C o n t e x t , C o n t a i n e r R e s p o n s e C o n t e x t r e s p o n s e C o n t e x t ) t h r o w s I O E x c e p t i o n { r e s p o n s e C o n t e x t . g e t H e a d e r s ( ) . a d d ( " X P o w e r e d B y " , " J e r s e y : ) " ) } }

Asthisisaresponsefilterandresponsefiltersareexecutedinthereverseorder,anyotherfilterwithprioritylowerthan3000 (P r i o r i t i e s . H E A D E R _ D E C O R A T O R is3000)willbeexecutedafterthisfilter.So,forexampleA U T H E N T I C A T I O N filter(priority1000)wouldberunafterthisfilter.

Chapter10.AsynchronousServicesandClients
TableofContents 10.1.AsynchronousServerAPI 10.1.1.AsynchronousServersideCallbacks 10.1.2.ChunkedOutput 10.2.ClientAPI 10.2.1.AsynchronousClientCallbacks 10.2.2.Chunkedinput ThischapterdescribestheusageofasynchronousAPIontheclientandserverside.Thetermasyncwillbesometimesusedinterchangeablywiththeterm asynchronousinthischapter.

10.1.AsynchronousServerAPI
Requestprocessingontheserverworksbydefaultinasynchronousprocessingmode,whichmeansthataclientconnectionofarequestisprocessedina singleI/Ocontainerthread.OncethethreadprocessingtherequestreturnstotheI/Ocontainer,thecontainercansafelyassumethattherequestprocessing isfinishedandthattheclientconnectioncanbesafelyreleasedincludingalltheresourcesassociatedwiththeconnection.Thismodelistypicallysufficientfor processingofrequestsforwhichtheprocessingresourcemethodexecutiontakesarelativelyshorttime.However,incaseswherearesourcemethod executionisknowntotakealongtimetocomputetheresult,serversideasynchronousprocessingmodelshouldbeused.Inthismodel,theassociation betweenarequestprocessingthreadandclientconnectionisbroken.I/Ocontainerthathandlesincomingrequestmaynolongerassumethataclient connectioncanbesafelyclosedwhenarequestprocessingthreadreturns.Insteadafacilityforexplicitlysuspending,resumingandclosingclientconnections needstobeexposed.Notethattheuseofserversideasynchronousprocessingmodelwillnotimprovetherequestprocessingtimeperceivedbytheclient.It willhoweverincreasethethroughputoftheserver,byreleasingtheinitialrequestprocessingthreadbacktotheI/Ocontainerwhiletherequestmaystillbe

waitinginaqueueforprocessingortheprocessingmaystillberunningonanotherdedicatedthread.ThereleasedI/Ocontainerthreadcanbeusedto acceptandprocessnewincomingrequestconnections. ThefollowingexampleshowsasimpleasynchronousresourcemethoddefinedusingthenewJAXRSasyncAPI: Example10.1.Simpleasyncresource


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 @ P a t h ( " / r e s o u r c e " ) p u b l i c c l a s s A s y n c R e s o u r c e { @ G E T p u b l i c v o i d a s y n c G e t ( @ S u s p e n d e d f i n a l A s y n c R e s p o n s e a s y n c R e s p o n s e ) { n e w T h r e a d ( n e w R u n n a b l e ( ) { @ O v e r r i d e p u b l i c v o i d r u n ( ) { S t r i n g r e s u l t = v e r y E x p e n s i v e O p e r a t i o n ( ) a s y n c R e s p o n s e . r e s u m e ( r e s u l t ) } p r i v a t e S t r i n g v e r y E x p e n s i v e O p e r a t i o n ( ) { / / . . . v e r y e x p e n s i v e o p e r a t i o n } } ) . s t a r t ( ) } }

Intheexampleabove,aresourceA s y n c R e s o u r c e withoneG E T methoda s y n c G e t isdefined.Thea s y n c G e t methodinjectsaJAXRSAsyncResponse instanceusingaJAXRS@Suspendedannotation.PleasenotethatA s y n c R e s p o n s e mustbeinjectedbythe@ S u s p e n d e d annotationandnotby@Contextas @ S u s p e n d e d doesnotonlyinjectresponsebutalsosaysthatthemethodisexecutedintheasynchronousmode.BytheA s y n c R e s p o n s e parameterintoa resourcemethodwetelltheJerseyruntimethatthemethodissupposedtobeinvokedusingtheasynchronousprocessingmode,thatistheclientconnection shouldnotbeautomaticallyclosedbytheunderlyingI/Ocontainerwhenthemethodreturns.Instead,theinjectedA s y n c R e s p o n s e instance(thatrepresents thesuspendedclientrequestconnection)willbeusedtoexplicitlysendtheresponsebacktotheclientusingsomeotherthread.Inotherwords,Jersey runtimeknowsthatwhenthea s y n c G e t methodcompletes,theresponsetotheclientmaynotbereadyyetandtheprocessingmustbesuspendedandwait tobeexplictlyresumedwitharesponseonceitbecomesavailable.Notethatthemethoda s y n c G e t returnsv o i d inourexample.Thisisperfectlyvalidincase ofanasynchronousJAXRSresourcemethod,evenfora@GETmethod,astheresponseisneverreturneddirectlyfromtheresourcemethodasitsreturn value.Instead,theresponseislaterreturnedusingA s y n c R e s p o n s e instanceasitisdemonstratedintheexample.Thea s y n c G e t resourcemethodstartsa newthreadandexitsfromthemethod.Inthatstatetherequestprocessingissuspendedandthecontainerthread(theonewhichenteredtheresource method)isreturnedbacktothecontainer'sthreadpoolanditcanprocessotherrequests.Newthreadstartedintheresourcemethodmayexecutean expensiveoperationwhichmighttakealongtimetofinish.Oncearesultisreadyitisresumedusingther e s u m e ( ) methodontheA s y n c R e s p o n s e instance. TheresumedresponseisthenprocessedinthenewthreadbyJerseyinasamewayasanyothersynchronousresponse,includingexecutionoffiltersand interceptors,useofexceptionmappersasnecessaryandsendingtheresponsebacktotheclient. Itisimportanttonotethattheasynchronousresponse(a s y n c R e s p o n s e intheexample)doesnotneedtoberesumedfromthethreadstartedfromthe resourcemethod.Theasynchronousresponsecanberesumedevenfromdifferentrequestprocessingthreadasitisshowninthetheexampleofthe AsyncResponsejavadoc.InthejavadocexampletheasyncresponsesuspendedfromtheG E T methodisresumedlateronfromtheP O S T method.The suspendedasyncresponseispassedbetweenrequestsusingastaticfieldandisresumedfromtheotherresourcemethodrunningonadifferentrequest processingthread. Imaginenowasituationwhenthereisalongdelaybetweentworequestsandyouwouldnotliketolettheclientwaitfortheresponse"forever"oratleastfor anunacceptablelongtime.Inasynchronousprocessingmodel,occurrencesofsuchsituationsshouldbecarefullyconsideredwithclientconnectionsnot beingautomaticallyclosedwhentheprocessingmethodreturnsandtheresponseneedstoberesumedexplicitlybasedonaneventthatmayactuallyeven neverhappen.Totacklethesesituationsasynchronoustimeoutscanbeused. Thefollowingexampleshowstheusageoftimeouts: Example10.2.Simpleasyncmethodwithtimeout
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 @ G E T p u b l i c v o i d a s y n c G e t W i t h T i m e o u t ( @ S u s p e n d e d f i n a l A s y n c R e s p o n s e a s y n c R e s p o n s e ) { a s y n c R e s p o n s e . s e t T i m e o u t H a n d l e r ( n e w T i m e o u t H a n d l e r ( ) { @ O v e r r i d e p u b l i c v o i d h a n d l e T i m e o u t ( A s y n c R e s p o n s e a s y n c R e s p o n s e ) { a s y n c R e s p o n s e . r e s u m e ( R e s p o n s e . s t a t u s ( R e s p o n s e . S t a t u s . S E R V I C E _ U N A V A I L A B L E ) . e n t i t y ( " O p e r a t i o n t i m e o u t . " ) . b u i l d ( ) ) } } ) a s y n c R e s p o n s e . s e t T i m e o u t ( 2 0 , T i m e U n i t . S E C O N D S ) n e w T h r e a d ( n e w R u n n a b l e ( ) { @ O v e r r i d e p u b l i c v o i d r u n ( ) { S t r i n g r e s u l t = v e r y E x p e n s i v e O p e r a t i o n ( ) a s y n c R e s p o n s e . r e s u m e ( r e s u l t ) } p r i v a t e S t r i n g v e r y E x p e n s i v e O p e r a t i o n ( ) { / / . . . v e r y e x p e n s i v e o p e r a t i o n t h a t t y p i c a l l y f i n i s h e s w i t h i n 2 0 s e c o n d s } } ) . s t a r t ( ) }

Bydefault,thereisnotimeoutdefinedonthesuspendedA s y n c R e s p o n s e instance.Acustomtimeoutandtimeouteventhandlermaybedefinedusing s e t T i m e o u t H a n d l e r ( T i m e o u t H a n d l e r ) ands e t T i m e o u t ( l o n g , T i m e U n i t ) methods.Thes e t T i m e o u t H a n d l e r ( T i m e o u t H a n d l e r ) methoddefinesthe handlerthatwillbeinvokedwhentimeoutisreached.Thehandlerresumestheresponsewiththeresponsecode503(from Response.Status.S E R V I C E _ U N A V A I L A B L E ).Atimeoutintervalcanbealsodefinedwithoutspecifyingacustomtimeouthandler(usingjustthe s e t T i m e o u t ( l o n g , T i m e U n i t ) method).InsuchcasethedefaultbehaviourofJerseyruntimeistothrowaS e r v i c e U n a v a i l a b l e E x c e p t i o n thatgets mappedinto503,"ServiceUnavailable"HTTPerrorresponse,asdefinedbytheJAXRSspecification.

10.1.1.AsynchronousServersideCallbacks
Asoperationsinasynchronouscasesmighttakelongtimeandtheyarenotalwaysfinishedwithinasingleresourcemethodinvocation,JAXRSoffersfacility toregistercallbackstobeinvokedbasedonsuspendedasyncresponsestatechanges.InJerseyyoucanregistertwoJAXRScallbacks: CompletionCallbackthatisexecutedwhenrequestfinishesorfails,and ConnectionCallbackexecutedwhenaconnectiontoaclientisclosedorlost. Example10.3.CompletionCallbackexample
1 2 3 @ P a t h ( " / r e s o u r c e " ) p u b l i c c l a s s A s y n c R e s o u r c e { p r i v a t e s t a t i c i n t n u m b e r O f S u c c e s s R e s p o n s e s = 0

4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5

p r i v a t e s t a t i c i n t n u m b e r O f F a i l u r e s = 0 p r i v a t e s t a t i c T h r o w a b l e l a s t E x c e p t i o n = n u l l @ G E T p u b l i c v o i d a s y n c G e t W i t h T i m e o u t ( @ S u s p e n d e d f i n a l A s y n c R e s p o n s e a s y n c R e s p o n s e ) { a s y n c R e s p o n s e . r e g i s t e r ( n e w C o m p l e t i o n C a l l b a c k ( ) { @ O v e r r i d e p u b l i c v o i d o n C o m p l e t e ( T h r o w a b l e t h r o w a b l e ) { i f ( t h r o w a b l e = = n u l l ) { / / n o t h r o w a b l e t h e p r o c e s s i n g e n d e d s u c c e s s f u l l y / / ( r e s p o n s e a l r e a d y w r i t t e n t o t h e c l i e n t ) n u m b e r O f S u c c e s s R e s p o n s e s + + } e l s e { n u m b e r O f F a i l u r e s + + l a s t E x c e p t i o n = t h r o w a b l e } } } ) n e w T h r e a d ( n e w R u n n a b l e ( ) { @ O v e r r i d e p u b l i c v o i d r u n ( ) { S t r i n g r e s u l t = v e r y E x p e n s i v e O p e r a t i o n ( ) a s y n c R e s p o n s e . r e s u m e ( r e s u l t ) } p r i v a t e S t r i n g v e r y E x p e n s i v e O p e r a t i o n ( ) { / / . . . v e r y e x p e n s i v e o p e r a t i o n } } ) . s t a r t ( ) } }

Acompletioncallbackisregisteredusingr e g i s t e r ( . . . ) methodontheA s y n c R e s p o n s e instance.Aregisteredcompletioncallbackisboundonlytothe response(s)towhichithasbeenregistered.IntheexampletheC o m p l e t i o n C a l l b a c k isusedtocalculatesuccessfullyprocessedresponses,failuresandto storelastexception.Thisisonlyasimplecasedemonstratingtheusageofthecallback.Youcanusecompletioncallbacktoreleasetheresources,change stateofinternalresourcesorrepresentationsorhandlefailures.ThemethodhasanargumentT h r o w a b l e whichissetonlyincaseofanerror.Otherwisethe parameterwillben u l l ,whichmeansthattheresponsewassuccessfullywritten.Thecallbackisexecutedonlyaftertheresponseiswrittentotheclient(not immediatelyaftertheresponseisresumed). TheA s y n c R e s p o n s e r e g i s t e r ( . . . ) methodisoverloadedandoffersoptionstoregisterasinglecallbackasanO b j e c t (intheexample),asaC l a s s or multiplecallbacksusingvarags. Assomeasyncrequestsmaytakelongtimetoprocesstheclientmaydecidetoterminateit'sconnectiontotheserverbeforetheresponsehasbeenresumed orbeforeithasbeenfullywrittentotheclient.TodealwiththeseusecasesaC o n n e c t i o n C a l l b a c k canbeused.Thiscallbackwillbeexecutedonlyifthe connectionwasprematurelyterminatedorlostwhiletheresponseisbeingwrittentothebackclient.Notethatthiscallbackwillnotbeinvokedwhena responseiswrittensuccessfullyandtheclientconnectionisclosedasexpected.SeejavadocofConnectionCallbackformoreinformation.

10.1.2.ChunkedOutput
Jerseyoffersafacilityforsendingresponsetotheclientinmultiplemoreorlessindependentchunksusingachunkedoutput.Eachresponsechunkusually takessome(longer)timetopreparebeforesendingittotheclient.Themostimportantfactaboutresponsechunksisthatyouwanttosendthemtotheclient immediatelyastheybecomeavailablewithoutwaitingfortheremainingchunkstobecomeavailabletoo.Thefirstbytesofeachchunkedresponseconsistsof theHTTPheadersthataresenttotheclient.Thesize1issetintheresponseC o n t e n t L e n g t h headertoindicatethattheresponseischunked.Asnoted above,theentityoftheresponseisthensentinchunksastheybecomeavailable.Clientknowsthattheresponseisgoingtobechunked,soitreadseach chunkoftheresponseseparately,processesit,andwaitsformorechunkstoarriveonthesameconnection.Aftersometime,theservergeneratesanother responsechunkandsenditagaintotheclient.Serverkeepsonsendingresponsechunksuntilitclosestheconnectionaftersendingthelastchunkwhenthe responseprocessingisfinished. InJerseyyoucanuseChunkedOutputtosendresponsetoaclientinchunks.Chunksarestrictlydefinedpiecesofaresponsebodycanbemarshalledasa separateentitiesusingJersey/JAXRSMessageBodyWriter<T>providers.AchunkcanbeString,LongorJAXBbeanserializedtoXMLorJSONoranyother dacustomtypeforwhichaM e s s a g e B o d y W r i t e r < T > isavailable. TheresourcemethodthatreturnsC h u n k e d O u t p u t informstheJerseyruntimethattheresponsewillbechunkedandthattheprocessingworks asynchronouslyassuch.YoudonotneedtoinjectA s y n c R e s p o n s e tostarttheasynchronousprocessingmodeinthiscase.ReturningaC h u n k e d O u t p u t instancefromthemethodisenoughtoindicatetheasynchronousprocessing.Responseheaderswillbesenttoaclientwhentheresourcemethodreturns andtheclientwillwaitforthestreamofchunkeddatawhichyouwillbeabletowritefromdifferentthreadusingthesameC h u n k e d O u t p u t instancereturned fromtheresourcemethodearlier.Thefollowingexampledemonstratesthisusecase: Example10.4.ChunkedOutputexample
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 @ P a t h ( " / r e s o u r c e " ) p u b l i c c l a s s A s y n c R e s o u r c e { @ G E T p u b l i c C h u n k e d O u t p u t < S t r i n g > g e t C h u n k e d R e s p o n s e ( ) { f i n a l C h u n k e d O u t p u t < S t r i n g > o u t p u t = n e w C h u n k e d O u t p u t < S t r i n g > ( S t r i n g . c l a s s ) n e w T h r e a d ( ) { p u b l i c v o i d r u n ( ) { t r y { S t r i n g c h u n k w h i l e ( ( c h u n k = g e t N e x t S t r i n g ( ) ) ! = n u l l ) { o u t p u t . w r i t e ( c h u n k ) } } c a t c h ( I O E x c e p t i o n e ) { / / I O E x c e p t i o n t h r o w n w h e n w r i t i n g t h e / / c h u n k s o f r e s p o n s e : s h o u l d b e h a n d l e d } f i n a l l y { o u t p u t . c l o s e ( ) / / s i m p l i f i e d : I O E x c e p t i o n t h r o w n f r o m / / t h i s c l o s e ( ) s h o u l d b e h a n d l e d h e r e . . . } } } . s t a r t ( ) / / t h e o u t p u t w i l l b e p r o b a b l y r e t u r n e d e v e n b e f o r e / / a f i r s t c h u n k i s w r i t t e n b y t h e n e w t h r e a d r e t u r n o u t p u t } p r i v a t e S t r i n g g e t N e x t S t r i n g ( ) { / / . . . l o n g r u n n i n g o p e r a t i o n t h a t r e t u r n s / / n e x t s t r i n g o r n u l l i f n o o t h e r s t r i n g i s a c c e s s i b l e } }

TheexampleabovedefinesaG E T methodthatreturnsaC h u n k e d O u t p u t instance.ThegenerictypeofC h u n k e d O u t p u t definesthechunktypes(inthiscase chunksareStrings).Beforetheinstanceisreturnedanewthreadisstartedthatwritesindividualchunksintothechunkedoutputinstancenamedo u t p u t . Oncetheoriginalthreadreturnsfromtheresourcemethod,Jerseyruntimewritesheaderstothecontainerresponsebutdoesnotclosetheclientconnection yetandwaitsfortheresponsedatatobewrittentothechunkedo u t p u t .Newthreadinaloopcallsthemethodg e t N e x t S t r i n g ( ) whichreturnsanextString orn u l l ifnootherStringexists(themethodcouldforexampleloadlatestdatafromthedatabase).ReturnedStringsarewrittentothechunkedo u t p u t .Such awrittenchunksareinternallywrittentothecontainerresponseandclientcanreadthem.Attheendthechunkedoutputisclosedwhichdeterminestheend ofthechunkedresponse.PleasenotethatyoumustclosetheoutputexplicitlyinordertoclosetheclientconnectionasJerseydoesnotimplicitlyknowwhen youarefinishedwithwritingthechunks. Achunkedoutputcanbeprocessedalsofromthreadscreatedfromanotherrequestasitisexplainedinthesectionsabove.Thismeansthatoneresource methodmaye.g.onlyreturnaC h u n k e d O u t p u t instanceandotherresourcemethod(s)invokedfromanotherrequestthread(s)canwritedataintothe chunkedoutputand/orclosethechunkedresponse.

10.2.ClientAPI
TheclientAPIsupportsasynchronousprocessingtoo.SimpleusageofasynchronousclientAPIisshowninthefollowingexample: Example10.5.Simpleclientasyncinvocation
1 2 3 4 5 6 7 f i n a l A s y n c I n v o k e r a s y n c I n v o k e r = t a r g e t ( ) . p a t h ( " h t t p : / / e x a m p l e . c o m / r e s o u r c e / " ) . r e q u e s t ( ) . a s y n c ( ) f i n a l F u t u r e < R e s p o n s e > r e s p o n s e F u t u r e = a s y n c I n v o k e r . g e t ( ) S y s t e m . o u t . p r i n t l n ( " R e q u e s t i s b e i n g p r o c e s s e d a s y n c h r o n o u s l y . " ) f i n a l R e s p o n s e r e s p o n s e = r e s p o n s e F u t u r e . g e t ( ) / / g e t ( ) w a i t s f o r t h e r e s p o n s e t o b e r e a d y S y s t e m . o u t . p r i n t l n ( " R e s p o n s e r e c e i v e d . " )

Thedifferenceagainstsynchronousinvocationisthatthehttpmethodcallg e t ( ) isnotcalledonSyncInvokerbutonAsyncInvoker.TheA s y n c I n v o k e r is returnedfromthecallofmethodI n v o c a t i o n . B u i l d e r . a s y n c ( ) asshownabove.A s y n c I n v o k e r offersmethodssimilartoS y n c I n v o k e r onlythese methodsdonotreturnaresponsesynchronously.InsteadaF u t u r e < . . . > representingresponsedataisreturned.Thesemethodcallsalsoreturn immediatelywithoutwaitingfortheactualrequesttocomplete.Inordertogettheresponseoftheinvokedg e t ( ) method,ther e s p o n s e F u t u r e . g e t ( ) is invokedwhichwaitsfortheresponsetobefinished(thiscallisblockingasdefinedbytheJavaSEF u t u r e contract). AsynchronousClientAPIinJAXRSisfullyintegratedinthefluentJAXRSClientAPIflow,sothattheasyncclientsideinvocationscanbewrittenfluentlyjust likeinthefollowingexample: Example10.6.Simpleclientfluentasyncinvocation
1 2 f i n a l F u t u r e < R e s p o n s e > r e s p o n s e F u t u r e = t a r g e t ( ) . p a t h ( " h t t p : / / e x a m p l e . c o m / r e s o u r c e / " ) . r e q u e s t ( ) . a s y n c ( ) . g e t ( )

Toworkwithasynchronousresultsontheclientside,allstandardF u t u r e APIfacilitiescanbeused.Forexample,youcanusethei s D o n e ( ) methodto determinewhetheraresponsehasfinishedtoavoidtheuseofablockingcalltoF u t u r e . g e t ( ) .

10.2.1.AsynchronousClientCallbacks
Similarlytotheserverside,intheclientAPIyoucanregisterasynchronouscallbackstoo.Youcanusethesecallbackstobenotifiedwhenaresponsearrives insteadofwaitingfortheresponseonF u t u r e . g e t ( ) orcheckingthestatusbyF u t u r e . i s D o n e ( ) inaloop.Aclientsideasynchronousinvocationcallback canberegisteredasshowninthefollowingexample: Example10.7.Clientasynccallback
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 f i n a l F u t u r e < R e s p o n s e > r e s p o n s e F u t u r e = t a r g e t ( ) . p a t h ( " h t t p : / / e x a m p l e . c o m / r e s o u r c e / " ) . r e q u e s t ( ) . a s y n c ( ) . g e t ( n e w I n v o c a t i o n C a l l b a c k < R e s p o n s e > ( ) { @ O v e r r i d e p u b l i c v o i d c o m p l e t e d ( R e s p o n s e r e s p o n s e ) { S y s t e m . o u t . p r i n t l n ( " R e s p o n s e s t a t u s c o d e " + r e s p o n s e . g e t S t a t u s ( ) + " r e c e i v e d . " ) } @ O v e r r i d e p u b l i c v o i d f a i l e d ( T h r o w a b l e t h r o w a b l e ) { S y s t e m . o u t . p r i n t l n ( " I n v o c a t i o n f a i l e d . " ) t h r o w a b l e . p r i n t S t a c k T r a c e ( ) } } )

TheregisteredcallbackisexpectedtoimplementtheInvocationCallbackinterfacethatdefinestwomethods.Firstmethodc o m p l e t e d ( R e s p o n s e ) gets invokedwhenaninvocationsuccessfullyfinishes.Theresultresponseispassedasaparametertothecallbackmethod.Thesecondmethod f a i l e d ( T h r o w a b l e ) isinvokedincasetheinvocationfailsandtheexceptiondescribingthefailureispassedtothemethodasaparameter.Inthiscasesince thecallbackgenerictypeisR e s p o n s e ,thef a i l e d ( T h r o w a b l e ) methodwouldonlyinvokedincasetheinvocationfailsbecauseofaninternalclientside processingerror.ItwouldnotbeinvokedincaseaserverrespondswithanHTTPerrorcode,forexampleiftherequestedresourceisnotfoundontheserver andHTTP4 0 4 responsecodeisreturned.Insuchcasec o m p l e t e d ( R e s p o n s e ) callbackmethodwouldbeinvokedandtheresponsepassedtothemethod wouldcontainthereturnederrorresponsewithHTTP4 0 4 errorcode.ThisisaspecialbehaviorincasethegenericcallbackreturntypeisR e s p o n s e .Inthe nextexampleanexceptionisthrown(orf a i l e d ( T h r o w a b l e ) methodontheinvocationcallbackisinvoked)evenincaseanon2 x x HTTPerrorcodeis returned. AswiththesynchronousclientAPI,youcanretrievetheresponseentityasaJavatypedirectlywithoutrequestingaR e s p o n s e first.Incaseofan I n v o c a t i o n C a l l b a c k ,youneedtosetitsgenerictypetotheexpectedresponseentitytypeinsteadofusingtheR e s p o n s e typeasdemonstratedinthe examplebellow: Example10.8.Clientasynccallbackforspecificentity
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 f i n a l F u t u r e < S t r i n g > e n t i t y F u t u r e = t a r g e t ( ) . p a t h ( " h t t p : / / e x a m p l e . c o m / r e s o u r c e / " ) . r e q u e s t ( ) . a s y n c ( ) . g e t ( n e w I n v o c a t i o n C a l l b a c k < S t r i n g > ( ) { @ O v e r r i d e p u b l i c v o i d c o m p l e t e d ( S t r i n g r e s p o n s e ) { S y s t e m . o u t . p r i n t l n ( " R e s p o n s e e n t i t y ' " + r e s p o n s e + " ' r e c e i v e d . " ) } @ O v e r r i d e p u b l i c v o i d f a i l e d ( T h r o w a b l e t h r o w a b l e ) { S y s t e m . o u t . p r i n t l n ( " I n v o c a t i o n f a i l e d . " ) t h r o w a b l e . p r i n t S t a c k T r a c e ( ) } } ) S y s t e m . o u t . p r i n t l n ( e n t i t y F u t u r e . g e t ( ) )

Here,thegenerictypeoftheinvocationcallbackinformationisusedtounmarshalltheHTTPresponsecontentintoadesiredJavatype.

Important
Pleasenotethatinthiscasethemethodf a i l e d ( T h r o w a b l e t h r o w a b l e ) wouldbeinvokedevenforcaseswhenaserverrespondswitha nonHTTP2 x x HTTPerrorcode.Thisisbecauseinthiscasetheuserdoesnothaveanyothermeansoffindingoutthattheserverreturned anerrorresponse.

10.2.2.Chunkedinput
InanearliersectiontheC h u n k e d O u t p u t wasdescribed.Itwasshownhowtouseachunkedoutputontheserver.Inordertoreadchunksontheclientthe ChunkedInputcanbeusedtocompletethestory. Youcan,ofcourse,processinputontheclientasastandardinputstreambutifyouwouldliketoleverageJerseyinfrastructuretoprovidesupportof translatingmessagechunkdataintoJavatypesusingaC h u n k e d I n p u t ismuchmorestraightforward.SeetheusageoftheC h u n k e d I n p u t inthefollowing example: Example10.9.ChunkedInputexample
1 2 3 4 5 6 7 8 f i n a l R e s p o n s e r e s p o n s e = t a r g e t ( ) . p a t h ( " h t t p : / / e x a m p l e . c o m / r e s o u r c e / " ) . r e q u e s t ( ) . g e t ( ) f i n a l C h u n k e d I n p u t < S t r i n g > c h u n k e d I n p u t = r e s p o n s e . r e a d E n t i t y ( n e w G e n e r i c T y p e < C h u n k e d I n p u t < S t r i n g > > ( ) { } ) S t r i n g c h u n k w h i l e ( ( c h u n k = c h u n k e d I n p u t . r e a d ( ) ) ! = n u l l ) { S y s t e m . o u t . p r i n t l n ( " N e x t c h u n k r e c e i v e d : " + c h u n k ) }

Theresponseisretrievedinastandardwayfromtheserver.TheentityisreadasaC h u n k e d I n p u t entity.InordertodothattheGenericEntity<T>isusedto preserveagenericinformationatruntime.IfyouwouldnotuseG e n e r i c E n t i t y < T > ,Javalanguagegenerictypeerasurewouldcausethatthegeneric informationwouldgetlostatcompiletimeandanexceptionwouldbethrownatruntimecomplainingaboutthemissingchunktypedefinition. Inthenextlinesintheexample,individualchunksarebeingreadfromtheresponse.Chunkscancomewithsomedelay,sotheywillbewrittentotheconsole astheycomefromtheserver.Afterreceivinglastchunkthen u l l willbereturnedfromther e a d ( ) method.Thiswillmeanthattheserverhassentthelast chunkandclosedtheconnection.Notethatther e a d ( ) isablockingoperationandtheinvokingthreadisblockeduntilanewchunkcomes. WritingchunkswithC h u n k e d O u t p u t issimple,youonlycallmethodw r i t e ( ) whichwritesexactlyonechunktotheoutput.Withtheinputreadingitisslightly morecomplicated.TheC h u n k e d I n p u t doesnotknowhowtodistinguishchunksinthebytestreamunlessbeingtoldbythedeveloper.Inordertodefine customchunksboundaries,theC h u n k e d I n p u t offerspossibilitytoregisteraChunkParserwhichreadschunksfromtheinputstreamandseparatesthem. Jerseyprovidesseveralchunkparserimplementationandyoucanimplementyourownparsertoseparateyourchunksifyouneed.Inourexampleabovethe defaultparserprovidedbyJerseyisusedthatseparateschunksbasedonpresenceofa\ r \ n delimitingcharactersequence. EachincominginputstreamisfirstlyparsedbytheC h u n k P a r s e r ,theneachchunkisprocessedbytheproperMessageBodyReader<T>.Youcandefinethe mediatypeofchunkstoaidtheselectionofaproperM e s s a g e B o d y R e a d e r < T > inordertoreadchunkscorrectlyintotherequestedentitytypes(inourcase intoStrings).

Chapter11.URIsandLinks
TableofContents 11.1.BuildingURIs 11.2.ResolveandRelativize 11.3.Link

11.1.BuildingURIs
AveryimportantaspectofRESTishyperlinks,URIs,inrepresentationsthatclientscanusetotransitiontheWebservicetonewapplicationstates(thisis otherwiseknownas"hypermediaastheengineofapplicationstate").HTMLformspresentagoodexampleofthisinpractice. BuildingURIsandbuildingthemsafelyisnoteasywithURI,whichiswhyJAXRShastheUriBuilderclassthatmakesitsimpleandeasytobuildURIssafely. U r i B u i l d e r canbeusedtobuildnewURIsorbuildfromexistingURIs.ForresourceclassesitismorethanlikelythatURIswillbebuiltfromthebaseURIthe webserviceisdeployedatorfromtherequestURI.TheclassUriInfoprovidessuchinformation(inadditiontofurtherinformation,seenextsection). ThefollowingexampleshowsURIbuildingwithU r i I n f o andU r i B u i l d e r fromthebookmarkexample: Example11.1.URIbuilding
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 @ P a t h ( " / u s e r s / " ) p u b l i c c l a s s U s e r s R e s o u r c e { @ C o n t e x t U r i I n f o u r i I n f o . . . @ G E T @ P r o d u c e s ( " a p p l i c a t i o n / j s o n " ) p u b l i c J S O N A r r a y g e t U s e r s A s J s o n A r r a y ( ) { J S O N A r r a y u r i A r r a y = n e w J S O N A r r a y ( ) f o r ( U s e r E n t i t y u s e r E n t i t y : g e t U s e r s ( ) ) { U r i B u i l d e r u b = u r i I n f o . g e t A b s o l u t e P a t h B u i l d e r ( ) U R I u s e r U r i = u b . p a t h ( u s e r E n t i t y . g e t U s e r i d ( ) ) . b u i l d ( ) u r i A r r a y . p u t ( u s e r U r i . t o A S C I I S t r i n g ( ) ) } r e t u r n u r i A r r a y } }

U r i I n f o isobtainedusingthe@Contextannotation,andinthisparticularexampleinjectionontothefieldoftherootresourceclassisperformed,previous

examplesshowedtheuseof@Contextonresourcemethodparameters.
U r i I n f o canbeusedtoobtainURIsandassociatedU r i B u i l d e r instancesforthefollowingURIs:thebaseURItheapplicationisdeployedattherequest

URIandtheabsolutepathURI,whichistherequestURIminusanyquerycomponents. Theg e t U s e r s A s J s o n A r r a y methodconstructsaJ S O N A r r r a y ,whereeachelementisaURIidentifyingaspecificuserresource.TheURIisbuiltfromthe absolutepathoftherequestURIbycallingUriInfo.getAbsolutePathBuilder().Anewpathsegmentisadded,whichistheuserID,andthentheURIisbuilt. Noticethatitisnotnecessarytoworryabouttheinclusionof' / ' charactersorthattheuserIDmaycontaincharactersthatneedtobepercentencoded. U r i B u i l d e r takescareofsuchdetails.

U r i B u i l d e r canbeusedtobuild/replacequeryormatrixparameters.URItemplatescanalsobedeclared,forexamplethefollowingwillbuildtheURI " h t t p : / / l o c a l h o s t / s e g m e n t ? n a m e = v a l u e " :

Example11.2.BuildingURIsusingqueryparameters
1 2 3 4 U r i B u i l d e r . f r o m U r i ( " h t t p : / / l o c a l h o s t / " ) . p a t h ( " { a } " ) . q u e r y P a r a m ( " n a m e " , " { v a l u e } " ) . b u i l d ( " s e g m e n t " , " v a l u e " )

11.2.ResolveandRelativize
JAXRS2.0introducedadditionalURIresolutionandrelativizationmethodsintheU r i B u i l d e r : UriInfo.resolve(java.net.URI) UriInfo.relativize(java.net.URI) UriBuilder.resolveTemplate(...)(variousarguments) ResolveandrelativizemethodsinUriInfoareessentiallycounterpartstothemethodslistedaboveUriInfo.resolve(java.net.URI)resolvesgivenrelativeURIto anabsoluteURIusingapplicationcontextURIasthebaseURIUriInfo.relativize(java.net.URI)thentransformsanabsoluteURItoarelativeone,usingagain theapplicationscontextURIasthebaseURI.
U r i B u i l d e r alsointroducesasetofmethodsthatprovidewaysofresolvingURItemplatesbyreplacingindividualtemplateswithaprovidedvalue(s).Ashort

example:
1 2 3 4 5 6 f i n a l U R I u r i = U r i B u i l d e r . f r o m U r i ( " h t t p : / / { h o s t } / { p a t h } ? q = { p a r a m } " ) . r e s o l v e T e m p l a t e ( " h o s t " , " l o c a l h o s t " ) . r e s o l v e T e m p l a t e ( " p a t h " , " m y A p p " ) . r e s o l v e T e m p l a t e ( " p a r a m " , " v a l u e " ) . b u i l d ( ) u r i . t o S t r i n g ( ) / / r e t u r n s " h t t p : / / l o c a l h o s t / m y A p p ? q = v a l u e "

SeetheUriBuilderjavadocformoredetails.

11.3.Link
JAXRS2.0introducesLinkclass,whichservesasarepresentationofWebLinkdefinedinRFC5988.TheJAXRSL i n k classaddsAPIsupportforproviding additionalmetadatainHTTPmessages,forexample,ifyouareconsumingaRESTinterfaceofapubliclibrary,youmighthavearesourcereturning descriptionofasinglebook.Thenyoucanincludelinkstorelatedresources,suchasabookcategory,author,etc.tomaketheproducedresponseconcise butcompleteatthesametime.Clientsarethenabletoqueryalltheadditionalinformationtheyareinterestedinandarenotforcedtoconsumedetailsthey arenotinterestedin.Atthesametime,thisapproachrelievestheserverresourcesasonlytheinformationthatistrulyrequestedisbeingservedtothe clients. AL i n k canbeserializedtoanHTTPmessage(tyicallyaresponse)asadditionalHTTPheader(theremightbemultipleL i n k headersprovided,thusmultiple linkscanbeservedinasinglemessage).SuchHTTPheadermaylooklike:
L i n k : < h t t p : / / e x a m p l e . c o m / T h e B o o k / c h a p t e r 2 > r e l = " p r e v " t i t l e = " p r e v i o u s c h a p t e r "

ProducingandconsumingLinkswithJAXRSAPIisdemonstratedinthefollowingexample:
/ / s e r v e r s i d e a d d i n g l i n k s t o a r e s p o n s e : R e s p o n s e r = R e s p o n s e . o k ( ) . l i n k ( " h t t p : / / o r a c l e . c o m " , " p a r e n t " ) . l i n k ( n e w U R I ( " h t t p : / / j e r s e y . j a v a . n e t " ) , " f r a m e w o r k " ) . b u i l d ( ) . . . / / c l i e n t s i d e p r o c e s s i n g : f i n a l R e s p o n s e r e s p o n s e = t a r g e t . r e q u e s t ( ) . g e t ( ) U R I u = r e s p o n s e . g e t L i n k ( " p a r e n t " ) . g e t U r i ( ) U R I u = r e s p o n s e . g e t L i n k ( " f r a m e w o r k " ) . g e t U r i ( )

InstancesofL i n k canbealsocreateddirectlybyinvokingoneofthefactorymethodsontheLinkAPIthatreturnsaLink.Builderthatcanbeusedtoconfigure andproducenewlinks.

Chapter12.ProgrammaticAPIforBuildingResources
TableofContents 12.1.Introduction 12.2.ProgrammaticHelloWorldexample 12.2.1.Deploymentofprogrammaticresources 12.3.Additionalexamples 12.4.Modelprocessors

12.1.Introduction
AstandardapproachofdevelopingJAXRSapplicationistoimplementresourceclassesannotatedwith@PathwithresourcemethodsannotatedwithHTTP methodannotationslike@GETor@POSTandimplementneededfunctionality.ThisapproachisdescribedinthechapterJAXRSApplication,Resourcesand SubResources.BesidesthisstandardJAXRSapproach,JerseyoffersanAPIforconstructingresourcesprogrammatically. ImagineasituationwhereadeployedJAXRSapplicationconsistsofmanyresourceclasses.TheseresourcesimplementstandardHTTPmethodslike @GET,@POST,@DELETE.Insomesituationsitwouldbeusefultoaddan@OPTIONSmethodwhichwouldreturnsomekindofmetadataaboutthe deployedresource.Ideally,youwouldwanttoexposethefunctionalityasanadditionalfeatureandyouwanttodecideatthedeploytimewhetheryouwantto addyourcustomO P T I O N S method.However,whencustomO P T I O N S methodarenotenabledyouwouldliketobeO P T I O N S requestshandledinthestandard waybyJAXRSruntime.ToachievethisyouwouldneedtomodifythecodetoaddorremovecustomO P T I O N S methodsbeforedeployment.Anotherway wouldbetouseprogrammaticAPItobuildresourceaccordingtoyourneeds. AnotherusecaseofprogrammaticresourcebuilderAPIiswhenyoubuildanygenericRESTfulinterfacewhichdependsonlotofconfigurationparametersor forexampledatabasestructure.Yourresourceclasseswouldneedtohavedifferentmethods,differentstructureforeverynewapplicationdeploy.Youcould usemoresolutionsincludingapproacheswhereyourresourceclasseswouldbebuiltusingJavabytecodemanipulation.However,thisisexactlythecase whenyoucansolvetheproblemcleanlywiththeprogrammaticresourcebuilderAPI.Let'shaveacloserlookathowtheAPIcanbeutilized.

12.2.ProgrammaticHelloWorldexample

JerseyProgrammaticAPIwasdesignedtofullysupportJAXRSresourcemodel.Inotherwords,everyresourcethatcanbedesignedusingstandardJAXRS approachviaannotatedresourceclassescanbealsomodelledusingJerseyprogrammaticAPI.Let'strytobuildsimplehelloworldresourceusingstandard approachfirstandthenusingtheJerseyprogrammaticresourcebuilderAPI. ThefollowingexampleshowsstandardJAXRS"Helloworld!"resourceclass. Example12.1.Astandardresourceclass


1 2 3 4 5 6 7 8 9 @ P a t h ( " h e l l o w o r l d " ) p u b l i c c l a s s H e l l o W o r l d R e s o u r c e { @ G E T @ P r o d u c e s ( " t e x t / p l a i n " ) p u b l i c S t r i n g g e t H e l l o ( ) { r e t u r n " H e l l o W o r l d ! " } }

ThisisjustasimpleresourceclasswithoneGETmethodreturning"HelloWorld!"stringthatwillbeserializedastext/plainmediatype. NowwewilldesignthissimpleresourceusingprogrammaticAPI. Example12.2.Aprogrammaticresource


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 p a c k a g e o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . h e l l o w o r l d i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e q u e s t C o n t e x t i m p o r t j a v a x . w s . r s . c o r e . A p p l i c a t i o n i m p o r t j a v a x . w s . r s . c o r e . R e s p o n s e i m p o r t o r g . g l a s s f i s h . j e r s e y . p r o c e s s . I n f l e c t o r i m p o r t o r g . g l a s s f i s h . j e r s e y . s e r v e r . R e s o u r c e C o n f i g i m p o r t o r g . g l a s s f i s h . j e r s e y . s e r v e r . m o d e l . R e s o u r c e i m p o r t o r g . g l a s s f i s h . j e r s e y . s e r v e r . m o d e l . R e s o u r c e M e t h o d p u b l i c s t a t i c c l a s s M y R e s o u r c e C o n f i g e x t e n d s R e s o u r c e C o n f i g { p u b l i c M y R e s o u r c e C o n f i g ( ) { f i n a l R e s o u r c e . B u i l d e r r e s o u r c e B u i l d e r = R e s o u r c e . b u i l d e r ( ) r e s o u r c e B u i l d e r . p a t h ( " h e l l o w o r l d " ) f i n a l R e s o u r c e M e t h o d . B u i l d e r m e t h o d B u i l d e r = r e s o u r c e B u i l d e r . a d d M e t h o d ( " G E T " ) m e t h o d B u i l d e r . p r o d u c e s ( M e d i a T y p e . T E X T _ P L A I N _ T Y P E ) . h a n d l e d B y ( n e w I n f l e c t o r < C o n t a i n e r R e q u e s t C o n t e x t , S t r i n g > ( ) { @ O v e r r i d e p u b l i c S t r i n g a p p l y ( C o n t a i n e r R e q u e s t C o n t e x t c o n t a i n e r R e q u e s t C o n t e x t ) { r e t u r n " H e l l o W o r l d ! " } } ) f i n a l R e s o u r c e r e s o u r c e = r e s o u r c e B u i l d e r . b u i l d ( ) r e g i s t e r R e s o u r c e s ( r e s o u r c e ) } }

First,focusonthecontentoftheM y R e s o u r c e C o n f i g constructorintheexample.TheJerseyprogrammaticresourcemodelisconstructedfromR e s o u r c e s thatcontainR e s o u r c e M e t h o d s.Intheexample,asingleresourcewouldbeconstructedfromaR e s o u r c e containingoneG E T resourcemethodthatreturns "HelloWorld!".ThemainentrypointforbuildingprogrammaticresourcesinJerseyistheR e s o u r c e . B u i l d e r class.R e s o u r c e . B u i l d e r containsjustafew methodslikethep a t h methodusedintheexample,whichsetsthenameofthepath.Anotherusefulmethodisaa d d M e t h o d ( S t r i n g p a t h ) whichaddsa newmethodtotheresourcebuilderandreturnsaresourcemethodbuilderforthenewmethod.Resourcemethodbuildercontainsmethodswhichset consumedandproducedmediatype,definenamebindings,timeoutforasynchronousexecutions,etc.Itisalwaysnecessarytodefinearesourcemethod handler(i.e.thecodeoftheresourcemethodthatwillreturn"HelloWorld!").Therearemoreoptionshowaresourcemethodcanbehandled.Intheexample theimplementationofI n f l e c t o r isused.TheJerseyI n f l e c t o r interfacedefinesasimplecontractfortransformationofarequestintoaresponse.An inflectorcaneitherreturnaResponseordirectlyanentityobject,thewayitisshownintheexample.AnotheroptionistosetupaJavamethodhandlerusing h a n d l e d B y ( C l a s s < ? > h a n d l e r C l a s s , M e t h o d m e t h o d ) andpassitthechosenj a v a . l a n g . r e f l e c t . M e t h o d instancetogetherwiththeenclosingclass. Aresourcemethodmodelconstructioncanbeexplicitlycompletedbyinvokingb u i l d ( ) ontheresourcemethodbuilder.Itishowevernotnecessarytodoso asthenewresourcemethodmodelwillbebuiltautomaticallyoncetheparentresourceisbuilt.Oncearesourcemodelisbuilt,itisregisteredintothe resourceconfigatthelastlineoftheM y R e s o u r c e C o n f i g constructorintheexample.

12.2.1.Deploymentofprogrammaticresources
Let'snowlookathowaprogrammaticresourcesaredeployed.Theeasiestwaytosetupyourapplicationaswellasregisteranyprogrammaticresourcesin JerseyistouseaJerseyR e s o u r c e C o n f i g utilityclass,anextensionofApplicationclass.IfyoudeployyourJerseyapplicationintoaServletcontaineryouwill needtoprovideaApplicationsubclassthatwillbeusedforconfiguration.Youmayuseaw e b . x m l whereyouwoulddefinea o r g . g l a s s f i s h . j e r s e y . s e r v l e t . S e r v l e t C o n t a i n e r Servletentrythereandspecifyinitialparameterj a v a x . w s . r s . A p p l i c a t i o n withtheclassnameof yourJAXRSApplicationthatyouwishtodeploy.Intheexampleabove,thisapplicationwillbeM y R e s o u r c e C o n f i g class.Thisisthereasonwhy M y R e s o u r c e C o n f i g extendstheR e s o u r c e C o n f i g (which,ifyourememberextendsthej a v a x . w s . r s . A p p l i c a t i o n ). Thefollowingexampleshowsafragmentofw e b . x m l thatcanbeusedtodeploytheR e s o u r c e C o n f i g JAXRSapplication. Example12.3.Aprogrammaticresource
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 . . . < s e r v l e t > < s e r v l e t n a m e > o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . h e l l o w o r l d . M y A p p l i c a t i o n < / s e r v l e t n a m e > < s e r v l e t c l a s s > o r g . g l a s s f i s h . j e r s e y . s e r v l e t . S e r v l e t C o n t a i n e r < / s e r v l e t c l a s s > < i n i t p a r a m > < p a r a m n a m e > j a v a x . w s . r s . A p p l i c a t i o n < / p a r a m n a m e > < p a r a m v a l u e > o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . h e l l o w o r l d . M y R e s o u r c e C o n f i g < / p a r a m v a l u e > < / i n i t p a r a m > < l o a d o n s t a r t u p > 1 < / l o a d o n s t a r t u p > < / s e r v l e t > < s e r v l e t m a p p i n g > < s e r v l e t n a m e > o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . h e l l o w o r l d . M y A p p l i c a t i o n < / s e r v l e t n a m e > < u r l p a t t e r n > / * < / u r l p a t t e r n > < / s e r v l e t m a p p i n g > . . .

IfyouuseanotherdeploymentoptionsandyouhaveaccessibleinstanceofResourceConfigwhichyouuseforconfiguration,youcanregisterprogrammatic resourcesdirectlybyr e g i s t e r R e s o u r c e s ( ) methodcalledontheResourceConfig.PleasenotethatthemethodregisterResources()replacesallthe

previouslyregisteredresources. BecauseJerseyprogrammaticAPIisnotastandardJAXRSfeaturetheR e s o u r c e C o n f i g mustbeusedtoregisterprogrammaticresourcesasshownabove. Seedeploymentchapterformoreinformation.

12.3.Additionalexamples
Example12.4.Aprogrammaticresource
1 2 3 4 5 6 7 8 9 f i n a l R e s o u r c e . B u i l d e r r e s o u r c e B u i l d e r = R e s o u r c e . b u i l d e r ( H e l l o W o r l d R e s o u r c e . c l a s s ) r e s o u r c e B u i l d e r . a d d M e t h o d ( " O P T I O N S " ) . h a n d l e d B y ( n e w I n f l e c t o r < C o n t a i n e r R e q u e s t C o n t e x t , R e s p o n s e > ( ) { @ O v e r r i d e p u b l i c R e s p o n s e a p p l y ( C o n t a i n e r R e q u e s t C o n t e x t c o n t a i n e r R e q u e s t C o n t e x t ) { r e t u r n R e s p o n s e . o k ( " T h i s i s a r e s p o n s e t o a n O P T I O N S m e t h o d . " ) . b u i l d ( ) } } ) f i n a l R e s o u r c e r e s o u r c e = r e s o u r c e B u i l d e r . b u i l d ( )

IntheexampleabovetheR e s o u r c e isbuiltfromaH e l l o W o r l d R e s o u r c e resourceclass.TheresourcemodelbuiltthiswaycontainsaG E T methodproducing ' t e x t / p l a i n ' responseswith"HelloWorld!"entity.ThisisquiteimportantasitallowsyoutowhateverResourceobjectsbasedonintrospectingexistingJAX RSresourcesandusebuilderAPItoenhancesuchthesestandardresources.IntheexampleweusedalreadyimplementedH e l l o W o r l d R e s o u r c e resource classandenhanceditbyO P T I O N S method.TheO P T I O N S methodishandledbyanInflectorwhichreturnsResponse. Thefollowingsampleshowshowtodefinesubresourcemethods(methodsthatcontainssubpath). Example12.5.Aprogrammaticresource
1 2 3 4 5 6 f i n a l R e s o u r c e . B u i l d e r r e s o u r c e B u i l d e r = R e s o u r c e . b u i l d e r ( " h e l l o w o r l d " ) f i n a l R e s o u r c e . B u i l d e r c h i l d R e s o u r c e = r e s o u r c e B u i l d e r . a d d C h i l d R e s o u r c e ( " s u b r e s o u r c e " ) c h i l d R e s o u r c e . a d d M e t h o d ( " G E T " ) . h a n d l e d B y ( n e w G e t I n f l e c t o r ( ) ) f i n a l R e s o u r c e r e s o u r c e = r e s o u r c e B u i l d e r . b u i l d ( )

Subresourcemethodsaredefinedusingsocalledchildresourcemodels.Childresourcemodels(orchildresources)areprogrammaticresourcesbuildinthe samewayasanyotherprogrammaticresourcebuttheyareregisteredasachildresourceofaparentresource.Thechildresourceintheexampleisbuild directlyfromtheparentbuilderusingmethoda d d C h i l d R e s o u r c e ( S t r i n g p a t h ) .However,thereisalsoanoptiontobuildachildresourcemodelseparately asastandardresourceandthenadditasachildresourcetoaselectedparentresource.Thismeansthatchildresourceobjectscanbereusedtodefinechild resourcesindifferentparentresources(youjustbuildasinglechildresourceandthenregisteritinmultipleparentresources).Eachchildresourcegroups methodswiththesamesubresourcepath.Notethatachildresourcecannothaveanychildresourcesasthereisnothinglikesubsubresourcemethod conceptinJAXRS.Forexampleifasubresourcemethodcontainsmorepathsegmentsinitspath(e.g."/root/sub/resource/method"where"root"isapathof theresourceand"sub/resource/method"isthesubresourcemethodpath)thenparentresourcewillhavepath"root"andchildresourcewillhavepath "sub/resource/method"(so,therewillnotbeanyseparatenestedsubresourcesfor"sub","resource"and"method"). SeethejavadocsoftheresourcebuilderAPIformoreinformation.

12.4.Modelprocessors
Jerseygivesyouanoptiontoregistersocalledmodelprocessorproviders.Theseprovidersareabletomodifyorenhancetheapplicationresourcemodel duringapplicationdeployment.Thisisanadvancedfeatureandwillnotbeneededinmostusecases.However,imagineyouwouldliketoaddO P T I O N S resourcemethodtoeachdeployedresourceasitisdescribedatthetopofthischapter.Youwouldwanttodoitforeveryprogrammaticresourcethatis registeredaswellasforallstandardJAXRSresources. Todothat,youfirstneedtoregisteramodelprocessorproviderinyourapplication,whichimplements o r g . g l a s s f i s h . j e r s e y . s e r v e r . m o d e l . M o d e l P r o c e s s o r extensioncontract.Anexampleofamodelprocessorimplementationisshownhere: Example12.6.Aprogrammaticresource
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 i m p o r t j a v a x . w s . r s . G E T i m p o r t j a v a x . w s . r s . P a t h i m p o r t j a v a x . w s . r s . P r o d u c e s i m p o r t j a v a x . w s . r s . c o n t a i n e r . C o n t a i n e r R e q u e s t C o n t e x t i m p o r t j a v a x . w s . r s . c o r e . A p p l i c a t i o n i m p o r t j a v a x . w s . r s . c o r e . C o n f i g u r a t i o n i m p o r t j a v a x . w s . r s . c o r e . M e d i a T y p e i m p o r t j a v a x . w s . r s . c o r e . R e s p o n s e i m p o r t j a v a x . w s . r s . e x t . P r o v i d e r i m p o r t o r g . g l a s s f i s h . j e r s e y . p r o c e s s . I n f l e c t o r i m p o r t o r g . g l a s s f i s h . j e r s e y . s e r v e r . m o d e l . M o d e l P r o c e s s o r i m p o r t o r g . g l a s s f i s h . j e r s e y . s e r v e r . m o d e l . R e s o u r c e i m p o r t o r g . g l a s s f i s h . j e r s e y . s e r v e r . m o d e l . R e s o u r c e M e t h o d i m p o r t o r g . g l a s s f i s h . j e r s e y . s e r v e r . m o d e l . R e s o u r c e M o d e l @ P r o v i d e r p u b l i c s t a t i c c l a s s M y O p t i o n s M o d e l P r o c e s s o r i m p l e m e n t s M o d e l P r o c e s s o r { @ O v e r r i d e p u b l i c R e s o u r c e M o d e l p r o c e s s R e s o u r c e M o d e l ( R e s o u r c e M o d e l r e s o u r c e M o d e l , C o n f i g u r a t i o n c o n f i g u r a t i o n ) { / / w e g e t t h e r e s o u r c e m o d e l a n d w e w a n t t o e n h a n c e e a c h r e s o u r c e b y O P T I O N S m e t h o d R e s o u r c e M o d e l . B u i l d e r n e w R e s o u r c e M o d e l B u i l d e r = n e w R e s o u r c e M o d e l . B u i l d e r ( f a l s e ) f o r ( f i n a l R e s o u r c e r e s o u r c e : r e s o u r c e M o d e l . g e t R e s o u r c e s ( ) ) { / / f o r e a c h r e s o u r c e i n t h e r e s o u r c e m o d e l w e c r e a t e a n e w b u i l d e r w h i c h i s b a s e d o n t h e o l d r e s o u r c e f i n a l R e s o u r c e . B u i l d e r r e s o u r c e B u i l d e r = R e s o u r c e . b u i l d e r ( r e s o u r c e ) / / w e a d d a n e w O P T I O N S m e t h o d t o e a c h r e s o u r c e / / n o t e t h a t w e s h o u l d c h e c k w h e t h e r t h e m e t h o d d o e s n o t y e t e x i s t t o a v o i d f a i l u r e s r e s o u r c e B u i l d e r . a d d M e t h o d ( " O P T I O N S " ) . h a n d l e d B y ( n e w I n f l e c t o r < C o n t a i n e r R e q u e s t C o n t e x t , S t r i n g > ( ) { @ O v e r r i d e p u b l i c S t r i n g a p p l y ( C o n t a i n e r R e q u e s t C o n t e x t c o n t a i n e r R e q u e s t C o n t e x t ) { r e t u r n " O n t h i s p a t h t h e r e s o u r c e w i t h " + r e s o u r c e . g e t R e s o u r c e M e t h o d s ( ) . s i z e ( ) + " m e t h o d s i s d e p l o y e d . " } } ) . p r o d u c e s ( M e d i a T y p e . T E X T _ P L A I N ) / / w e a d d t o t h e m o d e l n e w r e s o u r c e w h i c h i s a c o m b i n a t i o n o f t h e o l d r e s o u r c e e n h a n c e d / / b y t h e O P T I O N S m e t h o d n e w R e s o u r c e M o d e l B u i l d e r . a d d R e s o u r c e ( r e s o u r c e B u i l d e r . b u i l d ( ) ) }

4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4

f i n a l R e s o u r c e M o d e l n e w R e s o u r c e M o d e l = n e w R e s o u r c e M o d e l B u i l d e r . b u i l d ( ) / / a n d w e r e t u r n n e w m o d e l r e t u r n n e w R e s o u r c e M o d e l } @ O v e r r i d e p u b l i c R e s o u r c e M o d e l p r o c e s s S u b R e s o u r c e ( R e s o u r c e M o d e l s u b R e s o u r c e M o d e l , C o n f i g u r a t i o n c o n f i g u r a t i o n ) { / / w e j u s t r e t u r n t h e o r i g i n a l s u b R e s o u r c e M o d e l w h i c h m e a n s w e d o n o t w a n t t o d o a n y m o d i f i c a t i o n r e t u r n s u b R e s o u r c e M o d e l } }

TheM y O p t i o n s M o d e l P r o c e s s o r fromtheexampleisarelativelysimplemodelprocessorwhichiteratesoverallregisteredresourcesandforallofthem buildsanewresourcethatisequaltotheoldresourceexceptitisenhancedwithanewO P T I O N S method. NotethatyouonlyneedtoregistersuchaModelProcessorasyourcustomextensionproviderinthesamewayasyouwouldregisteranystandardJAXRS extensionprovider.Duringanapplicationdeployment,Jerseywilllookforanyregisteredmodelprocessorandexecutethem.Asyoucanseem,model processorsareverypowerfulastheycandowhatevermanipulationwiththeresourcemodeltheylike.Amodelprocessorcaneven,forexample,completely ignoretheoldresourcemodelandreturnanewcustomresourcemodelwithasingle"Helloworld!"resource,whichwouldresultinonlythe"Helloworld!" resourcebeingdeployedinyourapplication.Ofcourse,itwouldnotnotmakemuchsensetoimplementsuchmodelprocessor,butthescenario demonstrateshowpowerfulthemodelprocessorconceptis.Abetter,reallifeusecasescenariowould,forexample,betoalwaysaddsomecustomnew resourcetoeachapplicationthatmightreturnadditionalmetadataaboutthedeployedapplication.Or,youmightwanttofilteroutparticularresourcesor resourcemethods,whichisanothersituationwhereamodelprocessorcouldbeusedsuccessfully. Alsonotethatp r o c e s s S u b R e s o u r c e ( R e s o u r c e M o d e l s u b R e s o u r c e M o d e l , C o n f i g u r a t i o n c o n f i g u r a t i o n ) methodisexecutedforeachsubresource returnedfromthesubresourcelocator.Theexampleissimplifiedanddoesnotdoanymanipulationbutprobablyinsuchacaseyouwouldwanttoenhance allsubresourceswithanewO P T I O N S methodhandlerstoo. Itisimportanttorememberthatanymodelprocessormustalwaysreturnvalidresourcemodel.Asyoumighthavealreadynoticed,intheexampleabovethis importantruleisnotfollowed.IfanyoftheresourcesintheoriginalresourcemodelwouldalreadyhaveanO P T I O N S methodhandlerdefined,addinganother handlerwouldcausetheapplicationfailduringthedeploymentintheresourcemodelvalidationphase.Inordertoretaintheconsistencyofthefinalmodel,a modelprocessorimplementationwouldhavetobemorerobustthanwhatisshownintheexample.

Chapter13.ServerSentEvents(SSE)Support
TableofContents 13.1.WhatareServerSentEvents 13.2.WhentouseServerSentEvents 13.3.JerseyServerSentEventsAPI 13.4.ImplementingSSEsupportinaJAXRSresource 13.4.1.SimpleSSEresourcemethod 13.4.2.BroadcastingwithJerseySSE 13.5.ConsumingSSEeventswithJerseyclients 13.5.1.ReadingSSEeventswithE v e n t I n p u t 13.5.2.AsynchronousSSEprocessingwithE v e n t S o u r c e

13.1.WhatareServerSentEvents
InastandardHTTPrequestresponsescenarioaclientopensaconnection,sendsaHTTPrequesttotheserver(forexampleaHTTPG E T request),then receivesaHTTPresponsebackandtheserverclosestheconnectiononcetheresponseisfullysent/received.Theinitiativealwayscomesfromaclientwhen theclientrequestsallthedata.Incontrast,ServerSentEvents(SSE)isamechanismthatallowsservertoasynchronouslypushthedatafromtheserverto theclientoncetheclientserverconnectionisestablishedbytheclient.Oncetheconnectionisestablishedbytheclient,itistheserverwhoprovidesthedata anddecidestosendittotheclientwhenevernew"chunk"ofdataisavailable.Whenanewdataeventoccursontheserver,thedataeventissentbythe servertotheclient.ThusthenameServerSentEvents.Notethatathighleveltherearemoretechnologiesworkingonthisprinciple,ashortoverviewofthe technologiessupportingservertoclientcommunicationisinthislist: Polling Withpollingaclientrepeatedlysendsnewrequeststoaserver.Iftheserverhasnonewdata,thenitsendappropriateindicationandclosesthe connection.Theclientthenwaitsabitandsendsanotherrequestaftersometime(afteronesecond,forexample). Longpolling Withlongpollingaclientsendsarequesttoaserver.Iftheserverhasnonewdata,itjustholdstheconnectionopenandwaitsuntildataisavailable. Oncetheserverhasdata(message)fortheclient,itusestheconnectionandsendsitbacktotheclient.Thentheconnectionisclosed. ServerSentevents SSEissimilartothelongpollingmechanism,exceptitdoesnotsendonlyonemessageperconnection.Theclientsendsarequestandserverholdsa connectionuntilanewmessageisready,thenitsendsthemessagebacktotheclientwhilestillkeepingtheconnectionopensothatitcanbeusedfor anothermessageonceitbecomesavailable.Onceanewmessageisready,itissentbacktotheclientonthesameinitialconnection.Clientprocesses themessagessentbackfromtheserverindividuallywithoutclosingtheconnectionafterprocessingeachmessage.So,SSEtypicallyreusesone connectionformoremessages(calledevents).SSEalsodefinesadedicatedmediatypethatdescribesasimpleformatofindividualevnetssentfrom theservertotheclient.SSEalsooffersstandardjavascriptclientAPIimplementedmostmodernbrowsers.FormoreinformationaboutSSE,seethe SSEAPIspecification. WebSocket WebSockettechnologyisdifferentfromprevioustechnologiesasitprovidesarealfullduplexconnection.Theinitiatorisagainaclientwhichsendsa requesttoaserverwithaspecialHTTPheaderthatinformstheserverthattheHTTPconnectionmaybe"upgraded"toafullduplexTCP/IPWebSocket connection.IfserversupportsWebSocket,itmaychoosetodoso.OnceaWebSocketconnectionisestablished,itcanbeusedforbidirectional communicationbetweentheclientandtheserver.Bothclientandservercanthensenddatatotheotherpartyatwillwheneveritisneeded.The communicationonthenewWebSocketconnectionisnolongerbasedonHTTPprotocolandcanbeusedforexampleforforonlinegamingorany otherapplicationsthatrequirefastexchangeofsmallchunksofdatainflowinginbothdirections.

13.2.WhentouseServerSentEvents
Asexplainedabove,SSEisatechnologythatallowsclientstosubscribetoeventnotificationsthatoriginateonaserver.Servergeneratesneweventsand sendstheseeventsbacktotheclientssubscribedtoreceivethenotifications.Inotherwords,SSEoffersasolutionforaonewaypublishsubscribemodel. AgoodexampleoftheusecasewhereSSEcanbeusedisasimplemessageexchangeRESTfulservice.ClientsP O S T newmessagestotheserviceand subscribetoreceivemessagesfromotherclients.Let'scalltheresourcem e s s a g e s .WhileP O S T inganewmessagetothisresourceinvolvesatypicalHTTP requestresponsecommunicationbetweenaclientandthem e s s a g e s resource,subscribingtoreceiveallnewmessagenotificationswouldbehardand impracticaltomodelwithasequenceofstandardrequestresponsemessageexchanges.UsingServersenteventsprovidesamuchmorepracticalapproach here.YoucanuseSSEtoletclientssubscribetothem e s s a g e s resourceviastandardG E T request(useaSSEclientAPI,forexamplejavascriptAPIorJersey ClientSSEAPI)andlettheserverbroadcastnewmessagestoallconnectedclientsintheformofindividualevents(inourcaseusingJerseyServerSSEAPI). NotethatwithJerseyaSSEsupportisimplementedasanusualJAXRSresourcemethod.There'snoneedtodoanythingspecialtoprovideaSSEsupport

inyourJersey/JAXRSapplications,yourSSEenabledresourcesareastandardpartofyourRESTfulWebapplicationthatdefinestheRESTAPIofyour application.ThefollowingchaptersdescribesSSEsupportinJerseyinmoredetails.

Important
Note,thatwhileSSEinJerseyissupportedwithstandardJAXRSresources,JerseySSEAPIsarenotpartoftheJAXRSspecification.SSE supportandrelatedAPIsareaJerseyspecificfeaturethatextendsJAXRS.

13.3.JerseyServerSentEventsAPI
ThischapterbrieflydescribestheJerseysupportforSSE.Detailsandexampleswillbecoveredinchaptersbelow. JerseycontainssupportforSSEforbothserverandclient.SSEinJerseyisimplementedasanextensionsupportinganewmediatype,whichmeansthat SSEreallytreatedasjustanothermediatypethatcanbereturnedfromaresourcemethodandprocessedbytheclient.Thereisonlyaminimaladditional supportfor"chunked"messagesaddedtoJerseywhichcouldnotbeimplementedasstandardJAXRSmediatypeextension. BeforeyoustartworkingwithJerseySSE,inordertoaddsupportforSSEyouneedtoincludethedependencytotheSSEmediatypemodule:
1 2 3 4 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . m e d i a < / g r o u p I d > < a r t i f a c t I d > j e r s e y m e d i a s s e < / a r t i f a c t I d > < / d e p e n d e n c y >

ThenyouneedregisterSseFeature.TheS s e F e a t u r e isafeaturethatcanberegisteredforboth,theclientandtheserver.
S s e F e a t u r e addsnewsupportedentity(representation)Javatypes,namelyOutboundEventfortheoutboundservereventsandInboundEventforinbound

clientevents.ThesetypesareserializedbyOutboundEventWriteranddeserializedbyInboundEventReader.Thereisnorestrictionforamediatypeusedin individualeventmessageshoweverthemediatypeusedforaSSEstreamaswholeis"text/eventstream"andthismediatypeshouldbesetonmessages thatareusedtoserveSSEevents(forexampleontheserversideusing@ProducesonthemethodthatreturnsanE v e n t O u t p u t seebellow).The I n b o u n d E v e n t andO u t b o u n d E v e n t containallthefieldsneededforcomposingandprocessingindividualSSEevents.Theseentitiesrepresentthechunks sentorreceivedoveranopenservertoclientconnectionthatisrepresentedbyanChunkedOutputontheserverssideandChunkedInputontheclientside (ifyouarenotfamiliarwithC h u n k e d O u t p u t andC h u n k e d I n p u t ,seetheAsyncchapterfirstformoredetails).Inotherwords,ourresourcemethodthatis usedtoopenaSSEconnectiontoaclientdoesnotreturnindividualO u t b o u n d E v e n t s.Instead,anewinstanceofEventOutputisreturned.E v e n t O u t p u t isa typedextensionofC h u n k e d O u t p u t < O u t b o u n d E v e n t > .Similarly,toreceiveI n b o u n d E v e n t sonaclientside,JerseySSEAPIprovidesaE v e n t I n p u t that representsatypedextensionofC h u n k e d I n p u t < I n b o u n d E v e n t > . TheJerseyserverSSEAPIalsocontainsaSseBroadcasterutility,thatprovidesaconvenientwayofgroupingmultipleE v e n t O u t p u t instancesthatrepresent individualclientconnectionsintoagroup,andexposesmethodsforbroadcastingneweventstoalltheclientconnectionsgroupedinthebroadcaster.The S s e B r o a d c a s t e r inheritsfromBroadcasterwhichisthegenericbroadcasterimplementationoftheJerseychunkedmessageprocessingfacility.Onthehe clientside,theJerseySSEAPIcontainsadditionalEventSourceandEventListenerclassesthatfurtherimproveconvenienceofprocessingnewinboundSSE events.

13.4.ImplementingSSEsupportinaJAXRSresource
13.4.1.SimpleSSEresourcemethod
FirstlyyouneedtoaddaJerseySSEmoduledependencytoyourprojectasshownintheearliersectionandregistertheSseFeaturefromthismoduleinyour ApplicationorResourceConfig.Oncedone,youarereadytoaddSSEsupporttoyourresource: Example13.1.SimpleSSEresourcemethod
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 . . . i m p o r t o r g . g l a s s f i s h . j e r s e y . m e d i a . s s e . E v e n t O u t p u t i m p o r t o r g . g l a s s f i s h . j e r s e y . m e d i a . s s e . O u t b o u n d E v e n t i m p o r t o r g . g l a s s f i s h . j e r s e y . m e d i a . s s e . S s e F e a t u r e . . . @ P a t h ( " e v e n t s " ) p u b l i c s t a t i c c l a s s S s e R e s o u r c e { @ G E T @ P r o d u c e s ( S s e F e a t u r e . S E R V E R _ S E N T _ E V E N T S ) p u b l i c E v e n t O u t p u t g e t S e r v e r S e n t E v e n t s ( ) { f i n a l E v e n t O u t p u t e v e n t O u t p u t = n e w E v e n t O u t p u t ( ) n e w T h r e a d ( n e w R u n n a b l e ( ) { @ O v e r r i d e p u b l i c v o i d r u n ( ) { t r y { f o r ( i n t i = 0 i < 1 0 i + + ) { / / . . . c o d e t h a t w a i t s 1 s e c o n d f i n a l O u t b o u n d E v e n t . B u i l d e r e v e n t B u i l d e r = n e w O u t b o u n d E v e n t . B u i l d e r ( ) e v e n t B u i l d e r . n a m e ( " m e s s a g e t o c l i e n t " ) e v e n t B u i l d e r . d a t a ( S t r i n g . c l a s s , " H e l l o w o r l d " + i + " ! " ) f i n a l O u t b o u n d E v e n t e v e n t = e v e n t B u i l d e r . b u i l d ( ) e v e n t O u t p u t . w r i t e ( e v e n t ) } } c a t c h ( I O E x c e p t i o n e ) { t h r o w n e w R u n t i m e E x c e p t i o n ( " E r r o r w h e n w r i t i n g t h e e v e n t . " , e ) } f i n a l l y { t r y { e v e n t O u t p u t . c l o s e ( ) } c a t c h ( I O E x c e p t i o n i o C l o s e ) { t h r o w n e w R u n t i m e E x c e p t i o n ( " E r r o r w h e n c l o s i n g t h e e v e n t o u t p u t . " , i o C l o s e ) } } } } ) . s t a r t ( ) r e t u r n e v e n t O u t p u t } }

ThecodeabovedefinestheresourcedeployedonURI" / e v e n t s " .Thisresourcehasasingle@GETresourcemethodwhichreturnsasanentity EventOutputanextensionofgenericJerseyChunkedOutputAPIforoutputchunkedmessageprocessing.

Note
IfyouarenotfamiliarwithC h u n k e d O u t p u t andC h u n k e d I n p u t ,seetheAsyncchapterfirstformoredetails.

Afterthee v e n t O u t p u t isreturnedfromthemethod,theJerseyruntimerecognizesthatthisisaC h u n k e d O u t p u t extensionanddoesnotclosetheclient connectionimmediately.Instead,itwritestheHTTPheaderstotheresponsestreamandwaitsformorechunks(SSEevents)tobesent.Atthispointtheclient canreadheadersandstartslisteningforindividualevents.

Note
SinceJerseyruntimedoesnotimplicitlyclosetheconnectiontotheclient(similarlytoasynchronousprocessing),closingtheconnectionisa responsibilityoftheresourcemethodortheclientlisteningontheopenconnectionfornewevents(seefollowingexample). IntheExample13.1,SimpleSSEresourcemethod,theresourcemethodcreatesanewthreadthatsendsasequenceof10events.Thereisa1second delaybetweentwosubsequenteventsasindicatedinacomment.EacheventisrepresentedbyO u t b o u n d E v e n t typeandisbuiltwithahelpfofanoutbound eventB u i l d e r .TheO u t b o u n d E v e n t reflectsthestandardizedformatofSSEmessagesandcontainspropertiesthatrepresentn a m e (fornamedevents), c o m m e n t ,d a t a ori d .Thecodealsosetstheeventdatamediatypeusingthem e d i a T y p e ( M e d i a T y p e ) methodonthee v e n t B u i l d e r .Themediatype, togetherwiththedatatypesetbythed a t a ( C l a s s , O b j e c t > method(inourcaseS t r i n g . c l a s s ),isusedforserializationoftheeventdata.Notethatthe eventdatamediatypewillnotbewrittentoanyheadersastheresponseC o n t e n t t y p e headerisalreadydefinedbythe@ P r o d u c e s andsetto " t e x t / e v e n t s t r e a m " usingconstantfromtheS s e F e a t u r e .Theeventmediatypeisusedforserializationofeventd a t a .EventdatamediatypeandJava typeareusedtoselecttheproperMessageBodyWriter<T>foreventdataserializationandarepassedtotheselectedwriterthatserializestheeventd a t a content.Inourcasethestring" H e l l o w o r l d " + i + " ! " isserializedas" t e x t / p l a i n " .Ineventd a t a youcansendanyJavaentityandassociateitwith anymediatypethatyouwouldbeabletoserializewithanavailableM e s s a g e B o d y W r i t e r < T > .Typically,youmaywanttosende.g.JSONdata,soyouwould fillthed a t a withaJAXBannotatedbeaninstanceanddefinemediatypetoJSON.

Note
Iftheeventmediatypeisnotsetexplicitly,the" t e x t / p l a i n " mediatypeisusedbydefault. Onceanoutboundeventisready,itcanbewrittentothee v e n t O u t p u t .AtthatpointtheeventisserializedbyinternalO u t b o u n d E v e n t W r i t e r whichusesan appropriateM e s s a g e B o d y W r i t e r < T > toserializethe" H e l l o w o r l d " + i + " ! " string.Youcansendasmanymessagesasyoulike.Attheendofthe threadexecutiontheresponseisclosedwhichalsoclosestheconnectiontotheclient.Afterthat,nomoremessagescanbesendtotheclientonthis connection.Iftheclientwouldliketoreceivemoremessages,itwouldhavetosendanewrequesttotheservertoinitiateanewSSEstreamingconnection. AclientconnectingtoourSSEenabledresourcewillreceivethefollowingdatafromtheentitystream:
e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 0 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 1 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 2 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 3 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 4 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 5 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 6 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 7 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 8 ! e v e n t : m e s s a g e t o c l i e n t d a t a : H e l l o w o r l d 9 !

Eachmessageisreceivedwithadelayofonesecond.

13.4.2.BroadcastingwithJerseySSE
JerseySSEserverAPIdefinesSseBroadcasterwhichallowstobroadcastindividualeventstomultipleclients.Asimplebroadcastingimplementationisshown inthefollowingexample: Example13.2.BroadcastingSSEmessages
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 . . . i m p o r t o r g . g l a s s f i s h . j e r s e y . m e d i a . s s e . S s e B r o a d c a s t e r . . . @ S i n g l e t o n @ P a t h ( " b r o a d c a s t " ) p u b l i c s t a t i c c l a s s B r o a d c a s t e r R e s o u r c e { p r i v a t e S s e B r o a d c a s t e r b r o a d c a s t e r = n e w S s e B r o a d c a s t e r ( ) @ P O S T @ P r o d u c e s ( M e d i a T y p e . T E X T _ P L A I N ) @ C o n s u m e s ( M e d i a T y p e . T E X T _ P L A I N ) p u b l i c S t r i n g b r o a d c a s t M e s s a g e ( S t r i n g m e s s a g e ) { O u t b o u n d E v e n t . B u i l d e r e v e n t B u i l d e r = n e w O u t b o u n d E v e n t . B u i l d e r ( ) O u t b o u n d E v e n t e v e n t = e v e n t B u i l d e r . n a m e ( " m e s s a g e " ) . m e d i a T y p e ( M e d i a T y p e . T E X T _ P L A I N _ T Y P E ) . d a t a ( S t r i n g . c l a s s , m e s s a g e ) . b u i l d ( ) b r o a d c a s t e r . b r o a d c a s t ( e v e n t ) r e t u r n " M e s s a g e w a s ' " + m e s s a g e + " ' b r o a d c a s t . " } @ G E T @ P r o d u c e s ( S s e F e a t u r e . S E R V E R _ S E N T _ E V E N T S ) p u b l i c E v e n t O u t p u t l i s t e n T o B r o a d c a s t ( ) { f i n a l E v e n t O u t p u t e v e n t O u t p u t = n e w E v e n t O u t p u t ( ) t h i s . b r o a d c a s t e r . a d d ( e v e n t O u t p u t ) r e t u r n e v e n t O u t p u t }

3 3

Let'sexploretheexampletogether.TheB r o a d c a s t e r R e s o u r c e resourceclassisannotatedwith@SingletonannotationwhichtellsJerseyruntimethatonly asingleinstanceoftheresourceclassshouldbeusedtoservealltheincomingrequeststo/ b r o a d c a s t path.Thisisneededaswewanttokeepan applicationwidesinglereferencetotheprivateb r o a d c a s t e r fieldsothatwecanusethesameinstanceforallrequests.ClientsthatwanttolistentoSSE eventsfirstsendaG E T requesttotheB r o a d c a s t e r R e s o u r c e ,thatishandledbythel i s t e n T o B r o a d c a s t ( ) resourcemethod.Themethodcreatesanew E v e n t O u t p u t representingtheconnectiontotherequestingclientandregistersthise v e n t O u t p u t instancewiththesingletonb r o a d c a s t e r ,usingits a d d ( E v e n t O u t p u t ) method.Themethodthenreturnsthee v e n t O u t p u t whichcausesJerseytobindthee v e n t O u t p u t instancewiththerequestingclient andsendtheresponseHTTPheaderstotheclient.TheclientconnectionremainsopenandtheclientisnowwaitingreadytoreceivenewSSEevents.Allthe eventsarewrittentothee v e n t O u t p u t byb r o a d c a s t e r lateron.Thiswaydeveloperscanconvenientlyhandlesendingneweventstoalltheclientsthat subscribetothem. WhenaclientwantstobroadcastnewmessagetoalltheclientslisteningontheirSSEconnections,itsendsaP O S T requesttoB r o a d c a s t e r R e s o u r c e resourcewiththemessagecontent.Themethodb r o a d c a s t M e s s a g e ( S t r i n g ) isinvokedonB r o a d c a s t e r R e s o u r c e resourcewiththemessagecontentas aninputparameter.AnewSSEoutboundeventisbuiltinthestandardwayandpassedtothebroadcaster.Thebroadcasterinternallyinvokes w r i t e ( O u t b o u n d E v e n t ) onallregisteredE v e n t O u t p u t s.AfterthatthemethodjustreturnastandardtextresponsetotheP O S T ingclienttoinformtheclient thatthemessagewassuccessfullybroadcast.Asyoucansee,theb r o a d c a s t M e s s a g e ( S t r i n g ) resourcemethodisjustasimpleJAXRSresourcemethod. Inordertoimplementsuchascenario,youmayhavenoticed,thattheJerseyS s e B r o a d c a s t e r isnotmandatorytocompletetheusecase.individual EventOutputscanbejuststoredinacollectionanditeratedoverintheb r o a d c a s t M e s s a g e method.However,theS s e B r o a d c a s t e r internallyidentifiesand handlesalsoclientdisconnects.Whenaclientclosestheconnectionthebroadcasterdetectsthisandremovesthestaleconnectionfromtheinternalcollection oftheregisteredEventOutputsaswellasitfreesalltheserversideresourcesassociatedwiththestaleconnection.Additionally,theS s e B r o a d c a s t e r is implementedtobethreadsafe,sothatclientscanconnectanddisconnectinanytimeandS s e B r o a d c a s t e r willalwaysbroadcastmessagestothemost recentcollectionofregisteredandactivesetofclients.

13.5.ConsumingSSEeventswithJerseyclients
Ontheclientside,JerseyexposesAPIsthatsupportreceivingandprocessingSSEeventsusingtwoprogrammingmodels:
PullmodelpullingeventsfromaEventInput,or PushmodellisteningforasynchronousnotificationsofE v e n t S o u r c e

Bothmodelswillbedescribed.

13.5.1.ReadingSSEeventswithE v e n t I n p u t
TheeventscanbereadontheclientsidefromaEventInput.Seethefollowingcode:
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . r e g i s t e r ( S s e F e a t u r e . c l a s s ) . b u i l d ( ) W e b T a r g e t t a r g e t = c l i e n t . t a r g e t ( " h t t p : / / l o c a l h o s t : 9 9 9 8 / e v e n t s " ) E v e n t I n p u t e v e n t I n p u t = t a r g e t . r e q u e s t ( ) . g e t ( E v e n t I n p u t . c l a s s ) w h i l e ( ! e v e n t I n p u t . i s C l o s e d ( ) ) { f i n a l I n b o u n d E v e n t i n b o u n d E v e n t = e v e n t I n p u t . r e a d ( ) i f ( i n b o u n d E v e n t = = n u l l ) { / / c o n n e c t i o n h a s b e e n c l o s e d b r e a k } S y s t e m . o u t . p r i n t l n ( i n b o u n d E v e n t . g e t N a m e ( ) + " " + i n b o u n d E v e n t . r e a d D a t a ( S t r i n g . c l a s s ) ) }

Inthisexample,aclientconnectstotheserverwheretheS s e R e s o u r c e fromtheExample13.1,SimpleSSEresourcemethodisdeployed.Atfirst,anew JAXRS/Jerseyc l i e n t instanceiscreatedwithaS s e F e a t u r e registered.ThenaWebTargetinstanceisretrievedfromthec l i e n t andisusedtoinvokea HTTPrequest.ThereturnedresponseentityisdirectlyreadasaE v e n t I n p u t Javatype,whichisanextensionofJerseyC h u n k e d I n p u t thatprovidesgeneric supportforconsumingchunkedmessagepayloads.ThecodeintheexamplethenprocessstartsalooptoprocesstheinboundSSEeventsreadfromthe e v e n t I n p u t responsestream.EachchunkreadfromtheinputisaI n b o u n d E v e n t .ThemethodI n b o u n d E v e n t . r e a d D a t a ( C l a s s ) providesawayforthe clienttoindicatewhatJavatypeshouldbeusedfortheeventdatadeserialization.Inourexample,individualeventsaredeserializedasS t r i n g Javatype instances.ThismethodinternallyfindsandexecutesaproperMessageBodyReader<T>whichistheusedtodotheactualdeserialization.Thisissimilarto readinganentityfromtheResponsebyr e a d E n t i t y ( C l a s s ) .Themethodr e a d D a t a canalsothrowaProcessingException. Then u l l checkoni n b o u n d E v e n t isnecessarytomakesurethatthechunkwasproperlyreadandconnectionhasnotbeenclosedbytheserver.Oncethe connectionisclosed,theloopterminatesandtheprogramcompletesexecution.Theclientcodeproducesthefollowingconsoleoutput:
m e s s a g e t o c l i e n t H e l l o w o r l d 0 ! m e s s a g e t o c l i e n t H e l l o w o r l d 1 ! m e s s a g e t o c l i e n t H e l l o w o r l d 2 ! m e s s a g e t o c l i e n t H e l l o w o r l d 3 ! m e s s a g e t o c l i e n t H e l l o w o r l d 4 ! m e s s a g e t o c l i e n t H e l l o w o r l d 5 ! m e s s a g e t o c l i e n t H e l l o w o r l d 6 ! m e s s a g e t o c l i e n t H e l l o w o r l d 7 ! m e s s a g e t o c l i e n t H e l l o w o r l d 8 ! m e s s a g e t o c l i e n t H e l l o w o r l d 9 !

13.5.2.AsynchronousSSEprocessingwithE v e n t S o u r c e
ThemainJerseySSEclientAPIcomponentusedtoreadSSEeventsasynchronouslyisEventSource.TheusageoftheE v e n t S o u r c e isshownonthe followingexample. Example13.3.RegisteringE v e n t L i s t e n e r withE v e n t S o u r c e
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . r e g i s t e r ( S s e F e a t u r e . c l a s s ) . b u i l d ( ) W e b T a r g e t t a r g e t = c l i e n t . t a r g e t ( " h t t p : / / e x a m p l e . c o m / e v e n t s " ) E v e n t S o u r c e e v e n t S o u r c e = E v e n t S o u r c e . t a r g e t ( t a r g e t ) . b u i l d ( ) E v e n t L i s t e n e r l i s t e n e r = n e w E v e n t L i s t e n e r ( ) { @ O v e r r i d e p u b l i c v o i d o n E v e n t ( I n b o u n d E v e n t i n b o u n d E v e n t ) { S y s t e m . o u t . p r i n t l n ( i n b o u n d E v e n t . g e t N a m e ( ) + " " + i n b o u n d E v e n t . r e a d D a t a ( S t r i n g . c l a s s ) ) } } e v e n t S o u r c e . r e g i s t e r ( l i s t e n e r , " m e s s a g e t o c l i e n t " ) e v e n t S o u r c e . o p e n ( ) . . . e v e n t S o u r c e . c l o s e ( )

Inthisexample,theclientcodeagainconnectstotheserverwheretheS s e R e s o u r c e fromtheExample13.1,SimpleSSEresourcemethodisdeployed.The ClientinstanceisagaincreatedandinitializedwithSseFeature.ThentheWebTargetisbuilt.Inthiscasearequesttothewebtargetisnotmadedirectlyinthe code,instead,thewebtargetinstanceisusedtoinitializeanewEventSource.BuilderinstancethatisusedtobuildanewE v e n t S o u r c e .Thechoiceof b u i l d ( ) methodisimportant,asittellstheE v e n t S o u r c e . B u i l d e r tocreateanewE v e n t S o u r c e thatisnotautomaticallyconnectedtothet a r g e t .The connectionisestablishedonlylaterbymanuallyinvokingthee v e n t S o u r c e . o p e n ( ) method.AcustomEventListenerimplementationisusedtolistentoand processincomingSSEevents.ThemethodreadData(Class)saysthattheeventdatashouldbedeserializedfromareceivedInboundEventinstanceintoa S t r i n g Javatype.ThismethodcallinternallyexecutesMessageBodyReader<T>whichdeserializestheeventdata.Thisissimilartoreadinganentityfrom theResponsebyr e a d E n t i t y ( C l a s s ) .Themethodr e a d D a t a canthrowaProcessingException. ThecustomeventsourcelistenerisregisteredintheeventsourceviaE v e n t S o u r c e . r e g i s t e r ( E v e n t L i s t e n e r , S t r i n g ) method.Thenextmethod argumentsdefinethenamesoftheeventstoreceiveandcanbeomitted.Ifnamesaredefined,thelistenerwillbeassociatedwiththenamedeventsandwill onlyinvokedforeventswithanamefromthesetofdefinedeventnames.Itwillnotbeinvokedforeventswithanyothernameorforeventswithoutaname.

Important
Itisacommonmistaketothinkthatunnamedeventswillbeprocessedbylistenersthatareregisteredtoprocesseventsfromaparticular nameset.ThatisNOTthecase!Unnamedeventsareonlyprocessedbylistenersthatarenotnamebound.Thesamelimitationappliedto HTML5JavascriptSSEClientAPIsupportedbymodernbrowsers. Afteraconnectiontotheserverisopenedbycallingtheo p e n ( ) methodontheeventsource,thee v e n t S o u r c e startslisteningtoevents.Whenanevent named" m e s s a g e t o c l i e n t " comes,thelistenerwillbeexecutedbytheeventsource.Ifanyothereventcomes(withanamedifferentfrom" m e s s a g e t o c l i e n t " ),theregisteredlistenerisnotinvoked.Oncetheclientisdonewithprocessinganddoesnotwanttoreceiveeventsanymore,itclosesthe connectionbycallingthec l o s e ( ) methodontheeventsource. Thelistenerfromtheexampleabovewillprintthefollowingoutput:
m e s s a g e t o c l i e n t H e l l o w o r l d 0 ! m e s s a g e t o c l i e n t H e l l o w o r l d 1 ! m e s s a g e t o c l i e n t H e l l o w o r l d 2 ! m e s s a g e t o c l i e n t H e l l o w o r l d 3 ! m e s s a g e t o c l i e n t H e l l o w o r l d 4 ! m e s s a g e t o c l i e n t H e l l o w o r l d 5 ! m e s s a g e t o c l i e n t H e l l o w o r l d 6 ! m e s s a g e t o c l i e n t H e l l o w o r l d 7 ! m e s s a g e t o c l i e n t H e l l o w o r l d 8 ! m e s s a g e t o c l i e n t H e l l o w o r l d 9 !

WhenbrowsingthroughtheJerseySSEAPIdocumentation,youmayhavenoticedthattheEventSourceimplementsEventListenerandprovidesanempty implementationfortheo n E v e n t ( I n b o u n d E v e n t i n b o u n d E v e n t ) listenermethod.ThisaddsmoreflexibilitytotheJerseyclientsideSSEAPI.Insteadof definingandregisteringaseparateeventlistener,insimplescenariosyoucanalsochoosetoderivedirectlyfromtheE v e n t S o u r c e andoverridetheempty listenermethodtohandletheincomingevents.Thisprogrammingmodelisshowninthefollowingexample: Example13.4.OverridingE v e n t S o u r c e . o n E v e n t ( I n b o u n d E v e n t ) method


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . r e g i s t e r ( S s e F e a t u r e . c l a s s ) . b u i l d ( ) W e b T a r g e t t a r g e t = c l i e n t . t a r g e t ( " h t t p : / / e x a m p l e . c o m / e v e n t s " ) E v e n t S o u r c e e v e n t S o u r c e = n e w E v e n t S o u r c e ( t a r g e t ) { @ O v e r r i d e p u b l i c v o i d o n E v e n t ( I n b o u n d E v e n t i n b o u n d E v e n t ) { i f ( " m e s s a g e t o c l i e n t " . e q u a l s ( i n b o u n d E v e n t . g e t N a m e ( ) ) ) { S y s t e m . o u t . p r i n t l n ( i n b o u n d E v e n t . g e t N a m e ( ) + " " + i n b o u n d E v e n t . r e a d D a t a ( S t r i n g . c l a s s ) ) } } } . . . e v e n t S o u r c e . c l o s e ( )

ThecodeaboveisverysimilartothecodeinExample13.3,RegisteringE v e n t L i s t e n e r withE v e n t S o u r c e .Inthisexamplehowever,theE v e n t S o u r c e is constructeddirectlyusingasingleparameterconstructor.Thisway,theconnectiontotheSSEendpointisbydefaultautomaticallyopenedattheeventsource creation.TheimplementationoftheE v e n t L i s t e n e r hasbeenmovedintotheoverriddenE v e n t S o u r c e . o n E v e n t ( . . . ) method.However,thistime,the listenermethodwillbeexecutedforalleventsunnamedaswellaswithanyn a m e .Thereforethecodechecksthenamewhetheritisaneventwiththename "messagetoclient"thatwewanttohandle.NotethatyoucanstillregisteradditionalE v e n t L i s t e n e r slateron.Theoverriddenmethodontheeventsource allowsyoutohandlemessagesevenwhennoadditionallistenersareregisteredyet.

13.5.2.1.E v e n t S o u r c e reconnectsupport
StartinginJersey2.3,theE v e n t S o u r c e implementationsupportsautomatedrecuperationfromaconnectionloss,includingnegotiationofdeliveryofany missedeventsbasedonthelastreceivedSSEeventi d fieldvalue,providedthisfieldissetbytheserverandthenegotiationfacilityissupportedbythe server.Incaseofaconnectionloss,thelastreceivedSSEeventi d fieldvalueissendintheL a s t E v e n t I D HTTPrequestheaderaspartofanew connectionrequestsenttotheSSEendpoint.Uponareceiptofsuchreconnectrequest,theSSEendpointthatsupportsthisnegotiationfacilityisexpectedto replayallmissedevents.

Note
Note,thatSSElosteventnegotiationfacilityisabesteffortmechanismwhichdoesnotprovideanyguarantythatalleventswouldbedelivered withoutaloss.Youshouldthereforenotrelyonreceivingeverysingleeventanddesignyourclientapplicationcodeaccordingly. Bydefault,whenaconnectionthetheSSEendpointislost,theeventsourcewilluseadefaultdelaybeforeattemptingtoreconnecttotheSSEendpoint.The SSEendpointcanhowevercontroltheclientsideretrydelaybyincludingaspecialr e t r y fieldvalueintheanysendevent.JerseyE v e n t S o u r c e implementationautomaticallytracksanyreceivedSSEeventr e t r y fieldvaluessetbytheendpointandadjuststhereconnectdelayaccordingly,usingthelast receivedr e t r y fieldvalueasthenewreconnectdelay. Inadditiontohandlingthestandardconnectionlosses,JerseyE v e n t S o u r c e automaticallydealswithanyH T T P 5 0 3 S e r v i c e U n a v a i l a b l e responses receivedfromtheSSEendpoint,thatincludeaR e t r y A f t e r HTTPheaderwithavalidvalue.TheH T T P 5 0 3 + R e t r y A f t e r techniqueisoftenusedby HTTPendpointsasameansofconnectionandtrafficthrottling.IncaseaH T T P 5 0 3 + R e t r y A f t e r responseisreceivedinreturntoaconnectionrequest fromSSEendpoint,Jersey{@codeEventSource}willautomaticallyscheduleareconnectattemptandusethereceivedR e t r y A f t e r HTTPheadervalueas aonetimeoverrideofthereconnectdelay.

Chapter14.Security
TableofContents 14.1.Securingserver 14.1.1.SecurityContext 14.1.2.Authorizationsecuringresources 14.2.ClientSecurity

14.3.OAuth

14.1.Securingserver
14.1.1.SecurityContext
SecurityinformationisavailablebyinjectingaSecurityContextinstanceusing@Contextannotation,thatprovidesessentiallytheequivalentofthefunctionality availableonHttpServletRequestAPI.TheinjectedsecuritycontextdependsontheactualJerseyapplicationdeployment.Forexample,ifaJerseyapplication isdeployedinaServletcontainer,theJerseyS e c u r i t y C o n t e x t willreturninformationofthesecuritycontextretrievedfromServletrequest.ForJersey applicationsdeployedonaGrizzlyserver,theS e c u r i t y C o n t e x t willreturninformationretrievedfromtheGrizzlyrequest.
S e c u r i t y C o n t e x t canbeusedinconjunctionwithsubresourcelocatorstoreturndifferentresourcesiftheuserprincipleisincludedinacertainrole.For

example,asubresourcelocatorcouldreturnadifferentresourceifauserisapreferredcustomer: Example14.1.AccessingS e c u r i t y C o n t e x t
1 2 3 4 5 6 7 8 @ P a t h ( " b a s k e t " ) p u b l i c S h o p p i n g B a s k e t R e s o u r c e g e t ( @ C o n t e x t S e c u r i t y C o n t e x t s c ) { i f ( s c . i s U s e r I n R o l e ( " P r e f e r r e d C u s t o m e r " ) { r e t u r n n e w P r e f e r r e d C u s t o m e r S h o p p i n g B a s k e t R e s o u r c e ( ) } e l s e { r e t u r n n e w S h o p p i n g B a s k e t R e s o u r c e ( ) } }

S e c u r i t y C o n t e x t canbeinjectedalsotosingletonresourcesandprovidersasaclassfield.InsuchcasetheproxyoftherequestscopedS e c u r i t y C o n t e x t

willbeinjected. Example14.2.InjectingS e c u r i t y C o n t e x t intoasingletonresource


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 @ P a t h ( " r e s o u r c e " ) @ S i n g l e t o n p u b l i c s t a t i c c l a s s M y R e s o u r c e { @ C o n t e x t / / J e r s e y w i l l i n j e c t p r o x y o f S e c u r i t y C o n t e x t S e c u r i t y C o n t e x t s e c u r i t y C o n t e x t @ G E T p u b l i c S t r i n g g e t U s e r P r i n c i p a l ( ) { r e t u r n s e c u r i t y C o n t e x t . g e t U s e r P r i n c i p a l ( ) . g e t N a m e ( ) } }

14.1.1.1.InitializeSecurityContextwithServlets
Asdescribedabove,theS e c u r i t y C o n t e x t bydefault(ifnotoverwrittenbyfilters)onlyoffersinformationfromanunderlyingcontainer.Inthecaseyou deployaJerseyapplicationinaServletcontainer,youneedtosetupthe< s e c u r i t y c o n s t r a i n t > ,< a u t h c o n s t r a i n t > andusertorolesmappingsin ordertopasscorrectinformationtotheS e c u r i t y C o n t e x t .

14.1.1.2.SecurityContextinContainerRequestContext
TheS e c u r i t y C o n t e x t canberetrievedalsofromContainerRequestContextviag e t S e c u r i t y C o n t e x t ( ) method.YoucanalsosettheS e c u r i t y C o n t e x t intotherequestusingmethods e t S e c u r i t y C o n t e x t ( S e c u r i t y C o n t e x t ) .IfyousetanewS e c u r i t y C o n t e x t intheContainerRequestFilterintothe C o n t a i n e r R e q u e s t C o n t e x t ,thenthissecuritycontextwillbeusedforinjectionsinresourceclasses(wrappedintotheproxy).Thiswayyoucanimplementa customauthenticationfilterthatmaysetupyourownS e c u r i t y C o n t e x t tobeused.Toensuretheearlyexecutionofyourcustomauthenticationrequestfilter, setthefilterprioritytoA U T H E N T I C A T I O N usingconstantsfromPriorities.Anearlyexecutionofyouauthenticationfilterwillensurethatallotherfilters, resources,resourcemethodsandsubresourcelocatorswillexecutewithyourcustomS e c u r i t y C o n t e x t instance.

14.1.2.Authorizationsecuringresources
14.1.2.1.Securityresourceswithw e b . x m l
IncaseswhereaJerseyapplicationisdeployedinaServletcontaineryoucanrelyonlyonthestandardJavaEEWebapplicationsecuritymechanisms offeredbytheServletcontainerandconfigurableviaapplication'sw e b . x m l descriptor.Youneedtodefinethe< s e c u r i t y c o n s t r a i n t > elementsinthe w e b . x m l andassignroleswhichareabletoaccesstheseresources.YoucanalsodefineHTTPmethodsthatareallowedtobeexecuted.Seethefollowing example. Example14.3.Securingresourcesusingw e b . x m l
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 < s e c u r i t y c o n s t r a i n t > < w e b r e s o u r c e c o l l e c t i o n > < u r l p a t t e r n > / r e s t / a d m i n / * < / u r l p a t t e r n > < / w e b r e s o u r c e c o l l e c t i o n > < a u t h c o n s t r a i n t > < r o l e n a m e > a d m i n < / r o l e n a m e > < / a u t h c o n s t r a i n t > < / s e c u r i t y c o n s t r a i n t > < s e c u r i t y c o n s t r a i n t > < w e b r e s o u r c e c o l l e c t i o n > < u r l p a t t e r n > / r e s t / o r d e r s / * < / u r l p a t t e r n > < / w e b r e s o u r c e c o l l e c t i o n > < a u t h c o n s t r a i n t > < r o l e n a m e > c u s t o m e r < / r o l e n a m e > < / a u t h c o n s t r a i n t > < / s e c u r i t y c o n s t r a i n t > < l o g i n c o n f i g > < a u t h m e t h o d > B A S I C < / a u t h m e t h o d > < r e a l m n a m e > m y d e f a u l t r e a l m < / r e a l m n a m e > < / l o g i n c o n f i g >

TheexamplesecurestwokindsofURInamespacesusingtheHTTPBasicAuthentication.r e s t / a d m i n / * willbeaccessibleonlyforusergroup"admin"and r e s t / o r d e r s / * willbeaccessiblefor"customer"usergroup.ThissecurityconfigurationdoesnotuseJAXRSorJerseyfeaturesatallasitisenforcedbythe ServletcontainerevenbeforearequestreachestheJerseyapplication.KeepingthissecurityconstrainsuptodatewithyourJAXRSapplicationmightnotbe easyaswheneveryouchangethe@Pathannotationsonyourresourceclassesyoumayneedtoupdatealsothew e b . x m l securityconfigurationstoreflect thechangedJAXRSresourcepaths.ThereforeJerseyoffersamoreflexiblesolutionbasedonplacingstandardJavaEEsecurityannotationsdirectlyonJAX RSresourceclassesandmethods.

14.1.2.2.SecuringJAXRSresourceswithannotations
WithJerseyyoucandefinetheaccesstoresourcesbasedontheusergroupusingannotations.Youcanforexampledefinethatonlyausergroup"admin" canexecutespecificresourcemethod.TodothatyoufirstlyneedtoregisterRolesAllowedDynamicFeatureasaprovider.Thefollowingexampleshowshow toregisterthefeatureifyourdeploymentisbasedonaResourceConfig. Example14.4.RegisteringRolesAllowedDynamicFeatureusingResourceConfig
1 2 f i n a l R e s o u r c e C o n f i g r e s o u r c e C o n f i g = n e w R e s o u r c e C o n f i g ( M y R e s o u r c e . c l a s s ) r e s o u r c e C o n f i g . r e g i s t e r ( R o l e s A l l o w e d D y n a m i c F e a t u r e . c l a s s )

Thenyoucanuseannotationsfrompackagej a v a x . a n n o t a t i o n . s e c u r i t y definedbyJSR250.Seethefollowingexample. Example14.5.InjectingS e c u r i t y C o n t e x t intosingletons


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 @ P a t h ( " / " ) @ P e r m i t A l l p u b l i c c l a s s R e s o u r c e { @ R o l e s A l l o w e d ( " u s e r " ) @ G E T p u b l i c S t r i n g g e t ( ) { r e t u r n " G E T " } @ R o l e s A l l o w e d ( " a d m i n " ) @ P O S T p u b l i c S t r i n g p o s t ( S t r i n g c o n t e n t ) { r e t u r n c o n t e n t } @ P a t h ( " s u b " ) p u b l i c S u b R e s o u r c e g e t S u b R e s o u r c e ( ) { r e t u r n n e w S u b R e s o u r c e ( ) } }

TheresourceclassR e s o u r c e definedintheexampleisannotatedwitha@PermitAllannotation.Thismeansthatallmethodsintheclasswhichdonot overridethisannotationwillbepermittedforallusergroups(norestrictionsaredefined).Inourexample,theannotationwillonlyapplytothe g e t S u b R e s o u r c e ( ) methodasitistheonlymethodthatdoesnotoverridetheannotationbydefiningcustomrolebasedsecuritysettingsusingthe @RolesAllowedannotation.@ R o l e s A l l o w e d annotationpresentonothermethodsdefinesaroleorasetofrolesthatareallowedtoexecuteaparticular method. TheseJavaEEsecurityannotationsareprocessedinternallyintherequestfilterregisteredusingtheJerseyR o l e s A l l o w e d D y n a m i c F e a t u r e .Theroles definedintheannotationsaretestedagainstcurrentrolessetintheS e c u r i t y C o n t e x t usingtheS e c u r i t y C o n t e x t . i s U s e r I n R o l e ( S t r i n g r o l e ) method.Incasethecallerisnotintherolespecifiedbytheannotation,theHTTP4 0 3 ( F o r b i d d e n ) errorresponseisreturned.

14.2.ClientSecurity
FordetailsaboutclientsecuritypleaseseetheClientchapter.JerseyclientallowstodefineparametersofSSLcommunicationusingH T T P S protocol.Youcan alsousejerseybuiltinauthenticationfilterswhichperformHTTPBasicAuthenticationorHTTPDigestAuthentication.Seetheclientchapterformoredetails.

14.3.OAuth
OAuth1.xsupporthasnotbeenmigratedfromJersey1.xtoJersey2.xyet.ThedocumentationwillbeupdatedoncetheOAuthsupportfeaturewillbe releasedinJersey2.

Chapter15.WADLSupport
TableofContents 15.1.WADLintroduction 15.2.Configuration 15.3.ExtendedWADLsupport

15.1.WADLintroduction
JerseycontainssupportforWebApplicationDescriptionLanguage(WADL).WADLisaXMLdescriptionofadeployedRESTfulwebapplication.Itcontains modelofthedeployedresources,theirstructure,supportedmediatypes,HTTPmethodsandsoon.Inasense,WADLisasimilartotheWSDL(WebService DescriptionLanguage)whichdescribesSOAPwebservices.WADLishoweverspecificallydesignedtodescribeRESTfulWebresources. Let'sstartwiththesimpleWADLexample.IntheexamplethereisasimpleC o u n t r y R e s o u r c e deployedandwerequestawadlofthisresource.Thecontext rootpathoftheapplicationish t t p : / / l o c a l h o s t : 9 9 9 8 . Example15.1.AsimpleWADLexampleJAXRSresourcedefinition
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 @ P a t h ( " c o u n t r y / { i d } " ) p u b l i c s t a t i c c l a s s C o u n t r y R e s o u r c e { p r i v a t e C o u n t r y S e r v i c e c o u n t r y S e r v i c e p u b l i c C o u n t r y R e s o u r c e ( ) { / / i n i t c o u n t r y S e r v i c e } @ G E T @ P r o d u c e s ( M e d i a T y p e . A P P L I C A T I O N _ X M L ) p u b l i c C o u n t r y g e t C o u n t r y ( @ P a t h P a r a m ( " c o u n t r y I d " ) i n t c o u n t r y I d ) { r e t u r n c o u n t r y S e r v i c e . g e t C o u n t r y ( c o u n t r y I d ) } }

TheWADLofaJerseyapplicationthatcontainstheresourceabovecanberequestedbyaHTTPG E T requestto h t t p : / / l o c a l h o s t : 9 9 9 8 / a p p l i c a t i o n . w a d l .TheJerseywillreturnaresponsewithaWADLcontentsimilartotheoneinthefollowingexample: Example15.2.AsimpleWADLexampleWADLcontent


1 2 3 4 5 6 7 < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " s t a n d a l o n e = " y e s " ? > < a p p l i c a t i o n x m l n s = " h t t p : / / w a d l . d e v . j a v a . n e t / 2 0 0 9 / 0 2 " > < d o c x m l n s : j e r s e y = " h t t p : / / j e r s e y . j a v a . n e t / " j e r s e y : g e n e r a t e d B y = " J e r s e y : 2 . 0 S N A P S H O T $ { b u i l d N u m b e r } " / > < g r a m m a r s / > < r e s o u r c e s b a s e = " h t t p : / / l o c a l h o s t : 9 9 9 8 / " > < r e s o u r c e p a t h = " c o u n t r y / { i d } " > < p a r a m x m l n s : x s = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a "

8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 0 7 1 7 2 7 3 7 4 7 5 7 6 7 7 7 8 7 9 8 0 8 1 8 2 8 3 8 4 8 5 8 6 8 7 8 8 8 9

t y p e = " x s : i n t " s t y l e = " t e m p l a t e " n a m e = " c o u n t r y I d " / > < m e t h o d n a m e = " G E T " i d = " g e t C o u n t r y " > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / v n d . s u n . w a d l + x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " t e x t / p l a i n " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e s p o n s e > < / m e t h o d > < / r e s o u r c e > < r e s o u r c e p a t h = " a p p l i c a t i o n . w a d l " > < m e t h o d n a m e = " G E T " i d = " g e t W a d l " > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / v n d . s u n . w a d l + x m l " / > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " t e x t / p l a i n " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e s p o n s e > < / m e t h o d > < r e s o u r c e p a t h = " { p a t h } " > < p a r a m x m l n s : x s = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a " t y p e = " x s : s t r i n g " s t y l e = " t e m p l a t e " n a m e = " p a t h " / > < m e t h o d n a m e = " G E T " i d = " g e E x t e r n a l G r a m m a r " > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " t e x t / p l a i n " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e s p o n s e > < / m e t h o d > < / r e s o u r c e > < / r e s o u r c e > < / r e s o u r c e s > < / a p p l i c a t i o n >

IntheexampleabovethereturnedapplicationWADLisshowninfull.WADLschemaisdefinedbytheWADLspecification.TherootWADLdocumentelement isthea p p l i c a t i o n .ItcontainsglobalinformationaboutthedeployedJAXRSapplication.Underthiselementthereisanestedelementr e s o u r c e s which containszeroormorer e s o u r c e elements.Eachr e s o u r c e elementdescribesasingledeployedresource.Inourexample,thereareonlytworootresources " c o u n t r y / { i d } " and" a p p l i c a t i o n . w a d l " .The" a p p l i c a t i o n . w a d l " resourceistheresourcethatwasjustrequestedinordertoreceivethe applicationWADLdocument.EventhoughWADLsupportisanadditionalfeatureinJerseyitisstillaresourcedeployedintheresourcemodelandthereforeit isitselfpresentinthereturnedWADLdocument.Thefirstresourceelementwiththep a t h = " c o u n t r y / { i d } " istheelementthatdescribesourcustom deployedresource.ThisresourcecontainsaG E T methodandthreeO P T I O N S methods.TheG E T methodisourgetCountry()methoddefinedinthesample. Thereisamethodnameinthei d attributeand@Producesisdescribedinther e s p o n s e / r e p r e s e n t a t i o n WADLelement.O P T I O N S methodsarethe methodsthatareautomaticallyaddedbyJerseytoeachresource.ThereisanO P T I O N S methodreturning" t e x t / p l a i n " mediatype,thatwillreturna responsewithastringentitycontainingthelistofmethodsdeployedonthisresource(thismeansthatinsteadofWADLyoucanusethisO P T I O N S methodto getsimilarinformationinatextualrepresentation).AnotherO P T I O N S methodreturning* / * willreturnaresponsewithnoentityandA l l o w headerthatwill containlistofmethodsasaString.ThelastO P T I O N S methodproducing" a p p l i c a t i o n / v n d . s u n . w a d l + x m l " returnsaWADLdescriptionoftheresource " c o u n t r y / { i d } " .Asyoucansee,allO P T I O N S methodsreturninformationabouttheresourcetowhichtheHTTPO P T I O N S requestismade. Secondresourcewithapath"application.wadl"has,again,similarO P T I O N S methodsandoneG E T methodwhichreturnthisWADL.Thereisalsoasub resourcewithapathdefinedbypathparam{ p a t h } .ThismeansthatyoucanrequestaresourceontheURI h t t p : / / l o c a l h o s t : 9 9 9 8 / a p p l i c a t i o n . w a d l / s o m e t h i n g .Thisisusedonlytoreturnanexternalgrammarifthereisanyattached.Suchaexternal grammarcanbeforexampleanX S D schemaoftheresponseentitywhichiftheresponseentityisaJAXBbean.AnexternalgrammarsupportviaJersey extendedWADLsupportisdescribedinsectionsbelow. Let'snowsendanHTTPO P T I O N S requestto" c o u n t r y / { i d } " resourceusingthethec u r l command:
c u r l X O P T I O N S H " A l l o w : a p p l i c a t i o n / v n d . s u n . w a d l + x m l " \ v h t t p : / / l o c a l h o s t : 9 9 9 8 / c o u n t r y / 1 5

WeshouldseeaWADLreturnedsimilartothisone: Example15.3.OPTIONSmethodreturningWADL
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " s t a n d a l o n e = " y e s " ? > < a p p l i c a t i o n x m l n s = " h t t p : / / w a d l . d e v . j a v a . n e t / 2 0 0 9 / 0 2 " > < d o c x m l n s : j e r s e y = " h t t p : / / j e r s e y . j a v a . n e t / " j e r s e y : g e n e r a t e d B y = " J e r s e y : 2 . 0 S N A P S H O T $ { b u i l d N u m b e r } " / > < g r a m m a r s / > < r e s o u r c e s b a s e = " h t t p : / / l o c a l h o s t : 9 9 9 8 / " > < r e s o u r c e p a t h = " c o u n t r y / 1 5 " > < m e t h o d n a m e = " G E T " i d = " g e t C o u n t r y " > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / v n d . s u n . w a d l + x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " t e x t / p l a i n " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e s p o n s e > < / m e t h o d > < / r e s o u r c e > < / r e s o u r c e s > < / a p p l i c a t i o n >

ThereturnedWADLdocumenthasthestandardWADLstructurethatwesawintheWADLdocumentreturnedforthewholeJerseyapplicationearlier.The maindifferencehereisthattheonlyr e s o u r c e istheresourcetowhichtheO P T I O N S HTTPrequestwassent.Theresourcehasnowpath" c o u n t r y / 1 5 " and not" c o u n t r y / { i d } " asthepathparameter{ i d } wasalreadyspecifiedintherequesttothisconcreteresource. Another,amorecomplexWADLexampleisshowninthenextexample. Example15.4.MorecomplexWADLexampleJAXRSresourcedefinition
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 @ P a t h ( " c u s t o m e r / { i d } " ) p u b l i c s t a t i c c l a s s C u s t o m e r R e s o u r c e { p r i v a t e C u s t o m e r S e r v i c e c u s t o m e r S e r v i c e @ G E T p u b l i c C u s t o m e r g e t ( @ P a t h P a r a m ( " i d " ) i n t i d ) { r e t u r n c u s t o m e r S e r v i c e . g e t C u s t o m e r B y I d ( i d ) } @ P U T p u b l i c C u s t o m e r p u t ( C u s t o m e r c u s t o m e r ) { r e t u r n c u s t o m e r S e r v i c e . u p d a t e C u s t o m e r ( c u s t o m e r ) } @ P a t h ( " a d d r e s s " ) p u b l i c C u s t o m e r A d d r e s s S u b R e s o u r c e g e t C u s t o m e r A d d r e s s ( @ P a t h P a r a m ( " i d " ) i n t i d ) { r e t u r n n e w C u s t o m e r A d d r e s s S u b R e s o u r c e ( i d ) } @ P a t h ( " a d d i t i o n a l i n f o " ) p u b l i c O b j e c t g e t A d d i t i o n a l I n f o S u b R e s o u r c e ( @ P a t h P a r a m ( " i d " ) i n t i d ) { r e t u r n n e w C u s t o m e r A d d r e s s S u b R e s o u r c e ( i d ) } } p u b l i c s t a t i c c l a s s C u s t o m e r A d d r e s s S u b R e s o u r c e { p r i v a t e f i n a l i n t c u s t o m e r I d p r i v a t e C u s t o m e r S e r v i c e c u s t o m e r S e r v i c e p u b l i c C u s t o m e r A d d r e s s S u b R e s o u r c e ( i n t c u s t o m e r I d ) { t h i s . c u s t o m e r I d = c u s t o m e r I d t h i s . c u s t o m e r S e r v i c e = n u l l / / i n i t c u s t o m e r s e r v i c e h e r e } @ G E T p u b l i c S t r i n g g e t A d d r e s s ( ) { r e t u r n c u s t o m e r S e r v i c e . g e t A d d r e s s F o r C u s t o m e r ( c u s t o m e r I d ) } @ P U T p u b l i c v o i d u p d a t e A d d r e s s ( S t r i n g a d d r e s s ) { c u s t o m e r S e r v i c e . u p d a t e A d d r e s s F o r C u s t o m e r ( c u s t o m e r I d , a d d r e s s ) } @ G E T @ P a t h ( " s u b " ) p u b l i c S t r i n g g e t D e l i v e r y A d d r e s s ( ) { r e t u r n c u s t o m e r S e r v i c e . g e t D e l i v e r y A d d r e s s F o r C u s t o m e r ( c u s t o m e r I d ) } }

TheG E T requesttoh t t p : / / l o c a l h o s t : 9 9 9 8 / a p p l i c a t i o n . w a d l willreturnthefollowingWADLdocument: Example15.5.MorecomplexWADLexampleWADLcontent

1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 0 7 1 7 2 7 3 7 4 7 5 7 6 7 7 7 8 7 9 8 0 8 1 8 2 8 3 8 4 8 5 8 6 8 7 8 8 8 9 9 0 9 1 9 2 9 3 9 4 9 5 9 6 9 7 9 8 9 9 1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 1 0 6 1 0 7 1 0 8

< ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " s t a n d a l o n e = " y e s " ? > < a p p l i c a t i o n x m l n s = " h t t p : / / w a d l . d e v . j a v a . n e t / 2 0 0 9 / 0 2 " > < d o c x m l n s : j e r s e y = " h t t p : / / j e r s e y . j a v a . n e t / " j e r s e y : g e n e r a t e d B y = " J e r s e y : 2 . 0 S N A P S H O T $ { b u i l d N u m b e r } " / > < g r a m m a r s / > < r e s o u r c e s b a s e = " h t t p : / / l o c a l h o s t : 9 9 9 8 / " > < r e s o u r c e p a t h = " c u s t o m e r / { i d } " > < p a r a m x m l n s : x s = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a " t y p e = " x s : i n t " s t y l e = " t e m p l a t e " n a m e = " i d " / > < m e t h o d n a m e = " G E T " i d = " g e t " > < r e s p o n s e / > < / m e t h o d > < m e t h o d n a m e = " P U T " i d = " p u t " > < r e s p o n s e / > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / v n d . s u n . w a d l + x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " t e x t / p l a i n " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e s p o n s e > < / m e t h o d > < r e s o u r c e p a t h = " a d d i t i o n a l i n f o " > < p a r a m x m l n s : x s = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a " t y p e = " x s : i n t " s t y l e = " t e m p l a t e " n a m e = " i d " / > < / r e s o u r c e > < r e s o u r c e p a t h = " a d d r e s s " > < p a r a m x m l n s : x s = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a " t y p e = " x s : i n t " s t y l e = " t e m p l a t e " n a m e = " i d " / > < m e t h o d n a m e = " G E T " i d = " g e t A d d r e s s " > < r e s p o n s e / > < / m e t h o d > < m e t h o d n a m e = " P U T " i d = " u p d a t e A d d r e s s " / > < r e s o u r c e p a t h = " s u b " > < m e t h o d n a m e = " G E T " i d = " g e t D e l i v e r y A d d r e s s " > < r e s p o n s e / > < / m e t h o d > < / r e s o u r c e > < / r e s o u r c e > < / r e s o u r c e > < r e s o u r c e p a t h = " a p p l i c a t i o n . w a d l " > < m e t h o d n a m e = " G E T " i d = " g e t W a d l " > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / v n d . s u n . w a d l + x m l " / > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " t e x t / p l a i n " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e s p o n s e > < / m e t h o d > < r e s o u r c e p a t h = " { p a t h } " > < p a r a m x m l n s : x s = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a " t y p e = " x s : s t r i n g " s t y l e = " t e m p l a t e " n a m e = " p a t h " / > < m e t h o d n a m e = " G E T " i d = " g e E x t e r n a l G r a m m a r " > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " a p p l i c a t i o n / x m l " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " t e x t / p l a i n " / > < / r e s p o n s e > < / m e t h o d > < m e t h o d n a m e = " O P T I O N S " i d = " a p p l y " > < r e q u e s t > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e q u e s t > < r e s p o n s e > < r e p r e s e n t a t i o n m e d i a T y p e = " * / * " / > < / r e s p o n s e > < / m e t h o d > < / r e s o u r c e > < / r e s o u r c e > < / r e s o u r c e s > < / a p p l i c a t i o n >

Ther e s o u r c e withp a t h = " c u s t o m e r / { i d } " issimilartothecountryresourcefromthepreviousexample.Thereisapathparameterwhichidentifiesthe customerbyi d .Theresourcecontains2userdeclaredmethodsandagainautogeneratedO P T I O N S methodsaddedbyJersey.THeresourcedeclares2 subresourcelocatorswhicharerepresentedinthereturnedWADLdocumentasnestedr e s o u r c e elements.Notethatthesubresourcelocator

g e t C u s t o m e r A d d r e s s ( ) returnsatypeCustomerAddressSubResourceinthemethoddeclarationandalsointheWADLthereisar e s o u r c e elementfor suchasubresourcewithfullinternaldescription.Thesecondmethodg e t A d d i t i o n a l I n f o S u b R e s o u r c e ( ) returnsonlyanO b j e c t inthemethod

declaration.WhilethisiscorrectfromtheJAXRSperspectiveastherealreturnedtypecanbecomputedfromarequestinformation,itcreatesaproblemfor WADLgeneratorbecauseWADLisgeneratedbasedonthestaticconfigurationoftheJAXRSapplicationresources.TheWADLgeneratordoesnotknow whattypewouldbeactuallyreturnedtoarequestatruntime.Thatisthereasonwhythenestedr e s o u r c e elementwithp a t h = " a d d i t i o n a l i n f o " doesnot containanyinformationaboutthesupportedresourcerepresentations. TheC u s t o m e r A d d r e s s S u b R e s o u r c e subresourcedescribedinthenestedelement< r e s o u r c e p a t h = " a d d r e s s " > doesnotcontainanO P T I O N S method. WhilethesemethodsareinfactgeneratedbyJerseyforthesubresource,JerseyWADLgeneratordoesnotcurrentlysupportaddingthesemethodstothe subresourcedescription.Thisshouldbeaddressedinthenearfuture.Still,therearetwouserdefinedresourcemethodshandlingHTTPG E T andP U T requests.Thesubresourcemethodg e t D e l i v e r y A d d r e s s ( ) isrepresentedasaseparatenestedresourcewithp a t h = " s u b " .Shouldtherebemoresub resourcemethodsdefinedwithp a t h = " s u b " ,thenallthesemethoddescriptionswouldbeplacedintothesamer e s o u r c e element.Inotherwords,sub resourcemethodsaregroupedinWADLassubresourcesbasedontheirp a t h value.

15.2.Configuration
WADLgenerationisenabledinJerseybydefault.ThismeansthatO P T I O N S methodsareaddedbydefaulttoeachresourceandanautogenerated / a p p l i c a t i o n . w a d l resourceisdeployedtoo.TooverridethisdefaultbehavioranddisableWADLgenerationinJersey,setuptheconfigurationpropertyin yourapplication:
j e r s e y . c o n f i g . s e r v e r . w a d l . d i s a b l e W a d l = t r u e

Thispropertycanbesetupinaw e b . x m l iftheJerseyapplicationisdeployedintheservletwithw e b . x m l orthepropertycanbereturnedfromtheApplication. g e t P r o p e r t i e s ( ) .SeeDeploymentchapterformoreinformationonsettingtheapplicationconfigurationpropertiesinvariousdeployments. WADLsupportinJerseyisimplementedviaModelProcessorextension.ThisimplementationenhancestheapplicationresourcemodelbyaddingtheWADL providingresources.WADLM o d e l P r o c e s s o r priorityvalueishigh(i.e.thepriorityislow)asitshouldbeexecutedasoneofthelastmodelprocessors. Therefore,anyM o d e l P r o c e s s o r executedbeforewillnotseeWADLextensionsintheresourcemodel.WADLhandlingresourcemodelextensions (resourcesandO P T I O N S resourcemethods)arenotaddedtotheapplicationresourcemodelifthereisalreadyamatchingresourceoraresourcemethod detectedinthemodel.Inotherwords,ifyoudefineforexampleyourownO P T I O N S methodthatwouldproduce" a p p l i c a t i o n . w a d l " responsecontent,this methodwillnotbeoverriddenbyWADLmodelprocessor.SeeResourcebuilderchapterformoreinformationonM o d e l P r o c e s s o r extensionmechanism.

15.3.ExtendedWADLsupport
PleasenotethattheAPIofextendedWADLsupportisgoingtobechangedinoneofthefuturereleasesofJersey2.x(seebelow). JerseysupportsextensionofWADLgenerationcalledextendedWADL.UsingtheextendedWADLsupportyoucanenhancethegeneratedWADLdocument withadditionalinformation,suchasresourcemethodjavadocbaseddocumentationofyourRESTAPIs,addinggeneraldocumentation,addingexternal grammarsupport,oraddinganycustomWADLextensioninformation. ThedocumentationoftheexistingextendedWADLcanbefoundhere:ExtendedWADLinJersey1.ThiscontainsdescriptionofanextendedWADL generationinJersey1.xthatiscurrentlysupportedalsobyJersey2.x. Again,notethattheextendedWADLinJersey2.xisNOTtheintendedfinalversionandAPIisgoingtobechanged.Theexistingsetoffeaturesand functionalitywillbepreservedbuttheAPIswillbesignificantlyredesignedtosupportadditionalusecases.ThisimpactsmainlytheAPIsofWadlGenerator, WadlGeneratorConfigaswellasanyrelatedclasses.TheAPIchangesmayimpactyourcodeifyouareusingacustomW a d l G e n e r a t o r orplantoimplement one.

Chapter16.BeanValidationSupport
TableofContents 16.1.BeanValidationDependencies 16.2.EnablingBeanValidationinJersey 16.3.ConfiguringBeanValidationSupport 16.4.ValidatingJAXRSresourcesandmethods 16.4.1.ConstraintAnnotations 16.4.2.AnnotationconstraintsandValidators 16.4.3.EntityValidation 16.4.4.AnnotationInheritance 16.5.@ValidateOnExecution 16.6.Injecting 16.7.ErrorReporting 16.7.1.ValidationError 16.8.Example Validationisaprocessofverifyingthatsomedataobeysoneormorepredefinedconstraints.ThischapterdescribessupportforBeanValidationinJerseyin termsoftheneededdependencies,configuration,registrationandusage.FormoredetaileddescriptiononhowJAXRSprovidesnativesupportforvalidating resourceclassesbasedontheBeanValidationrefertothechapterintheJAXRSspec.

16.1.BeanValidationDependencies
BeanValidationsupportinJerseyisprovidedasanextensionmoduleandneedstobementionedexplicitlyinyourp o m . x m l file(incaseofusingMaven):
< d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . e x t < / g r o u p I d > < a r t i f a c t I d > j e r s e y b e a n v a l i d a t i o n < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Note
Ifyou'renotusingMavenmakesuretohavealsoallthetransitivedependencies(seejerseybeanvalidation)ontheclasspath. ThismoduledependsdirectlyonHibernateValidatorwhichprovidesamostcommonlyusedimplementationoftheBeanValidationAPIspec. IfyouwanttouseadifferentimplementationoftheBeanValidationAPI,usestandardMavenmechanismstoexcludeHibernateValidatorfromthemodules dependenciesandaddadependencyofyourown.
< d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . e x t < / g r o u p I d > < a r t i f a c t I d > j e r s e y b e a n v a l i d a t i o n < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < e x c l u s i o n s > < e x c l u s i o n > < g r o u p I d > o r g . h i b e r n a t e < / g r o u p I d > < a r t i f a c t I d > h i b e r n a t e v a l i d a t o r < / a r t i f a c t I d > < / e x c l u s i o n > < / e x c l u s i o n s >

< / d e p e n d e n c y >

16.2.EnablingBeanValidationinJersey
AsstatedinSection4.1,AutoDiscoverableFeatures,JerseyBeanValidationisoneofthemoduleswhereyoudon'tneedtoexplicitlyregisterit'sF e a t u r e s (ValidationFeature)ontheserverasit'sfeaturesareautomaticallydiscoveredandregisteredwhenyouaddthej e r s e y b e a n v a l i d a t i o n moduletoyour classpath.TherearethreeJerseyspecificpropertiesthatcoulddisableautomaticdiscoveryandregistrationofJerseyBeanValidationintegrationmodule: CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE ServerProperties.FEATURE_AUTO_DISCOVERY_DISABLE ServerProperties.BV_FEATURE_DISABLE

Note
JerseydoesnotsupportBeanValidationontheclientatthemoment.

16.3.ConfiguringBeanValidationSupport
ConfigurationofBeanValidationsupportinJerseyistwofoldtherearefewspecificpropertiesthataffectsJerseybehaviour(e.g.sendingvalidationerror entitiestotheclient)andthenthereisValidationConfigclassthatconfiguresValidatorusedforvalidatingresourcesinJAXRSapplication. ToconfigureJerseyspecificbehaviouryoucanusethefollowingproperties: ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK Disables@ V a l i d a t e O n E x e c u t i o n check.MoreonthisisdescribedinSection16.5,@ValidateOnExecution. ServerProperties.BV_SEND_ERROR_IN_RESPONSE Enablessendingvalidationerrorsinresponseentitytotheclient.MoreonthisinSection16.7.1,ValidationError. Example16.1.ConfiguringJerseyspecificpropertiesforBeanValidation.
1 2 3 4 5 6 7 n e w R e s o u r c e C o n f i g ( ) / / N o w y o u c a n e x p e c t v a l i d a t i o n e r r o r s t o b e s e n t t o t h e c l i e n t . . p r o p e r t y ( S e r v e r P r o p e r t i e s . B V _ S E N D _ E R R O R _ I N _ R E S P O N S E , t r u e ) / / @ V a l i d a t e O n E x e c u t i o n a n n o t a t i o n s o n s u b c l a s s e s w o n ' t c a u s e e r r o r s . . p r o p e r t y ( S e r v e r P r o p e r t i e s . B V _ D I S A B L E _ V A L I D A T E _ O N _ E X E C U T A B L E _ O V E R R I D E _ C H E C K , t r u e ) / / F u r t h e r c o n f i g u r a t i o n o f R e s o u r c e C o n f i g . . r e g i s t e r ( . . . )

CustomizationoftheV a l i d a t o r usedinvalidationofresourceclasses/methodscanbedoneusingV a l i d a t i o n C o n f i g classandexposingitvia ContextResolver<T>mechanismasshowninExample16.2,UsingV a l i d a t i o n C o n f i g toconfigureV a l i d a t o r ..Youcansetcustominstancesforthe followinginterfacesfromtheBeanValidationAPI: MessageInterpolatorinterpolatesagivenconstraintviolationmessage. TraversableResolverdeterminesifapropertycanbeaccessedbytheBeanValidationprovider. ConstraintValidatorFactoryinstantiatesaC o n s t r a i n t V a l i d a t o r instancebasedoffitsclass.Notethatbysettingacustom C o n s t r a i n t V a l i d a t o r F a c t o r y youmaylooseinjectionofavailableresources/providersatthemoment.SeeSection16.6,Injectinghowtohandle this. ParameterNameProviderprovidesnamesformethodandconstructorparameters.

Tip
InthelatestversionsofJersey,theoldstylesettermethods(s e t * )onValidationConfigaredeprecatedandreplacedwithmethodsthatallow thefluentuseoftheAPI(e.g.V a l i d a t i o n C o n f i g # m e s s a g e I n t e r p o l a t o r ( M e s s a g e I n t e r p o l a t o r ) ).Useofthenewfluentmethodsis encouragedastheoldsetterswillberemovedfromtheAPIsoon. Example16.2.UsingV a l i d a t i o n C o n f i g toconfigureV a l i d a t o r .
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 / * * * C u s t o m c o n f i g u r a t i o n o f v a l i d a t i o n . T h i s c o n f i g u r a t i o n d e f i n e s c u s t o m : * < u l > * < l i > C o n s t r a i n t V a l i d a t i o n F a c t o r y s o t h a t v a l i d a t o r s a r e a b l e t o i n j e c t J e r s e y p r o v i d e r s / r e s o u r c e s . < / l i > * < l i > P a r a m e t e r N a m e P r o v i d e r i f m e t h o d i n p u t p a r a m e t e r s a r e i n v a l i d , t h i s c l a s s r e t u r n s a c t u a l p a r a m e t e r n a m e s * i n s t e a d o f t h e d e f a u l t o n e s ( { @ c o d e a r g 0 , a r g 1 , . . } ) < / l i > * < / u l > * / p u b l i c c l a s s V a l i d a t i o n C o n f i g u r a t i o n C o n t e x t R e s o l v e r i m p l e m e n t s C o n t e x t R e s o l v e r < V a l i d a t i o n C o n f i g > { @ C o n t e x t p r i v a t e R e s o u r c e C o n t e x t r e s o u r c e C o n t e x t @ O v e r r i d e p u b l i c V a l i d a t i o n C o n f i g g e t C o n t e x t ( f i n a l C l a s s < ? > t y p e ) { f i n a l V a l i d a t i o n C o n f i g c o n f i g = n e w V a l i d a t i o n C o n f i g ( ) c o n f i g . s e t C o n s t r a i n t V a l i d a t o r F a c t o r y ( r e s o u r c e C o n t e x t . g e t R e s o u r c e ( I n j e c t i n g C o n s t r a i n t V a l i d a t o r F a c t o r y . c l a s s ) ) c o n f i g . s e t P a r a m e t e r N a m e P r o v i d e r ( n e w C u s t o m P a r a m e t e r N a m e P r o v i d e r ( ) ) r e t u r n c o n f i g } / * * * S e e C o n t a c t C a r d T e s t # t e s t A d d I n v a l i d C o n t a c t . * / p r i v a t e c l a s s C u s t o m P a r a m e t e r N a m e P r o v i d e r i m p l e m e n t s P a r a m e t e r N a m e P r o v i d e r { p r i v a t e f i n a l P a r a m e t e r N a m e P r o v i d e r n a m e P r o v i d e r p u b l i c C u s t o m P a r a m e t e r N a m e P r o v i d e r ( ) { n a m e P r o v i d e r = V a l i d a t i o n . b y D e f a u l t P r o v i d e r ( ) . c o n f i g u r e ( ) . g e t D e f a u l t P a r a m e t e r N a m e P r o v i d e r ( ) } @ O v e r r i d e p u b l i c L i s t < S t r i n g > g e t P a r a m e t e r N a m e s ( f i n a l C o n s t r u c t o r < ? > c o n s t r u c t o r ) { r e t u r n n a m e P r o v i d e r . g e t P a r a m e t e r N a m e s ( c o n s t r u c t o r ) } @ O v e r r i d e p u b l i c L i s t < S t r i n g > g e t P a r a m e t e r N a m e s ( f i n a l M e t h o d m e t h o d ) { / / S e e C o n t a c t C a r d T e s t # t e s t A d d I n v a l i d C o n t a c t .

4 1 4 2 4 3 4 4 4 5 4 6 4 7

i f ( " a d d C o n t a c t " . e q u a l s ( m e t h o d . g e t N a m e ( ) ) ) { r e t u r n A r r a y s . a s L i s t ( " c o n t a c t " ) } r e t u r n n a m e P r o v i d e r . g e t P a r a m e t e r N a m e s ( m e t h o d ) } } }

Registerthisclassinyourapp:
1 2 3 4 5 f i n a l A p p l i c a t i o n a p p l i c a t i o n = n e w R e s o u r c e C o n f i g ( ) / / V a l i d a t i o n . . r e g i s t e r ( V a l i d a t i o n C o n f i g u r a t i o n C o n t e x t R e s o l v e r . c l a s s ) / / F u r t h e r c o n f i g u r a t i o n . . r e g i s t e r ( . . . )

Note
ThiscodesnippethasbeentakenfromBeanValidationexample.

16.4.ValidatingJAXRSresourcesandmethods
JAXRSspecificationstatesthatconstraintannotationsareallowedinthesamelocationsasthefollowingannotations:@ M a t r i x P a r a m ,@ Q u e r y P a r a m , @ P a t h P a r a m ,@ C o o k i e P a r a m ,@ H e a d e r P a r a m and@ C o n t e x t ,exceptinclassconstructorsandpropertysetters.Specifically,theyareallowedinresource methodparameters,fieldsandpropertygettersaswellasresourceclasses,entityparametersandresourcemethods(returnvalues).Jerseyprovidessupport forvalidation(seefollowingsections)annotatedinputparametersandreturnvalueoftheinvokedresourcemethodaswellasvalidationofresourceclass (classconstraints,fieldconstraints)wherethisresourcemethodisplaced.Jerseydoesnotsupport,anddoesn'tvalidate,constraintsplacedonconstructors andBeanValidationgroups(onlyD e f a u l t groupissupportedatthemoment).

16.4.1.ConstraintAnnotations
TheJAXRSServerAPIprovidessupportforextractingrequestvaluesandmappingthemintoJavafields,propertiesandparametersusingannotationssuch as@HeaderParam,@QueryParam,etc.ItalsosupportsmappingoftherequestentitybodiesintoJavaobjectsvianonannotatedparameters(i.e., parameterswithoutanyJAXRSannotations). TheBeanValidationspecificationsupportstheuseofconstraintannotationsasawayofdeclarativelyvalidatingbeans,methodparametersandmethod returnedvalues.Forexample,considerresourceclassfromExample16.3,Constraintannotationsoninputparametersaugmentedwithconstraint annotations. Example16.3.Constraintannotationsoninputparameters
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 @ P a t h ( " / " ) c l a s s M y R e s o u r c e C l a s s { @ P O S T @ C o n s u m e s ( " a p p l i c a t i o n / x w w w f o r m u r l e n c o d e d " ) p u b l i c v o i d r e g i s t e r U s e r ( @ N o t N u l l @ F o r m P a r a m ( " f i r s t N a m e " ) S t r i n g f i r s t N a m e , @ N o t N u l l @ F o r m P a r a m ( " l a s t N a m e " ) S t r i n g l a s t N a m e , @ E m a i l @ F o r m P a r a m ( " e m a i l " ) S t r i n g e m a i l ) { . . . } }

Theannotations@ N o t N u l l and@ E m a i l imposeadditionalconstraintsontheformparametersf i r s t N a m e ,l a s t N a m e ande m a i l .The@ N o t N u l l constraintis builtintotheBeanValidationAPIthe@ E m a i l constraintisassumedtobeuserdefinedintheexampleabove.Theseconstraintannotationsarenotrestricted tomethodparameters,theycanbeusedinanylocationinwhichJAXRSbindingannotationsareallowedwiththeexceptionofconstructorsandproperty setters. Ratherthanusingmethodparameters,theM y R e s o u r c e C l a s s shownabovecouldhavebeenwrittenasinExample16.4,Constraintannotationsonfields. Example16.4.Constraintannotationsonfields
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 @ P a t h ( " / " ) c l a s s M y R e s o u r c e C l a s s { @ N o t N u l l @ F o r m P a r a m ( " f i r s t N a m e " ) p r i v a t e S t r i n g f i r s t N a m e @ N o t N u l l @ F o r m P a r a m ( " l a s t N a m e " ) p r i v a t e S t r i n g l a s t N a m e p r i v a t e S t r i n g e m a i l @ F o r m P a r a m ( " e m a i l " ) p u b l i c v o i d s e t E m a i l ( S t r i n g e m a i l ) { t h i s . e m a i l = e m a i l } @ E m a i l p u b l i c S t r i n g g e t E m a i l ( ) { r e t u r n e m a i l } . . . }

Notethatinthisversion,f i r s t N a m e andl a s t N a m e arefieldsinitializedviainjectionande m a i l isaresourceclassproperty.Constraintannotationson propertiesarespecifiedintheircorrespondinggetters. Constraintannotationsarealsoallowedonresourceclasses.Inadditiontoannotatingfieldsandproperties,anannotationcanbedefinedfortheentireclass. Letusassumethat@ N o n E m p t y N a m e s validatesthatoneofthetwonamefieldsinM y R e s o u r c e C l a s s isprovided.Usingsuchanannotation,theexample abovecanbeextendedtolooklikeExample16.5,Constraintannotationsonclass Example16.5.Constraintannotationsonclass
1 2 3 @ P a t h ( " / " ) @ N o n E m p t y N a m e s c l a s s M y R e s o u r c e C l a s s {

4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6

@ N o t N u l l @ F o r m P a r a m ( " f i r s t N a m e " ) p r i v a t e S t r i n g f i r s t N a m e @ N o t N u l l @ F o r m P a r a m ( " l a s t N a m e " ) p r i v a t e S t r i n g l a s t N a m e p r i v a t e S t r i n g e m a i l . . . }

Constraintannotationsonresourceclassesareusefulfordefiningcrossfieldandcrosspropertyconstraints.

16.4.2.AnnotationconstraintsandValidators
AnnotationconstraintsandvalidatorsaredefinedinaccordancewiththeBeanValidationspecification.The@ E m a i l annotationusedinExample16.4, ConstraintannotationsonfieldsisdefinedusingtheBeanValidation@Constraintmetaannotation,seeExample16.6,Definitionofaconstraintannotation. Example16.6.Definitionofaconstraintannotation
1 2 3 4 5 6 7 8 9 1 0 1 1 @ T a r g e t ( { M E T H O D , F I E L D , P A R A M E T E R } ) @ R e t e n t i o n ( R U N T I M E ) @ C o n s t r a i n t ( v a l i d a t e d B y = E m a i l V a l i d a t o r . c l a s s ) p u b l i c @ i n t e r f a c e E m a i l { S t r i n g m e s s a g e ( ) d e f a u l t " { c o m . e x a m p l e . v a l i d a t i o n . c o n s t r a i n t s . e m a i l } " C l a s s < ? > [ ] g r o u p s ( ) d e f a u l t { } C l a s s < ? e x t e n d s P a y l o a d > [ ] p a y l o a d ( ) d e f a u l t { } }

The@ C o n s t r a i n t annotationmustincludeareferencetothevalidatorclassthatwillbeusedtovalidatedecoratedvalues.TheE m a i l V a l i d a t o r classmust implementC o n s t r a i n t V a l i d a t o r < E m a i l , T > whereT isthetypeofvaluesbeingvalidated,asdescribedinExample16.7,Validatorimplementation.. Example16.7.Validatorimplementation.


1 2 3 4 5 6 7 8 9 1 0 p u b l i c c l a s s E m a i l V a l i d a t o r i m p l e m e n t s C o n s t r a i n t V a l i d a t o r < E m a i l , S t r i n g > { p u b l i c v o i d i n i t i a l i z e ( E m a i l e m a i l ) { . . . } p u b l i c b o o l e a n i s V a l i d ( S t r i n g v a l u e , C o n s t r a i n t V a l i d a t o r C o n t e x t c o n t e x t ) { . . . } }

Thus,E m a i l V a l i d a t o r appliestovaluesannotatedwith@ E m a i l thatareoftypeS t r i n g .ValidatorsforotherJavatypescanbedefinedforthesame constraintannotation.

16.4.3.EntityValidation
Requestentitybodiescanbemappedtoresourcemethodparameters.Therearetwowaysinwhichtheseentitiescanbevalidated.Iftherequestentityis mappedtoaJavabeanwhoseclassisdecoratedwithBeanValidationannotations,thenvalidationcanbeenabledusing@ValidasinExample16.8,Entity validation. Example16.8.Entityvalidation
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 @ S t a n d a r d U s e r c l a s s U s e r { @ N o t N u l l p r i v a t e S t r i n g f i r s t N a m e . . . } @ P a t h ( " / " ) c l a s s M y R e s o u r c e C l a s s { @ P O S T @ C o n s u m e s ( " a p p l i c a t i o n / x m l " ) p u b l i c v o i d r e g i s t e r U s e r ( @ V a l i d U s e r u s e r ) { . . . } }

Inthiscase,thevalidatorassociatedwith@ S t a n d a r d U s e r (aswellasthosefornonclasslevelconstraintslike@ N o t N u l l )willbecalledtoverifytherequest entitymappedtou s e r . Alternatively,anewannotationcanbedefinedanduseddirectlyontheresourcemethodparameter(Example16.9,Entityvalidation2). Example16.9.Entityvalidation2


1 2 3 4 5 6 7 8 9 @ P a t h ( " / " ) c l a s s M y R e s o u r c e C l a s s { @ P O S T @ C o n s u m e s ( " a p p l i c a t i o n / x m l " ) p u b l i c v o i d r e g i s t e r U s e r ( @ P r e m i u m U s e r U s e r u s e r ) { . . . } }

Intheexampleabove,@ P r e m i u m U s e r ratherthan@ S t a n d a r d U s e r willbeusedtovalidatetherequestentity.Thesetwowaysinwhichvalidationofentities canbetriggeredcanalsobecombinedbyincluding@ V a l i d inthelistofconstraints.Thepresenceof@ V a l i d willtriggervalidationofalltheconstraint annotationsdecoratingaJavabeanclass.

Responseentitybodiesreturnedfromresourcemethodscanbevalidatedinasimilarmannerbyannotatingtheresourcemethoditself.Toexemplify, assumingboth@ S t a n d a r d U s e r and@ P r e m i u m U s e r arerequiredtobecheckedbeforereturningauser,theg e t U s e r methodcanbeannotatedasshownin Example16.10,Responseentityvalidation. Example16.10.Responseentityvalidation


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 @ P a t h ( " / " ) c l a s s M y R e s o u r c e C l a s s { @ G E T @ P a t h ( " { i d } " ) @ P r o d u c e s ( " a p p l i c a t i o n / x m l " ) @ V a l i d @ P r e m i u m U s e r p u b l i c U s e r g e t U s e r ( @ P a t h P a r a m ( " i d " ) S t r i n g i d ) { U s e r u = f i n d U s e r ( i d ) r e t u r n u } . . . }

Notethat@ P r e m i u m U s e r isexplicitlylistedand@ S t a n d a r d U s e r istriggeredbythepresenceofthe@ V a l i d annotationseedefinitionofU s e r classearlierin thissection.

16.4.4.AnnotationInheritance
TherulesforinheritanceofconstraintannotationaredefinedinBeanValidationspecification.Itisworthnotingthattheserulesareincompatiblewiththose definedbyJAXRS.Generallyspeaking,constraintannotationsinBeanValidationarecumulative(canbestrengthen)acrossagiventypehierarchywhile JAXRSannotationsareinheritedor,overriddenandignored. ForBeanValidationannotationsJerseyfollowstheconstraintannotationrulesdefinedintheBeanValidationspecification.

16.5.@ValidateOnExecution
AccordingtoBeanValidationspecification,validationisenabledbydefaultonlyforthesocalledconstrainedmethods.GettermethodsasdefinedbytheJava Beansspecificationarenotconstrainedmethods,sotheywillnotbevalidatedbydefault.Thespecialannotation@ V a l i d a t e O n E x e c u t i o n canbeusedto selectivelyenableanddisablevalidation.Forexample,youcanenablevalidationonmethodg e t E m a i l showninExample16.11,Validategetteron execution. Example16.11.Validategetteronexecution
1 2 3 4 5 6 7 8 9 1 0 1 1 @ P a t h ( " / " ) c l a s s M y R e s o u r c e C l a s s { @ E m a i l @ V a l i d a t e O n E x e c u t i o n p u b l i c S t r i n g g e t E m a i l ( ) { r e t u r n e m a i l } . . . }

Thedefaultvalueforthet y p e attributeof@ V a l i d a t e O n E x e c u t i o n isI M P L I C I T whichresultsinmethodg e t E m a i l beingvalidated.

Note
AccordingtoBeanValidationspecification@ V a l i d a t e O n E x e c u t i o n cannotbeoverriddenonceisdeclaredonamethod(i.e.insubclass/sub interface)andinthissituationsaV a l i d a t i o n E x c e p t i o n shouldberaised.Thisdefaultbehaviourcanbesuppressedbysetting ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECKproperty(Jerseyspecific)tot r u e .

16.6.Injecting
Jerseyallowsyoutoinjectregisteredresources/providersintoyourConstraintValidatorimplementationandyoucaninjectConfiguration,ValidatorFactoryand ValidatorasrequiredbyBeanValidationspec.

Note
InjectedConfiguration,ValidatorFactoryandValidatordonotinheritconfigurationprovidedbyValidationConfigandneedtobeconfigured manually. InjectionofJAXRScomponentsintoC o n s t r a i n t V a l i d a t o r sissupportedviaacustomC o n s t r a i n t V a l i d a t o r F a c t o r y providedbyJersey.Anexampleis showninExample16.12,InjectingUriInfointoaConstraintValidator. Example16.12.InjectingUriInfointoaConstraintValidator
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 p u b l i c c l a s s E m a i l V a l i d a t o r i m p l e m e n t s C o n s t r a i n t V a l i d a t o r < E m a i l , S t r i n g > { @ C o n t e x t p r i v a t e U r i I n f o u r i I n f o p u b l i c v o i d i n i t i a l i z e ( E m a i l e m a i l ) { . . . } p u b l i c b o o l e a n i s V a l i d ( S t r i n g v a l u e , C o n s t r a i n t V a l i d a t o r C o n t e x t c o n t e x t ) { / / U s e U r i I n f o . . . . } }

UsingacustomConstraintValidatorFactoryofyourowndisablesregistrationoftheoneprovidedbyJerseyandinjectionsupportforresources/providers(if needed)hastobeprovidedbythisnewimplementation.Example16.13,SupportforinjectingJersey'sresources/providersviaConstraintValidatorFactory. showshowthiscanbeachieved. Example16.13.SupportforinjectingJersey'sresources/providersviaConstraintValidatorFactory.


1 p u b l i c c l a s s I n j e c t i n g C o n s t r a i n t V a l i d a t o r F a c t o r y i m p l e m e n t s C o n s t r a i n t V a l i d a t o r F a c t o r y {

2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5

@ C o n t e x t p r i v a t e R e s o u r c e C o n t e x t r e s o u r c e C o n t e x t @ O v e r r i d e p u b l i c < T e x t e n d s C o n s t r a i n t V a l i d a t o r < ? , ? > > T g e t I n s t a n c e ( f i n a l C l a s s < T > k e y ) { r e t u r n r e s o u r c e C o n t e x t . g e t R e s o u r c e ( k e y ) } @ O v e r r i d e p u b l i c v o i d r e l e a s e I n s t a n c e ( f i n a l C o n s t r a i n t V a l i d a t o r < ? , ? > i n s t a n c e ) { / / N O O P } }

Note
ThisbehaviourmaylikelychangeinoneofthenextversionofJerseytoremovetheneedofmanuallyprovidingsupportforinjecting resources/providersfromJerseyinyourownC o n s t r a i n t V a l i d a t o r F a c t o r y implementationcode.

16.7.ErrorReporting
BeanValidationspecificationdefinesasmallhierarchyofexceptions(theyallinheritfromValidationException)thatcouldbethrownduringinitializationof validationengineor(forourcasemoreimportantly)duringvalidationofinput/outputvalues(ConstraintViolationException).Ifathrownexceptionisasubclass ofV a l i d a t i o n E x c e p t i o n exceptC o n s t r a i n t V i o l a t i o n E x c e p t i o n thenthisexceptionismappedtoaHTTPresponsewithstatuscode500(Internal ServerError).Ontheotherhand,whenaC o n s t r a i n t V i o l a t i o n E x c e p t i o n isthrowtwodifferentstatuscodewouldbereturned: 500(InternalServerError) Iftheexceptionwasthrownwhilevalidatingamethodreturntype. 400(BadRequest) Otherwise.

16.7.1.ValidationError
Bydefault,(duringmappingC o n s t r a i n t V i o l a t i o n E x c e p t i o n s)Jerseydoesn'treturnanyentitiesthatwouldincludevalidationerrorstotheclient.This defaultbehaviourcouldbechangedbyenablingServerProperties.BV_SEND_ERROR_IN_RESPONSEpropertyinyourapplication(Example16.1, ConfiguringJerseyspecificpropertiesforBeanValidation.).WhenthispropertyisenabledthenourcustomExceptionMapper<EextendsThrowable>(thatis handlingV a l i d a t i o n E x c e p t i o n s)wouldtransformC o n s t r a i n t V i o l a t i o n E x c e p t i o n (s)intoValidationError(s)andsetthisobject(collection)asthenew responseentitywhichJerseyisabletosenttotheclient.FourM e d i a T y p e sarecurrentlysupportedwhensendingV a l i d a t i o n E r r o r stotheclient:
t e x t / p l a i n t e x t / h t m l a p p l i c a t i o n / x m l a p p l i c a t i o n / j s o n

Note
Note:YouneedtoregisteroneoftheJSON(JAXB)providers(e.g.MOXy)tomarshallvalidationerrorstoJSON. Let'stakealookatValidationErrorclasstoseewhichpropertiesaresendtotheclient:
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 @ X m l R o o t E l e m e n t p u b l i c f i n a l c l a s s V a l i d a t i o n E r r o r { p r i v a t e S t r i n g m e s s a g e p r i v a t e S t r i n g m e s s a g e T e m p l a t e p r i v a t e S t r i n g p a t h p r i v a t e S t r i n g i n v a l i d V a l u e . . . }

Them e s s a g e propertyistheinterpolatederrormessage,m e s s a g e T e m p l a t e representsanoninterpolatederrormessage(orkeyfromyourconstraint definitione.g.{ j a v a x . v a l i d a t i o n . c o n s t r a i n t s . N o t N u l l . m e s s a g e } ),p a t h containsinformationaboutthepathinthevalidatedobjectgraphtothe propertyholdinginvalidvalueandi n v a l i d V a l u e isthestringrepresentationoftheinvalidvalueitself. HerearefewexamplesofV a l i d a t i o n E r r o r messagessenttoclient: Example16.14.V a l i d a t i o n E r r o r tot e x t / p l a i n
H T T P / 1 . 1 5 0 0 I n t e r n a l S e r v e r E r r o r C o n t e n t L e n g t h : 1 1 4 C o n t e n t T y p e : t e x t / p l a i n V a r y : A c c e p t S e r v e r : J e t t y ( 6 . 1 . 2 4 ) C o n t a c t w i t h g i v e n I D d o e s n o t e x i s t . ( p a t h = C o n t a c t C a r d R e s o u r c e . g e t C o n t a c t . < r e t u r n v a l u e > , i n v a l i d V a l u e = n u l l )

Example16.15.V a l i d a t i o n E r r o r tot e x t / h t m l
H T T P / 1 . 1 5 0 0 I n t e r n a l S e r v e r E r r o r C o n t e n t L e n g t h : . . . C o n t e n t T y p e : t e x t / p l a i n V a r y : A c c e p t S e r v e r : J e t t y ( 6 . 1 . 2 4 ) < d i v c l a s s = " v a l i d a t i o n e r r o r s " > < d i v c l a s s = " v a l i d a t i o n e r r o r " > < s p a n c l a s s = " m e s s a g e " > C o n t a c t w i t h g i v e n I D d o e s n o t e x i s t . < / s p a n > (

< s p a n c l a s s = " p a t h " > < s t r o n g > p a t h < / s t r o n g > = C o n t a c t C a r d R e s o u r c e . g e t C o n t a c t . < r e t u r n v a l u e > < / s p a n > , < s p a n c l a s s = " i n v a l i d v a l u e " > < s t r o n g > i n v a l i d V a l u e < / s t r o n g > = n u l l < / s p a n > ) < / d i v > < / d i v >

Example16.16.V a l i d a t i o n E r r o r toa p p l i c a t i o n / x m l
H T T P / 1 . 1 5 0 0 I n t e r n a l S e r v e r E r r o r C o n t e n t L e n g t h : . . . C o n t e n t T y p e : t e x t / p l a i n V a r y : A c c e p t S e r v e r : J e t t y ( 6 . 1 . 2 4 ) < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F 8 " ? > < v a l i d a t i o n E r r o r s > < v a l i d a t i o n E r r o r > < m e s s a g e > C o n t a c t w i t h g i v e n I D d o e s n o t e x i s t . < / m e s s a g e > < m e s s a g e T e m p l a t e > { c o n t a c t . d o e s . n o t . e x i s t } < / m e s s a g e T e m p l a t e > < p a t h > C o n t a c t C a r d R e s o u r c e . g e t C o n t a c t . & l t r e t u r n v a l u e & g t < / p a t h > < / v a l i d a t i o n E r r o r > < / v a l i d a t i o n E r r o r s >

Example16.17.V a l i d a t i o n E r r o r toa p p l i c a t i o n / j s o n
H T T P / 1 . 1 5 0 0 I n t e r n a l S e r v e r E r r o r C o n t e n t L e n g t h : 1 7 4 C o n t e n t T y p e : a p p l i c a t i o n / j s o n V a r y : A c c e p t S e r v e r : J e t t y ( 6 . 1 . 2 4 ) [ { " m e s s a g e " : " C o n t a c t w i t h g i v e n I D d o e s n o t e x i s t . " , " m e s s a g e T e m p l a t e " : " { c o n t a c t . d o e s . n o t . e x i s t } " , " p a t h " : " C o n t a c t C a r d R e s o u r c e . g e t C o n t a c t . < r e t u r n v a l u e > " } ]

16.8.Example
ToseeacompleteworkingexampleofusingBeanValidation(JSR349)withJerseyrefertotheBeanValidationexample.

Chapter17.EntityDataFiltering
TableofContents 17.1.EnablingandconfiguringEntityFilteringinyourapplication 17.2.ComponentsusedtodescribeEntityFilteringconcepts 17.3.Usingcustomannotationstofilterentities 17.3.1.ServersideEntityFiltering 17.3.2.ClientsideEntityFiltering 17.4.RolebasedEntityFilteringusing(j a v a x . a n n o t a t i o n . s e c u r i t y )annotations 17.5.Definingcustomhandlingforentityfilteringannotations 17.6.SupportingEntityDataFilteringincustomentityprovidersorframeworks 17.7.ModuleswithsupportforEntityDataFiltering 17.8.Examples SupportforEntityFilteringinJerseyintroducesaconvenientfacilityforreducingtheamountofdataexchangedoverthewirebetweenclientandserver withoutaneedtocreatespecializeddataviewcomponents.ThemainideabehindthisfeatureistogiveyouAPIsthatwillletyoutoselectivelyfilteroutany nonrelevantdatafromthemarshalledobjectmodelbeforesendingthedatatotheotherpartybasedonthecontextoftheparticularmessageexchange.This way,onlythenecessaryorrelevantportionofthedataistransferredoverthenetworkwitheachclientrequestorserverresponse,withoutaneedtocreate specialfacademodelsfortransferringtheselimitedsubsetsofthemodeldata. Entityfilteringfeatureallowsyoutodefineyourownentityfilteringrulesforyourentityclassesbasedonthecurrentcontext(e.g.matchedresourcemethod) andkeeptheserulesinoneplace(directlyinyourdomainmodel).WithJerseyentityfilteringfacilityitisalsopossibletoassignsecurityaccessrulestoentity classespropertiesandpropertyaccessors. Wewillfirstexplainthemainconceptsandthenwewillexploretheentityfilteringfeaturetopicsfromaperspectiveofbasicusecases, Section17.3,Usingcustomannotationstofilterentities Section17.4,RolebasedEntityFilteringusing(j a v a x . a n n o t a t i o n . s e c u r i t y )annotations aswellassomemorecomplexones. Section17.5,Definingcustomhandlingforentityfilteringannotations

Note
JerseyentityfilteringfeatureissupportedviaJerseyextensionmoduleslistedinSection17.7,ModuleswithsupportforEntityDataFiltering.

17.1.EnablingandconfiguringEntityFilteringinyourapplication
EntityFilteringsupportinJerseyisprovidedasanextensionmoduleandneedstobementionedexplicitlyinyourp o m . x m l file(incaseofusingMaven):
< d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . e x t < / g r o u p I d >

< a r t i f a c t I d > j e r s e y e n t i t y f i l t e r i n g < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Note
Ifyou'renotusingMavenmakesuretohavealsoallthetransitivedependencies(seejerseyentityfiltering)ontheclasspath. TheentityfilteringextensionmoduleprovidestwoF e a t u r e swhichyoucanregisterintoserver/clientruntimeinpriortouseEntityFilteringinanapplication: EntityFilteringFeature Filteringbasedonentityfilteringannotations(ori.e.externalconfigurationfile)createdusing@EntityFilteringmetaannotation. SecurityEntityFilteringFeature Filteringbasedonsecurity(j a v a x . a n n o t a t i o n . s e c u r i t y )andentityfilteringannotations. IfyouwanttousebothentityfilteringannotationsandsecurityannotationsforentitydatafilteringitisenoughtoregisterS e c u r i t y E n t i t y F i l t e r i n g F e a t u r e asthisfeatureregistersalsoE n t i t y F i l t e r i n g F e a t u r e . EntityfilteringcurrentlyrecognizesonepropertythatcanbepassedintotheConfigurationinstance(client/server): EntityFilteringFeature.ENTITY_FILTERING_SCOPE"j e r s e y . c o n f i g . e n t i t y F i l t e r i n g . s c o p e " Definesoneormoreannotationsthatshouldbeusedasentityfilteringscopewhenreading/writinganentity.

Note
Processingofentityfilteringannotationstocreateanentityfilteringscopeisdefinedbyfollowing:"R e q u e s t / R e s o u r c e e n t i t y a n n o t a t i o n s ">"C o n f i g u r a t i o n ">"R e s o u r c e m e t h o d / c l a s s a n n o t a t i o n s "(onserver). Youcanconfigureentityfilteringonserver(basic+securityexamples)asfollows: Example17.1.Registeringandconfiguringentityfilteringfeatureonserver.
1 2 3 4 5 6 7 n e w R e s o u r c e C o n f i g ( ) / / S e t e n t i t y f i l t e r i n g s c o p e v i a c o n f i g u r a t i o n . . p r o p e r t y ( E n t i t y F i l t e r i n g F e a t u r e . E N T I T Y _ F I L T E R I N G _ S C O P E , n e w A n n o t a t i o n [ ] { P r o j e c t D e t a i l e d V i e w . F a c t o r y . g e t ( ) } ) / / R e g i s t e r t h e E n t i t y F i l t e r i n g F e a t u r e . . r e g i s t e r ( E n t i t y F i l t e r i n g F e a t u r e . c l a s s ) / / F u r t h e r c o n f i g u r a t i o n o f R e s o u r c e C o n f i g . . r e g i s t e r ( . . . )

Example17.2.Registeringandconfiguringentityfilteringfeaturewithsecurityannotationsonserver.
1 2 3 4 5 6 7 n e w R e s o u r c e C o n f i g ( ) / / S e t e n t i t y f i l t e r i n g s c o p e v i a c o n f i g u r a t i o n . . p r o p e r t y ( E n t i t y F i l t e r i n g F e a t u r e . E N T I T Y _ F I L T E R I N G _ S C O P E , n e w A n n o t a t i o n [ ] { S e c u r i t y A n n o t a t i o n s . r o l e s A l l o w e d ( " m a n a g e r " / / R e g i s t e r t h e S e c u r i t y E n t i t y F i l t e r i n g F e a t u r e . . r e g i s t e r ( S e c u r i t y E n t i t y F i l t e r i n g F e a t u r e . c l a s s ) / / F u r t h e r c o n f i g u r a t i o n o f R e s o u r c e C o n f i g . . r e g i s t e r ( . . . )

Usesimilarstepstoregisterentityfilteringonclient: Example17.3.Registeringandconfiguringentityfilteringfeatureonclient.
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 f i n a l C l i e n t C o n f i g c o n f i g = n e w C l i e n t C o n f i g ( ) / / S e t e n t i t y f i l t e r i n g s c o p e v i a c o n f i g u r a t i o n . . p r o p e r t y ( E n t i t y F i l t e r i n g F e a t u r e . E N T I T Y _ F I L T E R I N G _ S C O P E , n e w A n n o t a t i o n [ ] { P r o j e c t D e t a i l e d V i e w . F a c t o r y . g e t ( ) } ) / / R e g i s t e r t h e E n t i t y F i l t e r i n g F e a t u r e . . r e g i s t e r ( E n t i t y F i l t e r i n g F e a t u r e . c l a s s ) / / F u r t h e r c o n f i g u r a t i o n o f C l i e n t C o n f i g . . r e g i s t e r ( . . . ) / / C r e a t e n e w c l i e n t . f i n a l C l i e n t c l i e n t = C l i e n t C l i e n t B u i l d e r . n e w C l i e n t ( c o n f i g ) / / U s e t h e c l i e n t .

17.2.ComponentsusedtodescribeEntityFilteringconcepts
Inthenextsectiontheentityfilteringfeatureswillbeillustratedonaprojecttrackingapplicationthatcontainsthreeclassesinit'sdomainmodelandfew resources(onlyP r o j e c t resourcewillbeshowninthischapter).ThefullsourcecodefortheexampleapplicationcanbefoundinJerseyEntityFiltering example. Supposetherearethreedomainmodelclasses(orentities)inourmodel:P r o j e c t ,U s e r andT a s k (getters/setterareomittedforbrevity). Example17.4.Project
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 p u b l i c c l a s s P r o j e c t { p r i v a t e L o n g i d p r i v a t e S t r i n g n a m e p r i v a t e S t r i n g d e s c r i p t i o n p r i v a t e L i s t < T a s k > t a s k s p r i v a t e L i s t < U s e r > u s e r s / / g e t t e r s a n d s e t t e r s }

Example17.5.User

1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4

p u b l i c c l a s s U s e r { p r i v a t e L o n g i d p r i v a t e S t r i n g n a m e p r i v a t e S t r i n g e m a i l p r i v a t e L i s t < P r o j e c t > p r o j e c t s p r i v a t e L i s t < T a s k > t a s k s / / g e t t e r s a n d s e t t e r s }

Example17.6.Task
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 p u b l i c c l a s s T a s k { p r i v a t e L o n g i d p r i v a t e S t r i n g n a m e p r i v a t e S t r i n g d e s c r i p t i o n p r i v a t e P r o j e c t p r o j e c t p r i v a t e U s e r u s e r / / g e t t e r s a n d s e t t e r s }

Toretrievetheentitiesfromservertoclient,wehavecreatedalsoacoupleofJAXRSresourcesfromwhosetheP r o j e c t s R e s o u r c e isshownasexample. Example17.7.ProjectsResource


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 @ P a t h ( " p r o j e c t s " ) @ P r o d u c e s ( " a p p l i c a t i o n / j s o n " ) p u b l i c c l a s s P r o j e c t s R e s o u r c e { @ G E T @ P a t h ( " { i d } " ) p u b l i c P r o j e c t g e t P r o j e c t ( @ P a t h P a r a m ( " i d " ) f i n a l L o n g i d ) { r e t u r n g e t D e t a i l e d P r o j e c t ( i d ) } @ G E T p u b l i c L i s t < P r o j e c t > g e t P r o j e c t s ( ) { r e t u r n g e t D e t a i l e d P r o j e c t s ( ) } }

17.3.Usingcustomannotationstofilterentities
Entityfilteringviaannotationsisbasedonan@EntityFilteringmetaannotation.Thismetaannotationisusedtoidentifyentityfilteringannotationsthatcanbe thenattachedto domainmodelclasses(supportedonboth,serverandclientsides),and resourcemethods/resourceclasses(onlyonserverside) Anexampleofentityfilteringannotationapplicabletoaclass,fieldormethodcanbeseeninExample17.8,ProjectDetailedViewbellow. Example17.8.ProjectDetailedView
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 @ T a r g e t ( { E l e m e n t T y p e . T Y P E , E l e m e n t T y p e . M E T H O D , E l e m e n t T y p e . F I E L D } ) @ R e t e n t i o n ( R e t e n t i o n P o l i c y . R U N T I M E ) @ D o c u m e n t e d @ E n t i t y F i l t e r i n g p u b l i c @ i n t e r f a c e P r o j e c t D e t a i l e d V i e w { / * * * F a c t o r y c l a s s f o r c r e a t i n g i n s t a n c e s o f { @ c o d e P r o j e c t D e t a i l e d V i e w } a n n o t a t i o n . * / p u b l i c s t a t i c c l a s s F a c t o r y e x t e n d s A n n o t a t i o n L i t e r a l < P r o j e c t D e t a i l e d V i e w > i m p l e m e n t s P r o j e c t D e t a i l e d V i e w { p r i v a t e F a c t o r y ( ) { } p u b l i c s t a t i c P r o j e c t D e t a i l e d V i e w g e t ( ) { r e t u r n n e w F a c t o r y ( ) } } }

SincecreatingannotationinstancesdirectlyinJavacodeisnottrivial,itisagoodpracticetoprovideaninnerannotationF a c t o r y classineachcustom filteringannotation,throughwhichnewinstancesoftheannotationcanbedirectlycreated.TheannotationfactoryclasscanbecreatedbyextendingtheHK2 A n n o t a t i o n L i t e r a l classandimplementingtheannotationinterfaceitself.Itshouldalsoprovideastaticfactorymethodthatwillcreateandreturnanew instanceoftheF a c t o r y classwheninvoked.Suchannotationinstancescanbethenpassedtotheclientandserverruntimestodefineoroverrideentity filteringscopes. Byplacinganentityfilteringannotationonanentity(class,fields,gettersorsetters)wedefineasocalledentityfilteringscopefortheentity.Thepurposeof entityfilteringscopeistoidentifypartsofthedomainmodelthatshouldbeprocessedwhenthemodelistobesentoverthewireinaparticularentityfiltering scope.Wedistinguishbetween: globalentityfilteringscope(definedbyplacingfilteringannotationonaclassitself),and localentityfilteringscope(definedbyplacingfilteringannotationonafield,getterorsetter)

Unannotatedmembersofadomainmodelclassareautomaticallyaddedtoallexistingglobalentityfilteringscopes.Ifthereisnoexplicitglobalentityfiltering scopedefinedonaclassadefaultscopeiscreatedforthisclasstogroupthesemembers. Creatingentityfilteringscopesusingcustomentityfilteringannotationsindomainmodelclassesisillustratedinthefollowingexamples. Example17.9.AnnotatedProject


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 p u b l i c c l a s s P r o j e c t { p r i v a t e L o n g i d p r i v a t e S t r i n g n a m e p r i v a t e S t r i n g d e s c r i p t i o n @ P r o j e c t D e t a i l e d V i e w p r i v a t e L i s t < T a s k > t a s k s @ P r o j e c t D e t a i l e d V i e w p r i v a t e L i s t < U s e r > u s e r s / / g e t t e r s a n d s e t t e r s }

Example17.10.AnnotatedUser
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 p u b l i c c l a s s U s e r { p r i v a t e L o n g i d p r i v a t e S t r i n g n a m e p r i v a t e S t r i n g e m a i l @ U s e r D e t a i l e d V i e w p r i v a t e L i s t < P r o j e c t > p r o j e c t s @ U s e r D e t a i l e d V i e w p r i v a t e L i s t < T a s k > t a s k s / / g e t t e r s a n d s e t t e r s }

Example17.11.AnnotatedTask
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 p u b l i c c l a s s T a s k { p r i v a t e L o n g i d p r i v a t e S t r i n g n a m e p r i v a t e S t r i n g d e s c r i p t i o n @ T a s k D e t a i l e d V i e w p r i v a t e P r o j e c t p r o j e c t @ T a s k D e t a i l e d V i e w p r i v a t e U s e r u s e r / / g e t t e r s a n d s e t t e r s }

Asyoucanseeintheexamplesabove,wehavedefined3separatescopesusing@ P r o j e c t D e t a i l e d V i e w ,@ U s e r D e t a i l e d V i e w and@ T a s k D e t a i l e d V i e w annotationsandwehaveappliedthesescopesselectivelytocertainfieldsinthedomainmodelclasses. Oncetheentityfilteringscopesareappliedtothepartsofadomainmodel,theentityfilteringfacility(whenenabled)willchecktheactivescopeswhenthe modelisbeingsentoverthewire,andfilteroutallpartsfromthemodelforwhichthereisnoactivescopesetinthegivencontext.Therefore,weneedaway howtocontrolthescopesactiveinanygivencontextinordertoprocessthemodeldatainacertainway(e.g.exposethedetailedview).Weneedtotellthe server/clientruntimewhichentityfilteringscopeswewanttoapply.Thereare2wayshowtodothisforclientsideand3waysforserverside: Outboundclientrequestorserverresponseprogrammaticallycreatedwithentityfilteringannotationsthatidentifythescopestobeapplied(available onboth,clientandserver) PropertyidentifyingtheappliedscopespassedthroughConfiguration(availableonboth,clientandserver) Entityfilteringannotationsidentifyingtheappliedscopesattachedtoaresourcemethodorclass(serversideonly) Whenthemultipleapproachesarecombined,theprioritiesofcalculatingtheappliedscopesareasfollows:E n t i t y a n n o t a t i o n s i n r e q u e s t o r r e s p o n s e >P r o p e r t y p a s s e d t h r o u g h C o n f i g u r a t i o n >A n n o t a t i o n s a p p l i e d t o a r e s o u r c e m e t h o d o r c l a s s . Inagraphofdomainmodelobjects,theentityfilteringscopesareappliedtotherootnodeaswellastransitivelytoallthechildnodes.Fieldsandchildnodes thatdonotmatchatleastasingleactivescopearefilteredout.Whenthescopematchingisperformed,annotationsappliedtothedomainmodelclassesand fieldsareusedtocomputethescopeforeachparticularcomponentofthemodel.Iftherearenoannotationsontheclassorit'sfields,thedefaultscopeis assumed.Duringthefiltering,first,theannotationsonrootmodelclassandit'sfieldsareconsidered.Forallcompositefieldsthathavenotbeenfilteredout, theannotationsonthereferencedchildclassandit'sfieldsareconsiderednext,andsoon.

17.3.1.ServersideEntityFiltering
TopassentityfilteringannotationsviaResponsereturnedfromaresourcemethodyoucanleveragetheResponse.ResponseBuilder#entity(Object, Annotation[])method.Thenextexampleillustratesthisapproach.Youwillalsoseewhyeverycustomentityfilteringannotationshouldcontainafactoryfor creatinginstancesoftheannotation. Example17.12.ProjectsResourceResponseentityfilteringannotations
1 2 3 4 5 6 7 8 @ P a t h ( " p r o j e c t s " ) @ P r o d u c e s ( " a p p l i c a t i o n / j s o n " ) p u b l i c c l a s s P r o j e c t s R e s o u r c e { @ G E T p u b l i c R e s p o n s e g e t P r o j e c t s ( @ Q u e r y P a r a m ( " d e t a i l e d " ) f i n a l b o o l e a n i s D e t a i l e d ) { r e t u r n R e s p o n s e . o k ( )

9 1 0 1 1 1 2 1 3

. e n t i t y ( n e w G e n e r i c E n t i t y < L i s t < P r o j e c t > > ( E n t i t y S t o r e . g e t P r o j e c t s ( ) ) { } , i s D e t a i l e d ? n e w A n n o t a t i o n [ ] { P r o j e c t D e t a i l e d V i e w . F a c t o r y . g e t ( ) } : n e w A n n o t a t i o n [ 0 ] ) . b u i l d ( ) } }

Annotatingaresourcemethod/classistypicallyeasieralthoughitislessflexibleandmayrequiremoreresourcemethodstobecreatedtocoverallthe alternativeusecasescenarios.Forexample: Example17.13.ProjectsResourceEntityfilteringannotationsonmethods


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 @ P a t h ( " p r o j e c t s " ) @ P r o d u c e s ( " a p p l i c a t i o n / j s o n " ) p u b l i c c l a s s P r o j e c t s R e s o u r c e { @ G E T p u b l i c L i s t < P r o j e c t > g e t P r o j e c t s ( ) { r e t u r n g e t D e t a i l e d P r o j e c t s ( ) } @ G E T @ P a t h ( " d e t a i l e d " ) @ P r o j e c t D e t a i l e d V i e w p u b l i c L i s t < P r o j e c t > g e t D e t a i l e d P r o j e c t s ( ) { r e t u r n E n t i t y S t o r e . g e t P r o j e c t s ( ) } }

ToseehowentityfilteringscopescanbeappliedusingaC o n f i g u r a t i o n property,seetheExample17.1,Registeringandconfiguringentityfilteringfeature onserver.example. WhenaP r o j e c t modelfromtheexampleaboveisrequestedinascoperepresentedby@ P r o j e c t D e t a i l e d V i e w entityfilteringannotation,theP r o j e c t modeldatasentoverthewirewouldcontain:


P r o j e c t i d ,n a m e ,d e s c r i p t i o n ,t a s k s ,u s e r s T a s k i d ,n a m e ,d e s c r i p t i o n U s e r i d ,n a m e ,e m a i l

Or,toillustratethisinJSONformat:
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9

{ " d e s c r i p t i o n " : " J e r s e y i s t h e o p e n s o u r c e ( u n d e r d u a l C D D L + G P L l i c e n s e ) J A X R S 2 . 0 ( J S R 3 3 9 ) p r o d u c t i o n q u a l i t y R e f e r e n c e I m " i d " : 1 , " n a m e " : " J e r s e y " , " t a s k s " : [ { " d e s c r i p t i o n " : " E n t i t y D a t a F i l t e r i n g " , " i d " : 1 , " n a m e " : " E N T _ F L T " } , { " d e s c r i p t i o n " : " O A u t h 1 + 2 " , " i d " : 2 , " n a m e " : " O A U T H " } ] , " u s e r s " : [ { " e m a i l " : " v e r y @ s e c r e t . c o m " , " i d " : 1 , " n a m e " : " J e r s e y R o b o t " } ] }

Forthedefaultentityfilteringscopethefilteredmodelwouldlooklike:
P r o j e c t i d ,n a m e ,d e s c r i p t i o n

OrinJSONformat:
1 2 3 4 5

{ " d e s c r i p t i o n " : " J e r s e y i s t h e o p e n s o u r c e ( u n d e r d u a l C D D L + G P L l i c e n s e ) J A X R S 2 . 0 ( J S R 3 3 9 ) p r o d u c t i o n q u a l i t y R e f e r e n c e I m p " i d " : 1 , " n a m e " : " J e r s e y " }

17.3.2.ClientsideEntityFiltering
AsmentionedaboveyoucandefineappliedentityfilteringscopesusingapropertyseteitherintheclientruntimeC o n f i g u r a t i o n (seeExample17.3, Registeringandconfiguringentityfilteringfeatureonclient.)orbypassingtheentityfilteringannotationsduringacreationofanindividualrequesttobesent toserver. Example17.14.ClientRequestentityfilteringannotations
1 2 3 4 C l i e n t B u i l d e r . n e w C l i e n t ( c o n f i g ) . t a r g e t ( u r i ) . r e q u e s t ( ) . p o s t ( E n t i t y . e n t i t y ( p r o j e c t , n e w A n n o t a t i o n [ ] { P r o j e c t D e t a i l e d V i e w . F a c t o r y . g e t ( ) } ) )

Youcanusethementionedmethodwithclientinjectedintoaresourceaswell. Example17.15.ClientRequestentityfilteringannotations
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 @ P a t h ( " c l i e n t s " ) @ P r o d u c e s ( " a p p l i c a t i o n / j s o n " ) p u b l i c c l a s s C l i e n t s R e s o u r c e { @ U r i ( " p r o j e c t s " ) p r i v a t e W e b T a r g e t t a r g e t @ G E T p u b l i c L i s t < P r o j e c t > g e t P r o j e c t s ( ) { r e t u r n t a r g e t . r e q u e s t ( ) . p o s t ( E n t i t y . e n t i t y ( p r o j e c t , n e w A n n o t a t i o n [ ] { P r o j e c t D e t a i l e d V i e w . F a c t o r y . g e t ( ) } ) ) } }

17.4.RolebasedEntityFilteringusing(j a v a x . a n n o t a t i o n . s e c u r i t y )annotations
Filteringthecontentsenttotheclient(orserver)basedontheauthorizedsecurityrolesisacommonlyrequiredusecase.Byregistering SecurityEntityFilteringFeatureyoucanleveragetheJerseyEntityFilteringfacilityinconnectionwithstandardj a v a x . a n n o t a t i o n . s e c u r i t y annotations exactlythesamewayasyouwouldwithcustomentityfilteringannotationsdescribedinpreviouschapters.Supportedsecurityannotationsare: @PermitAll, @RolesAllowed,and @DenyAll AlthoughthemechanicsoftheEntityDataFilteringfeatureusedforthesecurityannotationbasedfilteringisthesameaswiththeentityfilteringannotations, theprocessingofsecurityannotationsdiffersinafewimportantaspects: CustomSecurityContextshouldbesetbyacontainerrequestfilterinordertouse@ R o l e s A l l o w e d forrolebasedfilteringofdomainmodeldata (serverside) Thereisnoneedtoprovideentityfiltering(orsecurity)annotationsonresourcemethodsinordertodefineentityfilteringscopesfor@ R o l e s A l l o w e d thatisappliedtothedomainmodelcomponents,asalltheavailablerolesforthecurrentuserareautomaticallydeterminedusingtheinformationfrom theprovidedS e c u r i t y C o n t e x t (serversideonly).

Note
Instancesofsecurityannotations(tobeusedforprogrammaticallydefinedscopeseitheronclientorserver)canbecreatedusingoneofthe methodsintheSecurityAnnotationsfactoryclassthatispartoftheJerseyEntityFilteringAPI.

17.5.Definingcustomhandlingforentityfilteringannotations
Tocreateacustomentityfilteringannotationwithspecialhandling,i.e.anfieldaggregatorannotationusedtoannotateclassesliketheoneinExample17.16, Entityfilteringannotationwithcustommeaningitis,inmostcases,sufficienttoimplementandregisterthefollowingSPIcontracts: EntityProcessor ImplementationsofthisSPIareinvokedtoprocessentityclassandit'smembers.CustomimplementationscanextendfromAbstractEntityProcessor. ScopeResolver ImplementationsofthisSPIareinvokedtoretrieveentityfilteringscopesfromanarrayofprovidedannotations. Example17.16.Entityfilteringannotationwithcustommeaning
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 @ T a r g e t ( { E l e m e n t T y p e . T Y P E } ) @ R e t e n t i o n ( R e t e n t i o n P o l i c y . R U N T I M E ) @ E n t i t y F i l t e r i n g p u b l i c @ i n t e r f a c e F i l t e r i n g A g g r e g a t o r { / * * * E n t i t y f i l t e r i n g s c o p e t o a d d g i v e n f i e l d s t o . * / A n n o t a t i o n f i l t e r i n g S c o p e ( ) / * * * F i e l d s t o b e a p a r t o f t h e e n t i t y f i l t e r i n g s c o p e . * / S t r i n g [ ] f i e l d s ( ) }

17.6.SupportingEntityDataFilteringincustomentityprovidersorframeworks
TosupportEntityDataFilteringincustomentityproviders(e.g.asinExample17.17,EntityDataFilteringsupportinMOXyJSONbindingprovider),itis sufficientinmostofthecasestoimplementandregisterthefollowingSPIcontracts: ObjectProvider Tobeabletoobtainaninstanceofafilteringobjectmodelyourproviderunderstandsandcanacton.Theimplementationscanextend AbstractObjectProvider. ObjectGraphTransformer Totransformareadonlygenericrepresentationofadomainobjectmodelgraphtobeprocessedintoanentityfilteringobjectmodelyourprovider understandsandcanacton.TheimplementationscanextendAbstractObjectProvider. Example17.17.EntityDataFilteringsupportinMOXyJSONbindingprovider
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6

@ S i n g l e t o n p u b l i c c l a s s F i l t e r i n g M o x y J s o n P r o v i d e r e x t e n d s C o n f i g u r a b l e M o x y J s o n P r o v i d e r { @ I n j e c t p r i v a t e P r o v i d e r < O b j e c t P r o v i d e r < O b j e c t G r a p h > > p r o v i d e r @ O v e r r i d e p r o t e c t e d v o i d p r e W r i t e T o ( f i n a l O b j e c t o b j e c t , f i n a l C l a s s < ? > t y p e , f i n a l T y p e g e n e r i c T y p e , f i n a l A n n o t a t i o n [ ] a n n o t a t i o n s , f i n a l M e d i a T y p e m e d i a T y p e , f i n a l M u l t i v a l u e d M a p < S t r i n g , O b j e c t > h t t p H e a d e r s , f i n a l M a r s h a l l e r m a r s h a l l e r ) t h r o w s J A X B E x c e p t i o n { s u p e r . p r e W r i t e T o ( o b j e c t , t y p e , g e n e r i c T y p e , a n n o t a t i o n s , m e d i a T y p e , h t t p H e a d e r s , m a r s h a l l e r ) / / E n t i t y F i l t e r i n g . i f ( m a r s h a l l e r . g e t P r o p e r t y ( M a r s h a l l e r P r o p e r t i e s . O B J E C T _ G R A P H ) = = n u l l ) { f i n a l O b j e c t o b j e c t G r a p h = p r o v i d e r . g e t ( ) . g e t F i l t e r i n g O b j e c t ( g e n e r i c T y p e , t r u e , a n n o t a t i o n s ) i f ( o b j e c t G r a p h ! = n u l l ) { m a r s h a l l e r . s e t P r o p e r t y ( M a r s h a l l e r P r o p e r t i e s . O B J E C T _ G R A P H , o b j e c t G r a p h ) } } } @ O v e r r i d e p r o t e c t e d v o i d p r e R e a d F r o m ( f i n a l C l a s s < O b j e c t > t y p e , f i n a l T y p e g e n e r i c T y p e , f i n a l A n n o t a t i o n [ ] a n n o t a t i o n s , f i n a l M e d i a T y p e m e d i a T y p e , f i n a l M u l t i v a l u e d M a p < S t r i n g , S t r i n g > h t t p H e a d e r s , f i n a l U n m a r s h a l l e r u n m a r s h a l l e r ) t h r o w s J A X B E x c e p t i o n {

2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8

s u p e r . p r e R e a d F r o m ( t y p e , g e n e r i c T y p e , a n n o t a t i o n s , m e d i a T y p e , h t t p H e a d e r s , u n m a r s h a l l e r ) / / E n t i t y F i l t e r i n g . i f ( u n m a r s h a l l e r . g e t P r o p e r t y ( M a r s h a l l e r P r o p e r t i e s . O B J E C T _ G R A P H ) = = n u l l ) { f i n a l O b j e c t o b j e c t G r a p h = p r o v i d e r . g e t ( ) . g e t F i l t e r i n g O b j e c t ( g e n e r i c T y p e , f a l s e , a n n o t a t i o n s ) i f ( o b j e c t G r a p h ! = n u l l ) { u n m a r s h a l l e r . s e t P r o p e r t y ( M a r s h a l l e r P r o p e r t i e s . O B J E C T _ G R A P H , o b j e c t G r a p h ) } } } }

17.7.ModuleswithsupportforEntityDataFiltering
ListofmodulesfromJerseyworkspacethatsupportEntityFiltering: MOXy InordertouseEntityFilteringinmentionedmodulesyouneedtoexplicitlyregistereitherEntityFilteringFeatureorSecurityEntityFilteringFeaturetoactivate EntityFilteringforparticularmodule.

17.8.Examples
Toseeacompleteworkingexamplesofentityfilteringfeaturerefertothe: EntityFilteringexample EntityFilteringexample(withsecurityannotations)

Chapter18.MVCTemplates
TableofContents 18.1.Dependencies 18.2.RegistrationandConfiguration 18.3.Explicitvs.ImplicitViewTemplates 18.3.1.V i e w a b l e ExplicitViewTemplates 18.3.2.@ T e m p l a t e ImplicitViewTemplates 18.4.JSP 18.5.CustomTemplatingEngines 18.6.OtherExamples JerseyprovidesanextensiontosupporttheModelViewController(MVC)designpattern.InthecontextofJerseycomponents,theControllerfromtheMVC patterncorrespondstoaresourceclassormethod,theViewtoatemplateboundtotheresourceclassormethod,andtheModeltoaJavaobject(oraJava bean)returnedfromaresourcemethod.

18.1.Dependencies
JerseyMVCtemplatingsupportisprovidedbyJerseyasasetof(three)extensionmodules: jerseymvc ThebasemodulethatprovidesAPIandextensionSPIforMVCtemplatingsupportinJersey.ThismoduleisrequiredbyanyparticularMVCtemplating engineintegrationmodulethatimplementstheexposedSPI. jerseymvcfreemarker AnintegrationmodulewithFreemarkerbasedtemplatingengine.ThemoduleprovidesacustomT e m p l a t e P r o c e s s o r forFreemarkertemplatesanda setofrelatedenginespecificconfigurationproperties. jerseymvcjsp AnintegrationmoduleforJSPbasedtemplatingengine.ThemoduleprovidesacustomT e m p l a t e P r o c e s s o r forJSPtemplates,customtag implementationandasetofrelatedenginespecificconfigurationproperties.

Note
InatypicalsetupprojectsusingtheJerseyMVCtemplatingsupportwoulddependonthebasemodulethatprovidestheAPIandSPIanda singletemplatingenginemoduleforthetemplatingengineofyourchoice.Thesemodulesneedtobementionedexplicitlyinyourp o m . x m l file. IfyouwanttousejusttemplatingAPIinfrastructureprovidedbyJerseyfortheMVCtemplatingsupportinordertoimplementyourcustomsupportfora templatingengineotherthantheonesprovidedbyJersey(JSP/Freemarker),youwillneedtoaddthebasejerseymvcmoduleintothelistofyour dependencies:
1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . e x t < / g r o u p I d > < a r t i f a c t I d > j e r s e y m v c < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

TouseoneofthetemplatingenginesforwhichJerseyprovidestheintegrationimplementation(JSP/Freemarker)inyourproject,youneedtoaddthejersey mvcjsporjerseymvcfreemarkermoduletoyourp o m . x m l respectively:


1 2 3 4 5 1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . e x t < / g r o u p I d > < a r t i f a c t I d > j e r s e y m v c j s p < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y > < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . e x t < / g r o u p I d > < a r t i f a c t I d > j e r s e y m v c f r e e m a r k e r < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Bothofthesemodulestransitivelydependonthebasej e r s e y m v c ,soitisnotnecessarytoaddthebasej e r s e y m v c moduleexplicitlyintoyour dependencylist,howeveritisarecommendedMavenpracticetodoso.

IfyouarenotusingMavenyouneedtomakesuretohaveallrequiredtransitivedependencies(seejerseymvc/jerseymvcfreemarker/jerseymvcjsp)onthe classpath.

18.2.RegistrationandConfiguration
TousecapabilitiesofJerseyMVCtemplatingsupportinyourJAXRS/JerseyapplicationyouneedtoregisterFeaturesprovidedbythemodulesmentioned above.Forj e r s e y m v c itisMvcFeature,forj e r s e y m v c j s p it'sJspMvcFeatureandforj e r s e y m v c f r e e m a r k e r itisFreemarkerMvcFeature.

Note
BothJ s p M v c F e a t u r e andF r e e m a r k e r M v c F e a t u r e alsoregisterM v c F e a t u r e soyoudon'tneedtoregisteritexplicitlywhenusingthese JSP/Freemarkermodules. Example18.1.RegisteringM v c F e a t u r e
1 2 3 4 n e w R e s o u r c e C o n f i g ( ) . r e g i s t e r ( o r g . g l a s s f i s h . j e r s e y . s e r v e r . m v c . M v c F e a t u r e . c l a s s ) / / F u r t h e r c o n f i g u r a t i o n o f R e s o u r c e C o n f i g . . r e g i s t e r ( . . . )

Example18.2.RegisteringJ s p M v c F e a t u r e
1 2 3 4 n e w R e s o u r c e C o n f i g ( ) . r e g i s t e r ( o r g . g l a s s f i s h . j e r s e y . s e r v e r . m v c . j s p . J s p M v c F e a t u r e . c l a s s ) / / F u r t h e r c o n f i g u r a t i o n o f R e s o u r c e C o n f i g . . r e g i s t e r ( . . . )

Important
JerseywebapplicationsthatwanttouseMVCtemplatingsupportfeatureshouldberegisteredasServletfiltersratherthanServletsinthe application'sw e b . x m l .Thew e b . x m l lessdeploymentstyleintroducedinServlet3.0isnotsupportedatthemomentforwebapplicationsthat requireuseofJerseyMVCtemplatingsupport. EachofthethreeMVCmodulescontainsa* P r o p e r t i e s (e.g.F r e e m a r k e r M v c P r o p e r t i e s )filewhichdefinesasetofpropertiesthatcouldbesetinaJAX RSA p p l i c a t i o n /R e s o u r c e C o n f i g inordertotakeeffect,seetheExample18.3,SettingM v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H valuein R e s o u r c e C o n f i g andExample18.4,SettingF r e e m a r k e r M v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H valueinw e b . x m l . Followinglistcontainsdescriptionoftheavailableproperties:
M v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H "j e r s e y . c o n f i g . s e r v e r . m v c . t e m p l a t e B a s e p a t h "

Thebasepathwheretemplatesarelocated.
F r e e m a r k e r M v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H "j e r s e y . c o n f i g . s e r v e r . m v c . t e m p l a t e B a s e p a t h . f r e e m a r k e r "

ThebasepathwhereFreemarkertemplatesarelocated.
J s p M v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H "j e r s e y . c o n f i g . s e r v e r . m v c . t e m p l a t e B a s e p a t h . j s p "

ThebasepathwhereJSPtemplatesarelocated. Example18.3.SettingM v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H valueinR e s o u r c e C o n f i g


1 2 3 4 5 n e w R e s o u r c e C o n f i g ( ) . p r o p e r t y ( M v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H , " t e m p l a t e s " ) . r e g i s t e r ( M v c F e a t u r e . c l a s s ) / / F u r t h e r c o n f i g u r a t i o n o f R e s o u r c e C o n f i g . . r e g i s t e r ( . . . )

Example18.4.SettingF r e e m a r k e r M v c P r o p e r t i e s . T E M P L A T E _ B A S E _ P A T H valueinw e b . x m l
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 < s e r v l e t > < s e r v l e t n a m e > o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . f r e e m a r k e r . M y A p p l i c a t i o n < / s e r v l e t n a m e > < s e r v l e t c l a s s > o r g . g l a s s f i s h . j e r s e y . s e r v l e t . S e r v l e t C o n t a i n e r < / s e r v l e t c l a s s > < i n i t p a r a m > < p a r a m n a m e > j a v a x . w s . r s . A p p l i c a t i o n < / p a r a m n a m e > < p a r a m v a l u e > o r g . g l a s s f i s h . j e r s e y . e x a m p l e s . f r e e m a r k e r . M y A p p l i c a t i o n < / p a r a m v a l u e > < / i n i t p a r a m > < i n i t p a r a m > < p a r a m n a m e > j e r s e y . c o n f i g . s e r v e r . m v c . t e m p l a t e B a s e P a t h . f r e e m a r k e r < / p a r a m n a m e > < p a r a m v a l u e > f r e e m a r k e r < / p a r a m v a l u e > < / i n i t p a r a m > < l o a d o n s t a r t u p > 1 < / l o a d o n s t a r t u p > < / s e r v l e t >

18.3.Explicitvs.ImplicitViewTemplates
Note
Someofthepassages/examplesfromthisandthenextsectionwastakenfromMVCJblogarticlewrittenbyPaulSandozearlier. InJersey2.0,thebaseMVCAPI(excludingtheSPIpart)consistsoftwoclasses(intheo r g . g l a s s f i s h . j e r s e y . s e r v e r . m v c packageinbaseMVC module)thatwewillexploreinmoredetailnow,namelyViewableand@Template.Theseclassesdetermineswhichapproach(explicit/implicit)youwouldbe takingwhenworkingwithJerseyMVCtemplatingsupport.

18.3.1.V i e w a b l e ExplicitViewTemplates
Inthisapproacharesourcemethodexplicitlyreturnsareferencetoaviewtemplateandthedatamodeltobeused.ForthispurposetheViewableclasshas beenintroducedinJersey1andisalsopresent(underadifferentpackage)inJersey2.AsimpleexampleofusagecanbeseeninExample18.5,Using V i e w a b l e inaresourceclass. Example18.5.UsingV i e w a b l e inaresourceclass
1 2 p a c k a g e c o m . f o o

3 4 5 6 7 8 9 1 0

@ P a t h ( " f o o " ) p u b l i c c l a s s F o o { @ G E T p u b l i c V i e w a b l e g e t ( ) { r e t u r n n e w V i e w a b l e ( " i n d e x " , " F O O " ) } }

Inthisexample,theF o o JAXRSresourceclassisthecontrollerandtheV i e w a b l e instanceencapsulatestheprovideddatamodel(" F O O " string)anda namedreferencetotheassociatedviewtemplate(" i n d e x " ). Thetemplatenamereference" i n d e x " isarelativevaluethatJerseywillresolvetoitsabsolutetemplatereferenceusingthefullyqualifiedclassnameofF o o (moreonresolvingrelativetemplatenametotheabsoluteonecanbefoundintheJavaDocofViewableclass),which,inourcase,is:
" / c o m / f o o / F o o / i n d e x "

Jerseywillthensearchalltheregisteredtemplateprocessors(seeSection18.5,CustomTemplatingEngines)tofindatemplateprocessorthatcanresolve theabsolutetemplatereferencefurthertoa"processable"templatereference.Ifatemplateprocessorisfoundthenthe"processable"templateisprocessed usingthesupplieddatamodel. Let'schangetheresourceG E T methodinourF o o resourcealittle: Example18.6.UsingabsolutepathtotemplateinV i e w a b l e


1 2 3 4 @ G E T p u b l i c V i e w a b l e g e t ( ) { r e t u r n n e w V i e w a b l e ( " / i n d e x " , " F O O " ) }

Inthiscase,sincethetemplatereferencebeginswith" / " ,Jerseywillconsiderthereferencetobeabsolutealreadyandwillnotattempttoabsolutizeitagain. Thereferencewillbeused"asis"whenresolvingittoa"processable"templatereferenceasdescribedearlier.

Tip
AllHTTPmethodsmayreturnV i e w a b l e instances.ThusaP O S T methodmayreturnatemplatereferencetoatemplatethatproducesaview thatistheresultofprocessinganHTMLForm.

18.3.2.@ T e m p l a t e ImplicitViewTemplates
18.3.2.1.Resourceclasses
Aresourceclasscanhavetemplatesimplicitlyassociatedwithitvia@Templateannotation.Forexample,takealookattheresourceclasslistingin Example18.7,Using@ T e m p l a t e onaresourceclass. Example18.7.Using@ T e m p l a t e onaresourceclass
1 2 3 4 5 6 7 8 @ P a t h ( " f o o " ) @ T e m p l a t e p u b l i c c l a s s F o o { p u b l i c S t r i n g g e t F o o ( ) { r e t u r n " F O O " } }

Theexampleaboveusesalotofconventionsandrequiressomemoreexplanation.Firstofall,youmayhavenoticedthatthereisnoresourcemethod definedinthisJAXRSresource.Also,thereisnotemplatereferencedefined.Inthiscase,sincethe@ T e m p l a t e annotationplacedontheresourceclassdoes notcontainanyinformation,thedefaultrelativetemplatereference" i n d e x " willbeused.Lateritwillgetresolvedtoanabsolute" / c o m / f o o / F o o / i n d e x " templatereference.Asforthemissingresourcemethods,adefault@ G E T methodwillbeimplicitlygeneratedbyJerseyfortheF o o resource(ourMVC Controller).Theimplementationoftheimplicitlyaddedresourcemethodperformstheequivalentofthefollowingexplicitresourcemethod:
1 2 3 4 @ G E T p u b l i c V i e w a b l e g e t ( ) { r e t u r n n e w V i e w a b l e ( " i n d e x " , t h i s ) }

Asyoucansee,theresourceclassservesinthiscasealsoasamodel.Produciblemediatypesaredeterminedbasedonthe@ P r o d u c e s annotationdeclared ontheresourceclass,ifany.

Note
IncaseofaresourceclassbasedimplicitMVCviewtemplate,thecontrollerisalsothemodel.Inthiscasethetemplatereference" i n d e x " is special,itisthetemplatereferenceassociatedwiththecontrolleritself. Implicitsubresourcetemplatesarealsosupported,forexample,foratemplatereference" b a r " thatresolvestoanabsolutetemplatereference " / c o m / f o o / F o o / b a r " thatinturnresolvestoaprocessabletemplatereference.Following@ G E T methodisalsoimplicitlyaddedtotheF o o controllerthat performstheequivalentofthefollowingexplicitsubresourcemethod:
1 2 3 4 5 @ G E T @ P a t h ( " { i m p l i c i t v i e w p a t h p a r a m e t e r } " ) p u b l i c V i e w a b l e g e t ( @ P a t h P a r a m e t e r ( " { i m p l i c i t v i e w p a t h p a r a m e t e r } " ) S t r i n g t e m p l a t e ) { r e t u r n n e w V i e w a b l e ( t e m p l a t e , t h i s ) }

Inotherwords,aHTTPG E T requesttoa" / f o o / b a r " wouldbehandledbythisautogeneratedmethodintheF o o resourceandwoulddelegatetherequest toaregisteredtemplateprocessorsupportsprocessingoftheabsolutetemplatereference" / c o m / f o o / F o o / b a r " ,whilethemodelisstillaninstanceofthe JAXRSresourceclassF o o .

18.3.2.2.Resourcemethods
Incasearesourcemethodisannotatedwith@TemplateannotationthenthereturnvalueofthemethoddefinestheMVCmodelpart.Theprocessingofsuch amethodisthenessentiallythesameasifthereturntypeofthemethodwasaninstanceoftheViewableclass.Ifamethodisannotatedwith@ T e m p l a t e and isalsoreturningaV i e w a b l e instancethenthevalues(r e s o l v i n g C l a s s )fromtheV i e w a b l e instancetakeprecedenceoverthosedefinedintheannotation. Produciblemediatypesaredeterminedfromthemethod's@ P r o d u c e s annotation.

Note
Implicitviewtemplatessupportworksdynamically(asisthecaseforexplicitMVC)soitispossible(ifthedeploymentsystemisconfigured correctly)toaddormodifytemplateswhiletheapplicationisrunning.

18.4.JSP
Asstatedearlier,JerseyprovidessupportforJSPtemplatesinjerseymvcjspextensionmodule.ThereisaJSPtemplateprocessorthatresolvesabsolute templatereferencestoprocessabletemplatereferencesrepresentedasJSPpagesasfollows: Procedure18.1.ResolvingJSPprocessabletemplatereference 1. iftheabsolutetemplatereferencedoesnotendin" . j s p " appendthissuffixtothereferenceand 2. ifS e r v l e t . g e t R e s o u r c e returnsanonn u l l valuefortheappendedreferencethenreturntheappendedreferenceastheprocessabletemplate referenceotherwisereturnn u l l (toindicatetheabsolutereferencehasnotbeenresolvedbytheJSPtemplateprocessor). Thustheabsolutetemplatereference" / c o m / f o o / F o o / i n d e x " wouldberesolvedto" / c o m / f o o / F o o / i n d e x . j s p " ,providedthereexistsa " / c o m / f o o / F o o / i n d e x . j s p " JSPpageinthewebapplication. Jerseywillassignthemodelinstancetotheattributenamed"i t ".Sointhecaseoftheimplicitexampleitispossibletoreferecethef o o propertyontheF o o resourcefromtheJSPtemplateasfollows:
1 < h 1 > $ { i t . f o o } < / h 1 >

18.5.CustomTemplatingEngines
Toaddsupportforother(custom)templatingenginesintoJerseyMVCTemplatingfacility,youneedtoimplementtheTemplateProcessorandregisterthis classintoyourapplication.

Tip
Whenwritingtemplateprocessorsitisrecommendthatyouuseanappropriateuniquesuffixfortheprocessabletemplatereferences.Insuch caseitisthenpossibletoeasilysupportmixingofmultipletemplatingenginesinasingleapplicationwithoutanyconflicts. Example18.8.CustomTemplateProcessor
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 @ P r o v i d e r c l a s s M y T e m p l a t e P r o c e s s o r i m p l e m e n t s T e m p l a t e P r o c e s s o r < S t r i n g > { @ O v e r r i d e p u b l i c S t r i n g r e s o l v e ( S t r i n g p a t h , f i n a l M e d i a T y p e m e d i a T y p e ) { f i n a l S t r i n g e x t e n s i o n = " . t e s t p " i f ( ! p a t h . e n d s W i t h ( e x t e n s i o n ) ) { p a t h = p a t h + e x t e n s i o n } f i n a l U R L u = t h i s . g e t C l a s s ( ) . g e t R e s o u r c e ( p a t h ) r e t u r n u = = n u l l ? n u l l : p a t h } @ O v e r r i d e p u b l i c v o i d w r i t e T o ( S t r i n g t e m p l a t e R e f e r e n c e , V i e w a b l e v i e w a b l e , M e d i a T y p e m e d i a T y p e , O u t p u t S t r e a m o u t ) t h r o w s I O E x c e p t i o n { f i n a l P r i n t S t r e a m p s = n e w P r i n t S t r e a m ( o u t ) p s . p r i n t ( " p a t h = " ) p s . p r i n t ( t e m p l a t e R e f e r e n c e ) p s . p r i n t l n ( ) p s . p r i n t ( " m o d e l = " ) p s . p r i n t ( v i e w a b l e . g e t M o d e l ( ) . t o S t r i n g ( ) ) p s . p r i n t l n ( ) } }

Example18.9.RegisteringcustomTemplateProcessor
1 2 3 4 n e w R e s o u r c e C o n f i g ( ) . r e g i s t e r ( M y T e m p l a t e P r o c e s s o r . c l a s s ) / / F u r t h e r c o n f i g u r a t i o n o f R e s o u r c e C o n f i g . . r e g i s t e r ( . . . )

18.6.OtherExamples
ToseeanexampleofMVC(JSP)templatingsupportinJerseyrefertotheMVC(Bookstore)example.

Chapter19.Monitoringanddiagnostics
TableofContents 19.1.Introduction 19.2.EventListeners 19.2.1.GuidelinesforimplementingJerseyeventlisteners 19.2.2.MonitoringStatistics 19.2.3.MonitoringStatisticsasMBeans

19.1.Introduction
Important
JerseymonitoringsupporthasbeenreleasedasabetareleaseinJersey2.1version.Assuch,theexposedmonitoringpublicAPIsand functionalitydescribedinthissectionmaychangeinthefutureJerseyreleases. JerseyprovidesfunctionalityformonitoringJAXRS/Jerseyapplications.Applicationmonitoringisusefulincaseswhenyouneedtoidentifytheperformance hotspotsinyourJAXRSapplication,observeexecutionstatisticsofparticularresourcesorlistentoapplicationorrequestlifecycleevents.Notethatthis

functionalityisJerseyspecificextensiontoJAXRSAPI. Jerseymonitoringsupportisdividedintothreefunctionalareas: EventListeners Eventlistenersallowuserstoreceiveandprocessapredefinedsetofeventsthatoccurduringaapplicationlifecycle(suchasapplicationinitialization, applicationdestroy)aswellasrequestprocessinglifecycleevents(requeststarted,resourcemethodfinished,exceptionthrown,etc.).Thisfeatureis alwaysenabledinJerseyserverruntimeandisleveragedbytheothermonitoringfeatures. MonitoringStatistics Jerseycanbeconfiguredtoprocesslifecycleeventsinordertoexposeawiderangeofruntimemonitoringstatisticstotheenduser.Thestatisticsare accessibletroughaninjectableMonitoringStatisticsinterface.Thestatisticsprovidegeneralinformationabouttheapplicationaswellasfinegrained executionstatisticsonparticularresourcesandsubresourcesandexposedURIs.Forperformancereasons,thisfunctionalitymustbeexplicitlyenabled priorusing. JMXMBeanswithstatistics InadditiontotheinjectableM o n i t o r i n g S t a t i s t i c s data,JerseyisabletoexposethestatisticsasJMXMBeans(forexampleApplicationMXBean). JerseymonitoringMXBeanscanbeaccessedprogrammaticallyusingJMXAPIsorbrowsedviaJMXenabledtool(J C o n s o l e forexample).This functionalityis,too,bydefaultdisabledforperformancereasonsandmustbeenabledifneeded. AllmonitoringrelatedAPIs(beta!)canbefoundinthej e r s e y s e r v e r moduleino r g . g l a s s f i s h . j e r s e y . s e r v e r . m o n i t o r i n g package.Monitoringin Jerseyiscurrentlysupportedontheserverside.

19.2.EventListeners
Jerseydefinestwotypesofeventlistenersthatyoucanimplementandregisterwithyourapplication: ApplicationEventListenerforlisteningtoapplicationevents,and RequestEventListenerforlisteningtoeventsofrequestprocessing. Onlythefirsttype,A p p l i c a t i o n E v e n t L i s t e n e r canbedirectlyregisteredasanapplicationwideprovider.TheR e q u e s t E v e n t L i s t e n e r isdesignedtobe specifictoeveryrequestandcanbeonlyreturnedfromtheA p p l i c a t i o n E v e n t L i s t e n e r assuch. Let'sstartwithanexample.ThefollowingexamplesshowsimpleimplementationsofJerseyeventlistenersaswellasatestJAXRSresourcethatwillbe monitored. Example19.1.Applicationeventlistener
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 p u b l i c c l a s s M y A p p l i c a t i o n E v e n t L i s t e n e r i m p l e m e n t s A p p l i c a t i o n E v e n t L i s t e n e r { p r i v a t e v o l a t i l e i n t r e q u e s t C n t = 0 @ O v e r r i d e p u b l i c v o i d o n E v e n t ( A p p l i c a t i o n E v e n t e v e n t ) { s w i t c h ( e v e n t . g e t T y p e ( ) ) { c a s e I N I T I A L I Z A T I O N _ F I N I S H E D : S y s t e m . o u t . p r i n t l n ( " A p p l i c a t i o n " + e v e n t . g e t R e s o u r c e C o n f i g ( ) . g e t A p p l i c a t i o n N a m e ( ) + " w a s i n i t i a l i z e d . " ) b r e a k c a s e D E S T R O Y _ F I N I S H E D : S y s t e m . o u t . p r i n t l n ( " A p p l i c a t i o n " + e v e n t . g e t R e s o u r c e C o n f i g ( ) . g e t A p p l i c a t i o n N a m e ( ) d e s t r o y e d . " ) b r e a k } } @ O v e r r i d e p u b l i c R e q u e s t E v e n t L i s t e n e r o n R e q u e s t ( R e q u e s t E v e n t r e q u e s t E v e n t ) { r e q u e s t C n t + + S y s t e m . o u t . p r i n t l n ( " R e q u e s t " + r e q u e s t C n t + " s t a r t e d . " ) / / r e t u r n t h e l i s t e n e r i n s t a n c e t h a t w i l l h a n d l e t h i s r e q u e s t . r e t u r n n e w M y R e q u e s t E v e n t L i s t e n e r ( r e q u e s t C n t ) } }

Example19.2.Requesteventlistener
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 p u b l i c c l a s s M y R e q u e s t E v e n t L i s t e n e r i m p l e m e n t s R e q u e s t E v e n t L i s t e n e r { p r i v a t e f i n a l i n t r e q u e s t N u m b e r p r i v a t e f i n a l l o n g s t a r t T i m e p u b l i c M y R e q u e s t E v e n t L i s t e n e r ( i n t r e q u e s t N u m b e r ) { t h i s . r e q u e s t N u m b e r = r e q u e s t N u m b e r s t a r t T i m e = S y s t e m . c u r r e n t T i m e M i l l i s ( ) } @ O v e r r i d e p u b l i c v o i d o n E v e n t ( R e q u e s t E v e n t e v e n t ) { s w i t c h ( e v e n t . g e t T y p e ( ) ) { c a s e R E S O U R C E _ M E T H O D _ S T A R T : S y s t e m . o u t . p r i n t l n ( " R e s o u r c e m e t h o d " + e v e n t . g e t U r i I n f o ( ) . g e t M a t c h e d R e s o u r c e M e t h o d ( ) . g e t H t t p M e t h o d ( ) + " s t a r t e d f o r r e q u e s t " + r e q u e s t N u m b e r ) b r e a k c a s e F I N I S H E D : S y s t e m . o u t . p r i n t l n ( " R e q u e s t " + r e q u e s t N u m b e r + " f i n i s h e d . P r o c e s s i n g t i m e " + ( S y s t e m . c u r r e n t T i m e M i l l i s ( ) s t a r t T i m e ) + " m s . " ) b r e a k } } }

Example19.3.Eventlistenertestresource
1 2 3 @ P a t h ( " r e s o u r c e " ) p u b l i c c l a s s T e s t R e s o u r c e { @ G E T

4 5 6 7 8 9 1 0 1 1 1 2

p u b l i c S t r i n g g e t S o m e t h i n g ( ) { r e t u r n " g e t " } @ P O S T p u b l i c S t r i n g p o s t S o m e t h i n g ( S t r i n g e n t i t y ) { r e t u r n " p o s t " } }

Oncethelistenersandthemonitoredresourceisdefined,it'stimetoinitializeourapplication.ThefollowingpieceofcodeshowsaResourceConfigthatis usedtoinitializetheapplication(pleasenotethatonlyA p p l i c a t i o n E v e n t L i s t e n e r isregisteredasprovider).


1 2 3 R e s o u r c e C o n f i g r e s o u r c e C o n f i g = n e w R e s o u r c e C o n f i g ( T e s t R e s o u r c e . c l a s s , M y A p p l i c a t i o n E v e n t L i s t e n e r . c l a s s ) . s e t A p p l i c a t i o n N a m e ( " m y m o n i t o r e d a p p l i c a t i o n " )

OurexampleapplicationnowcontainsasimpleresourceT e s t R e s o u r c e thatdefinesresourcemethodsforG E T andP O S T andacustom M y A p p l i c a t i o n E v e n t L i s t e n e r eventlistener. TheregisteredM y A p p l i c a t i o n E v e n t L i s t e n e r implementstwomethodsdefinedbytheA p p l i c a t i o n E v e n t L i s t e n e r interface.Amethodo n E v e n t ( ) handlesallapplicationlifecycleevents.Inourcasethemethodhandlesonly2applicationeventsinitializationanddestroy.Othereventtypesareignored.All applicationeventtypesaredefinedinApplicationEvent. T y p e .Thesecondmethodo n R e q u e s t isinvokedbyJerseyruntimeeverytimeanewrequestis received.TherequesteventtypepassedtothemethodisalwaysS T A R T .Ifyouwanttolistentoanyotherrequestlifecycleeventsforthenewrequest,you areexpectedtoreturnaninstanceofR e q u e s t E v e n t L i s t e n e r thatwillhandletherequest.Itisimportanttounderstand,thattheinstancewillhandleonlythe requestforwhichithasbeenreturnedfromanA p p l i c a t i o n E v e n t L i s t e n e r . o n R e q u e s t methodandnotanyotherrequests.Inourcasethereturned requesteventlistenerkeepsinformationabouttherequestnumberofthecurrentrequestandastarttimeoftherequestwhichislaterusedtoprintoutthe requestprocessingtimesstatistics.Thisdemonstratestheprincipleoflisteningtorequestevents:foronerequestthereisaoneinstancewhichcanbeused toholdalltheinformationabouttheparticularrequest.Inotherwords,R e q u e s t E v e n t L i s t e n e r isdesignedtobeimplicitlyrequestscoped. JerseyrepresentslifecycleeventsviaRequestEventandApplicationEventtypes.Instancesoftheseclassescontaininformationaboutrespectiveevents.The mostimportantinformationistheeventtypeT y p e retrievableviag e t T y p e ( ) method,whichidentifiesthetypeoftheevent.Eventscontainalsoadditional informationthatisdependentonaparticulareventtype.Thisinformationcanberetrievedviaeventgetters.Again,somegettersreturnvalidinformationforall eventtypes,somearespecifictoasubsetofeventtypes.Forexample,intheR e q u e s t E v e n t ,theg e t E x c e p t i o n C a u s e ( ) methodreturnsvalidinformation onlywheneventtypeisO N _ E X C E P T I O N .Ontheotherhand,ag e t C o n t a i n e r R e q u e s t ( ) canbeusedtoreturncurrentrequestcontextforanyrequestevent type.Seejavadocofeventsandeventtypestogetfamiliarwitheventtypesandinformationvalidforeacheventtype. OurM y R e q u e s t E v e n t L i s t e n e r implementationisfocusedonprocessing2requestevents.First,itlistensforaneventthatistriggeredbeforearesource methodisexecuted.Also,ithookstoa"requestfinished"event.Asmentionedearlier,therequesteventS T A R T ishandledonlyinthe M y A p p l i c a t i o n E v e n t L i s t e n e r .TheS T A R T eventtypewillneverbeinvokedonR e q u e s t E v e n t L i s t e n e r .Thereforethelogicformeasuringthes t a r t T i m e isintheconstructorwhichisinvokedfromM y A p p l i c a t i o n E v e n t L i s t e n e r . o n R e q u e s t ( ) .AnattempttohandlingtherequestS T A R T eventina R e q u e s t E v e n t L i s t e n e r . o n E v e n t ( ) methodwouldbeamistake. Let'sdeploytheapplicationanduseasimpletestclientcodetoproducesomeactivityinordertospawnnewevents:
1 2 3 t a r g e t . p a t h ( " r e s o u r c e " ) . r e q u e s t ( ) . p o s t ( E n t i t y . e n t i t y ( " p o s t " , M e d i a T y p e . T E X T _ P L A I N _ T Y P E ) ) t a r g e t . p a t h ( " r e s o u r c e " ) . r e q u e s t ( ) . g e t ( )

Inthecodeabove,thet a r g e t isaWebTargetinstancepointingtotheapplicationcontextrootpath.UsingtheChapter5,ClientAPI,weinvokeG E T andP O S T methodsontheM y R e s o u r c e JAXRSresourceclassthatweimplementedearlier. Whenwestarttheapplication,runthetestclientandthenstoptheapplication,theconsoleoutputforthedeployedserversideapplicationwouldcontainthe followingoutput:


A p p l i c a t i o n m y m o n i t o r e d a p p l i c a t i o n w a s i n i t i a l i z e d . R e q u e s t 1 s t a r t e d . R e s o u r c e m e t h o d P O S T s t a r t e d f o r r e q u e s t 1 R e q u e s t 1 f i n i s h e d . P r o c e s s i n g t i m e 3 3 0 m s . R e q u e s t 2 s t a r t e d . R e s o u r c e m e t h o d G E T s t a r t e d f o r r e q u e s t 2 R e q u e s t 2 f i n i s h e d . P r o c e s s i n g t i m e 4 m s . A p p l i c a t i o n m y m o n i t o r e d a p p l i c a t i o n d e s t r o y e d .

19.2.1.GuidelinesforimplementingJerseyeventlisteners
Implementeventlistenersasthreadsafe.Whileindividualeventswillbearrivingserially,individuallistenerinvocationsmayoccurfromdifferentthreads. ThusmakesurethatyourlistenersareprocessingdatasafelywithrespecttotheirJavaMemoryModelvisibility(intheexampleabovethefields r e q u e s t N u m b e r ,s t a r t T i m e ofM y R e q u e s t E v e n t L i s t e n e r arefinalandthereforethesamevalueisvisibleforallthreadsexecutingtheo n E v e n t ( ) method). Donotblockthethreadexecutingtheeventlistenersbyperforminglongrunningtasks.Executionofeventlistenersisapartofthestandardapplication andrequestprocessingandassuchneedstofinishasquicklyaspossibletoavoidnegativeimpactonoverallapplicationperformance. DonottrytomodifymutableobjectsreturnedfromA p p l i c a t i o n E v e n t andR e q u e s t E v e n t getterstoavoidexperiencingundefinedbehavior.Events listenersshouldusetheinformationforreadonlypurposesonly.Usedifferenttechniqueslikefilters,interceptorsorotherproviderstomodifythe processingofrequestsandapplications.Eventhoughmodificationmightbepossibleandmightworkasdesirednow,yourcodeisinriskofproducing intermittentfailuresorunexpectedbehaviour(forexampleaftermigratingtonewJerseyversion). Ifyoudonotwanttolistentorequestevents,donotreturnanemptylistenerintheo n R e q u e s t ( ) method.Returnn u l l instead.Returningempty listenermighthaveanegativeperformanceimpact.DonotrelyonJIToptimizingouttheemptylistenerinvocationcode. Ifyoumissanyeventtypeoranydetailintheevents,letusknowviaJerseyusermailinglist.

19.2.2.MonitoringStatistics
Eventlistenersdescribedintheprevioussectionareallpurposefacility.Forexample,youmaydecidetousethemtomeasurevariousexecutionstatisticsof yourapplication.Whilethismightbeaneasytaskforsimplestatisticslike"howmuchtimewasspentonexecutionofeachJavamethod?",nevertheless,ifyou wanttomeasurestatisticsbasedonURIsandindividualresources,theimplementationmightgetrathercomplexsoon,especiallywhenconsideringsub resourcesandsubresourcelocators.Tosaveyouthetrouble,Jerseyprovidesfeatureforcollectingeventsandcalculatingapredefinedsetofmonitoring andexecutionstatistics,includingapplicationconfiguration,exceptionmappersexecution,minimum/maximum/averageexecutiontimesforindividualresource methodsaswellasentirerequestprocessingetc. Calculatingthemonitoringstatisticshasobviouslyaperformanceimpact,thereforethisfeatureisdisabledbydefault.Toenablethefeature,setthefollowing configurationpropertytot r u e :
j e r s e y . c o n f i g . s e r v e r . m o n i t o r i n g . s t a t i s t i c s . e n a b l e d = t r u e

ThepropertydescriptioncanbefoundinServerProperties.MONITORING_STATISTICS_ENABLEDThiswillcalculatethestatistics.Theeasiestwayhowto getstatisticsistoletJerseytoinjectthem.Seethefollowingexample:

Example19.4.InjectingMonitoringStatistics
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 @ P a t h ( " r e s o u r c e " ) p u b l i c s t a t i c c l a s s S t a t i s t i c s R e s o u r c e { @ I n j e c t P r o v i d e r < M o n i t o r i n g S t a t i s t i c s > m o n i t o r i n g S t a t i s t i c s P r o v i d e r @ G E T p u b l i c S t r i n g g e t S o m e t h i n g ( ) { f i n a l M o n i t o r i n g S t a t i s t i c s s n a p s h o t = m o n i t o r i n g S t a t i s t i c s P r o v i d e r . g e t ( ) . s n a p s h o t ( ) f i n a l T i m e W i n d o w S t a t i s t i c s t i m e W i n d o w S t a t i s t i c s = s n a p s h o t . g e t R e q u e s t S t a t i s t i c s ( ) . g e t T i m e W i n d o w S t a t i s t i c s ( ) . g e t ( 0 l ) r e t u r n " r e q u e s t c o u n t : " + t i m e W i n d o w S t a t i s t i c s . g e t R e q u e s t C o u n t ( ) + " , a v e r a g e r e q u e s t p r o c e s s i n g [ m s ] : " + t i m e W i n d o w S t a t i s t i c s . g e t A v e r a g e D u r a t i o n ( ) } } }

MonitoringStatisticsareinjectedintotheresourceusingan@Injectannotation.PleasenotetheusageoftheProviderforinjection(itwillbediscussedlater). Firstly,thesnapshotofstatisticsisretrievedbythes n a p s h o t ( ) method.Thesnapshotofstatisticsisanimmutablecopyofstatisticswhichdoesnotchange overthetime.Additionally,datainasnapshotareconsistent.It'srecommendedtocreatesnapshotsbeforeworkingwiththestatisticsdataandthenprocess thesnapshotdata.Workingwithoriginalnonsnapshotdatamakessensewhendataconsistencyisnotimportantandperformanceisofhighestconcern. Whileitiscurrentlynotthecase,theinjectednonsnapshotdatamaybeimplementedasmutableforperformancereasonsinafuturereleaseofJersey. Theinjectedmonitoringstatisticsrepresenttherootofthecollectedstatisticshierarchy.Thehierarchycanbetraversedtoretrieveanypartialstatisticsdata. Intheexample,weretrievecertainrequestTimeWindowStatisticsdata.Inourcase,thosearetherequestexecutionstatisticsforatimewindowdefinedby longvalue0whichmeansunlimitedtimewindow.Thismeansweareretrievingtheglobalrequestexecutionstatisticsmeasuredsinceastartofthe application.Finally,requestcountandaveragedurationfromthestatisticsareusedtoproducetheStringresponse.WhenweinvokefewG E T requestsonthe S t a t i s t i c s R e s o u r c e ,wegetthefollowingconsoleoutput:
r e q u e s t c o u n t : 1 , a v e r a g e r e q u e s t p r o c e s s i n g [ m s ] : 2 6 0 r e q u e s t c o u n t : 2 , a v e r a g e r e q u e s t p r o c e s s i n g [ m s ] : 1 3 5 r e q u e s t c o u n t : 3 , a v e r a g e r e q u e s t p r o c e s s i n g [ m s ] : 9 3 r e q u e s t c o u n t : 4 , a v e r a g e r e q u e s t p r o c e s s i n g [ m s ] : 7 3

Let'slookcloseratMonitoringStatisticsinterface.M o n i t o r i n g S t a t i s t i c s interfacedefinesgettersbywhichothernestedstatisticscanberetrieved.All statisticsareinthesamepackageandendswithS t a t i s t i c s postfix.Statisticsinterfacesarethefollowing: MonitoringStatistics maintoplevelstatistics ApplicationStatistics mostlyconfigurationoftheapplication


R e s p o n s e S t a t i s t i c s

responsestatistics(eg.responsestatuscodesandtheircount) ResourceStatistics statisticsofexecutionofresources(resourceclassesorresourceURIs) ResourceMethodStatistics statisticsofexecutionofresourcemethods ExecutionStatistics statisticofexecutionofatarget(resource,request,resourcemethod) TimeWindowStatistics statisticsofexecutiontimeinspecificinterval(eg.executionsinlast5minutes) EachtimemonitoredtargetcontainsE x e c u t i o n S t a t i s t i c s .So,forexampleresourcemethodcontainsexecutionstatisticsofitsexecution.Each E x e c u t i o n S t a t i s t i c s containsmultipleT i m e W i n d o w S t a t i s t i c s .Currently,eachE x e c u t i o n S t a t i s t i c s containsT i m e W i n d o w S t a t i s t i c s forthesetime windows: 0:unlimited=>allexecutionsincestartoftheapplication 1000:1s=>statsmeasuredinlast1second 15000:15s=>statsmeasuredinlast15seconds 60000:1min=>statsmeasuredinlast1minute 900000:15min=>statsmeasuredinlast15minutes 3600000:1hour=>statsmeasuredinlasthourminutes AllthetimewindowstatisticscanberetrievedfromaM a p < L o n g , T i m e W i n d o w S t a t i s t i c s > mapreturnedfrom E x e c u t i o n S t a t i s t i c s . g e t T i m e W i n d o w S t a t i s t i c s ( ) .Keyofthemapisthenumberofmillisecondsofinterval(so,forexamplekey60000pointsto statisticsforlastoneminute). Note,thats n a p s h o t ( ) methodwascalledintheexampleonlyonthetoplevelM o n i t o r i n g S t a t i s t i c s .Thisproducedasnapshotoftheentiretreeof statisticsandthereforewedonotneedtocalls n a p s h o t ( ) onT i m e W i n d o w S t a t i s t i c s again. StatisticsareinjectedusingtheProvider.Thisispreferredwayofinjectingstatistics.Thereasonissimple.Statisticsmightchangeovertimeandcontractof M o n i t o r i n g S t a t i s t i c s doesnotmakeanyassumptionsaboutmutabilityofmonitoringstatisticsinstances(toallowfutureoptimizationsandchangesin implementationstrategy).Inordertogetalwayslateststatistics,werecommendinjectingaProviderratherthanadirectreferenceanduseit'sg e t ( ) method toretrievethelateststatistics.Forexample,insingletonresourcestheuseofthetechniqueisveryimportantotherwisestatisticsmightcorrespondtothetime whensingletonwasfirstlycreatedandmightnotupdatesincethattime.

19.2.2.1.Listeningtostatisticschanges
Statisticsarenotcalculatedforeachrequestoreachchange.Statisticsarecalculatedonlyfromthecollecteddatainregularintervalsforperformance reasons(forexampleoncepersecond).Ifyouwanttobenotifiedaboutnewstatistics,registeranimplementationofMonitoringStatisticsListenerasoneof

yourcustomapplicationproviders.Yourlistenerwillbecalledeverytimethenewstatisticsarecalculatedandtheupdatedstatisticsdatawillbepassedtothe listenermethod.Thisisanotherwayofreceivingstatistics.SeethelinkedlistenerAPIdocumentationformoreinformation.

19.2.3.MonitoringStatisticsasMBeans
JerseyprovidesfeaturetoexposemonitoringstatisticsasJMXMXBeans.InordertoenablemonitoringstatisticsMXBeansexposure,the ServerProperties.MONITORING_STATISTICS_MBEANS_ENABLEDmustbesettot r u e .
j e r s e y . c o n f i g . s e r v e r . m o n i t o r i n g . s t a t i s t i c s . m b e a n s . e n a b l e d = t r u e

NotethatenablingexposureofmonitoringMXBeanscausesthatalsothecalculationofM o n i t o r i n g S t a t i s t i c s isautomaticallyenabledastheexposed MXBeanstatisticsareextractedfromM o n i t o r i n g S t a t i s t i c s . TheeasiestwayistobrowsetheMXBeansintheJConsole.OpentheJConsole($ J A V A _ H O M E / b i n / j c o n s o l e ).ThenconnecttotheprocesswhereJAXRS applicationisrunning(serveronwhichtheapplicationisrunning).SwitchtoaMBeantabandintheMBeantreeontheleftsidefindagroup o r g . g l a s s f i s h . j e r s e y .AlldeployedJerseyapplicationsarelocatedunderthisgroup.Ifyoudon'tseesuchthisgroup,thenMBeansarenotexposed (checktheconfigurationpropertyandlogsiftheynotcontainanyexceptionsorerrors).ThefollowingfigureisanexampleofanoutputfromtheJConsole:

Undertherooto r g . g l a s s f i s h . j e r s e y JerseyMBeangroupyoucanfindyourapplication.IftheservercontainsmoreJerseyapplication,allwillbepresent undertherootJerseythegroup.Inthescreenshot,thedeployedJAXRSapplicationisnamedm y A p p l i c a t i o n (thenamecanbedefinedvia ResourceConfigdirectlyorbysettingtheServerProperties.APPLICATION_NAMEproperty).EachapplicationcontainsG l o b a l ,R e s o u r c e andU r i s sub groups.TheG l o b a l groupcontainsallglobalstatisticslikeoverallrequestsstatisticsoftheentireapplication(A l l R e q u e s t T i m e s ),configurationoftheJAX RSapplication(C o n f i g u r a t i o n ),statisticsaboutExceptionMapper<EextendsThrowable>execution(E x c e p t i o n M a p p e r )andstatisticsaboutproduced responses(R e s p o n s e s ).
R e s o u r c e s andU r i s groupscontainsmonitoringstatisticsspecifictoindividualresources.StatisticsinR e s o u r c e s areboundtotheJAXRSresourceJava classesloadedbytheapplication.U r i s containsstatisticsofresourcesbasedonthematchedapplicationUris(oneURIentryrepresentsallmethodsboundto theparticulaURI,e.g./ r e s o u r c e / e x c e p t i o n ).AsJerseyprovidesprogrammaticresourcebuilders(describedinthechapter"ProgrammaticAPIforBuilding

Resources"),oneJavaresourceclasscanbeanendpointforresourcemethodsonmanydifferentURIs.AndalsooneURIcanbeservedbymethodfrom manydifferentJavaclasses.Thereforebothviewsarenottobecompared1:1.InsteadtheyprovidedifferentloggicalviewsonyourJAXRSapplication.This monitoringfeaturecanalsohelpwhendesigningtheJAXRSAPIsasitprovidesniceviewonavailablerootapplicationURIs. Bothlogicalviewsontheresourcesexposedbyapplicationsharefewcommonprinciples.Asingleresourceentryisalwaysasetofresourcemethodswhich areavailableunderthem e t h o d s subgroup.StatisticscanbefoundinMBeansM e t h o d T i m e s andR e q u e s t T i m e s .M e t h o d T i m e s containsstatisticsmeasured ononresourcemethods(durationofexecutionofacodeofthearesourcemethod),whereasR e q u e s t T i m e s containsstatisticsofanentirerequestexecution (notonlyatimeoftheexecutionoftheresourcemethodbuttheoveralltimeoftheexecutionofwholerequestbyJerseyruntime).Anotherusefulinformation isthatstatisticsdirectlyunderresource(notunderthem e t h o d s subgroup)containssummaryofstatisticsforallresourcemethodsgroupedintheresource

entry. Additionalusefuldetailsthataboutstatistics
G l o b a l > C o n f i g u r a t i o n > R e g i s t e r e d ( C l a a s e s / I n s t a n c e s ) :registeredresourceclassesandinstancesbytheuser(i.e.,notaddedby

ModelProcessorduringdeploymentforexample).
G l o b a l > E x c e p t i o n M a p p e r > E x c e p t i o n M a p p e r C o u n t :mapthatcontainsexceptionmapperclassesaskeysandnumberoftheirexecutionas

values.
G l o b a l > R e s p o n s e s ? R e s p o n s e C o d e s T o C o u n t M a p :mapthatcontainsresponsecodesaskeysandtheirtotaloccurrenceinresponsesasvalues.

ResourcegroupscontainalsoentriesforresourcesthatwereaddedbyJerseyatdeploymenttimeusingM o d e l P r o c e s s o r (forexampleallO P T I O N S methods,W A D L ).H E A D methodsarenotpresentintheMXBeansview(evenHEADmethodsareinresources). Executionstatisticsfordifferenttimewindowshavedifferentupdateintervals.Theshorterthetimewindow,theshortertheupdateinterval.Thiscauses thatimmediatelyaftertheapplicationstart,theshortertimewindows(suchas15seconds)maycontainhighervaluesthanlongerones(e.g.1hour timewindow).Thereasonisthat1hourintervalwillshowinformationthatisnotuptodateandthereforehassmallervalue.Thisinconsistencyisnotso muchsignificantwhenapplicationisrunninglongertime.Totalunlimitedtimewindowscontainsalwaysuptodatedata.Thisinconsistencywillgetfixed inafutureJerseyrelease. MXBeanscanbealsoaccessedusingJMX.Todoso,youwouldneedtousetheinterfacesofMXBeans.Theseinterfacesareevenusefulwhenworkingwith MXBeansonlytroughJ C o n s o l e astheycontainJavadocsforeachMXBeanandattribute.MonitoringMBeansaredefinedbyfollowinginterfaces: ApplicationMXBean:containsconfigurationstatistics ExceptionMapperMXBean:containsstatisticsofexceptionmappers ResourceMethodMXBean:containsstatisticsofresourcemethod ResourceMXBean:containsstatisticsofresource ResponseMXBean:containsstatisticsofresponses ThelistdoesnotcontainMXBeanfortheexecutionandtimewindowstatistics.ThereasonisthatthisbeanisdefinedasaDynamicMBean.Attributesofthis dynamicMBeancontainsstatisticsforalltimewindowsavailable. MXBeansdonotreferenceeachotherbutcanberetrievedbytheirObjectNameswhicharedesignedintheway,thatfinalMBeantreelooksnicelyorganized inJConsole.EachMXBeanisuniquelyidentifiedbyitsO b j e c t N a m e andpropertiesofO b j e c t N a m e arestructuredhierarchically,sothateachMXBeancanbe identifiedtowhichparentitbelongto(e.g.executionstatisticsdynamicMXBeanbelongstoresourcemethodMXBean,whichbelongstoresourceandwhich belongstoapplication).ChecktheO b j e c t N a m e sofexposedMXBeanstoinvestigatethestructure(forexamplethroughJConsole). Toreiterate,exposingJerseyMXBeansandthecalculatingmonitoringstatisticsmayhaveanperformanceimpactonyourapplicationandthereforeshouldbe enabledonlywhenneeded.Also,pleasenote,thatitJerseymonitoringisexposingquitealotofinformationaboutthemonitoredapplicationwhichmightbe viewedasproblematicinsomecases(e.g.inproductionserverdeployments).

Chapter20.SpringDI
TableofContents 20.1.Dependencies 20.2.RegistrationandConfiguration 20.3.Example JerseyprovidesanextensiontosupportSpringDI.ThisenablesJerseytouseSpringbeansasJAXRScomponents(e.g.resourcesandproviders)andalso allowsSpringtoinjectintoJerseymanagedcomponents. TheSpringextensionmoduleconfigurationisbasedonannotations.SpringbeansareinjectedandJAXRSclassesaremadeSpringmanagedusing annotations.InjectedSpringbeanscanhavefurtherdependenciesinjectedusingSpringXMLconfiguration.Springsingletonandrequestscopesare supported. Limitations: Springbeanscan'tbeinjecteddirectlyintoJAXRSclassesbyusingSpringXMLconfiguration

20.1.Dependencies
IfyouwanttouseJerseySpringDIsupportyouwillneedtoaddthejerseyspring3moduleintothelistofyourdependencies:
1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . e x t < / g r o u p I d > < a r t i f a c t I d > j e r s e y s p r i n g 3 < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

TheabovemoduledoesnotaddanytransitivedependencytoSpringmodules,soyouwillneedtoaddSpring3dependenciesexplicitlyintoyourdependency list.

20.2.RegistrationandConfiguration
TousecapabilitiesofJerseySpring3DIsupportinyourJAXRS/Jerseyapplicationyouneedtohavetheabovementionedmoduleonyourclasspath.

20.3.Example
ToseeanexampleofSpringDIsupportinJerseyrefertotheSpringDIexample.

Chapter21.JerseyTestFramework
TableofContents 21.1.Basics 21.2.SupportedContainers 21.3.Advancedfeatures 21.3.1.J e r s e y T e s t Features 21.3.2.Externalcontainer 21.3.3.TestClientconfiguration 21.3.4.Accessingtheloggedtestrecordsprogrammatically JerseyTestFrameworkoriginatedasaninternaltoolusedforverifyingthecorrectimplementationofserversidecomponents.TestingRESTfulapplications becameamorepressingissuewith"modern"approachesliketestdrivendevelopmentandusersstartedtolookforatoolthatcouldhelpwithdesigningand

runningthetestsasfastaspossiblebutwithmanyoptionsrelatedtotestexecutionenvironment. CurrentimplementationofJerseyTestFrameworksupportsthefollowingsetoffeatures: preconfiguredclienttoaccessdeployedapplication supportformultiplecontainersgrizzly,inmemory,jdk,simple abletorunagainstanyexternalcontainer automatedconfigurabletrafficlogging JerseyTestFrameworkisbasedonJUnitandworksalmostoutofthebox.ItiseasytointegrateitwithinyourMavenbasedproject.Whileitisusableonall environmentswhereyoucanrunJUnit,wesupportprimarilytheMavenbasedsetups.

21.1.Basics
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 p u b l i c c l a s s S i m p l e T e s t e x t e n d s J e r s e y T e s t { @ P a t h ( " h e l l o " ) p u b l i c s t a t i c c l a s s H e l l o R e s o u r c e { @ G E T p u b l i c S t r i n g g e t H e l l o ( ) { r e t u r n " H e l l o W o r l d ! " } } @ O v e r r i d e p r o t e c t e d A p p l i c a t i o n c o n f i g u r e ( ) { r e t u r n n e w R e s o u r c e C o n f i g ( H e l l o R e s o u r c e . c l a s s ) } @ T e s t p u b l i c v o i d t e s t ( ) { f i n a l S t r i n g h e l l o = t a r g e t ( " h e l l o " ) . r e q u e s t ( ) . g e t ( S t r i n g . c l a s s ) a s s e r t E q u a l s ( " H e l l o W o r l d ! " , h e l l o ) } }

IfyouwanttodevelopatestusingJerseyTestFramework,youneedtosubclassJerseyTestandconfigurethesetofresourcesand/orprovidersthatwillbe deployedaspartofthetestapplication.ThisshortcodesnippetshowsbasicresourceclassH e l l o R e s o u r c e usedintestsdefinedaspartoftheS i m p l e T e s t class.Theoverriddenc o n f i g u r e methodreturnsaResourceConfigofthetestapplication,thatcontainsonlytheH e l l o R e s o u r c e resourceclass. R e s o u r c e C o n f i g isasubclassofJAXRSApplication.ItisaJerseyconvenienceclassforconfiguringJAXRSapplications.R e s o u r c e C o n f i g also implementsJAXRSConfigurableinterfacetomaketheapplicationconfigurationmoreflexible.

21.2.SupportedContainers
JerseyTestsupportsdeployingapplicationsonvariouscontainers,all(excepttheexternalcontainerwrapper)needtohavesome"glue"codetobesupported. CurrentlyJerseyTestFrameworkprovidessupportforGrizzly,InMemory,JDK(c o m . s u n . n e t . h t t p s e r v e r . H t t p S e r v e r )andSimpleHTTPcontainer (o r g . s i m p l e f r a m e w o r k . h t t p ). Atestcontainerisselectedbasedonvariousinputs.JerseyTest#getTestContainerFactory()isalwaysexecuted,soifyouoverrideitandprovideyourown versionofTestContainerFactory,nothingelsewillbeconsidered.SettingasystemvariableTestProperties#CONTAINER_FACTORYhassimilareffect.This wayyoumaydeferthedecisiononwhichcontainersyouwanttorunyourtestsfromthecompiletimetothetestexecutiontime.Defaultimplementationof T e s t C o n t a i n e r F a c t o r y looksforcontainerfactoriesonclasspath.IfmorethanoneinstanceisfoundandthereisaGrizzlytestcontainerfactoryamong them,itwillbeusedifnot,awarningwillbeloggedandthefirstfoundfactorywillbeinstantiated. FollowingisabriefdescriptionofallcontainerssupportedinJerseyTestFramework. Grizzlycontainercanrunasalightweight,plainHTTPcontainer.AlmostallJerseytestsareusingGrizzlybydefault.
1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . t e s t f r a m e w o r k . p r o v i d e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y t e s t f r a m e w o r k p r o v i d e r g r i z z l y 2 < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

InMemorycontainerisnotarealcontainer.ItstartsJerseyapplicationanddirectlycallsinternalAPIstohandlerequestcreatedbyclientprovidedby testframework.Thereisnonetworkcommunicationinvolved.Thiscontainersdoesnotsupportservletandothercontainerdependentfeatures,butitis aperfectchoiceforsimpleunittests.


1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . t e s t f r a m e w o r k . p r o v i d e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y t e s t f r a m e w o r k p r o v i d e r i n m e m o r y < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

H t t p S e r v e r fromOracleJDKisanothersupportedtestcontainer. 1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . t e s t f r a m e w o r k . p r o v i d e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y t e s t f r a m e w o r k p r o v i d e r j d k h t t p < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Simplecontainer(o r g . s i m p l e f r a m e w o r k . h t t p )isanotherlightweightHTTPcontainerthatintegrateswithJerseyandissupportedbyJerseyTest Framework.


1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . t e s t f r a m e w o r k . p r o v i d e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y t e s t f r a m e w o r k p r o v i d e r s i m p l e < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

21.3.Advancedfeatures
21.3.1.J e r s e y T e s t Features
J e r s e y T e s t provideenable(...),forceEnable(...)anddisable(...)methods,thatgiveyoucontroloverconfiguringvaluesofthepropertiesdefinedand describedintheT e s t P r o p e r t i e s class.Atypicalcodethatoverridesthedefaultpropertyvaluesislistedbellow: 1 2 3 p u b l i c c l a s s S i m p l e T e s t e x t e n d s J e r s e y T e s t { / / . . .

4 5 6 7 8 9 1 0 1 1 1 2

@ O v e r r i d e p r o t e c t e d A p p l i c a t i o n c o n f i g u r e ( ) { e n a b l e ( T e s t P r o p e r t i e s . L O G _ T R A F F I C ) e n a b l e ( T e s t P r o p e r t i e s . D U M P _ E N T I T Y ) / / . . . } }

Thecodeintheexampleaboveenablestesttrafficlogging(inboundandoutboundheaders)aswellasdumpingtheHTTPmessageentityaspartofthetraffic logging.

21.3.2.Externalcontainer
Complicatedtestscenariosmayrequirefullystartedcontainerswithcomplexsetupconfiguration,thatisnoteasilydoablewithcurrentJerseycontainer support.Toaddresstheseusecases,JerseyTestFrameworkprovidersgeneralfallbackmechanismanExternalTestContainerFactory.Supportofthis externalcontainer"wrapper"isprovidedasthefollowingmodule:
1 2 3 4 5 < d e p e n d e n c y > < g r o u p I d > o r g . g l a s s f i s h . j e r s e y . t e s t f r a m e w o r k . p r o v i d e r s < / g r o u p I d > < a r t i f a c t I d > j e r s e y t e s t f r a m e w o r k p r o v i d e r e x t e r n a l < / a r t i f a c t I d > < v e r s i o n > 2 . 3 . 1 < / v e r s i o n > < / d e p e n d e n c y >

Asindicated,the"container"exposedbythismoduleisjustawrapperorstub,thatredirectsallrequesttoaconfiguredhostandport.Writingtestsforthis containerissameasforanyotherbutyouhavetoprovidetheinformationabouthostandportduringthetestexecution:
m v n t e s t D j e r s e y . t e s t . h o s t = m y h o s t . o r g D j e r s e y . c o n f i g . t e s t . c o n t a i n e r . p o r t = 8 0 8 0

21.3.3.TestClientconfiguration
Testsmightrequiresomeadvancedclientconfiguration.ThisispossiblebyoverridingconfigureClient(ClientConfigclientConfig)method.Typicalusecasefor thisisregisteringmoreproviders,suchasMessageBodyReader<T>sorMessageBodyWriter<T>s,orenablingadditionalfeatures.

21.3.4.Accessingtheloggedtestrecordsprogrammatically
Sometimesyoumightneedtocheckaloggedmessageaspartofyourtestassertions.ForthispurposeJerseyTestFrameworkprovidesconvenientaccess totheloggedrecordsviaJerseyTest#getLastLoggedRecord()andJerseyTest#getLoggedRecords()methods.Notethatthisfeatureisnotenabledbydefault, seeTestProperties#RECORD_LOG_LEVELformoreinformation.

Chapter22.BuildingandTestingJersey
TableofContents 22.1.CheckingOuttheSource 22.2.BuildingtheSource 22.3.Testing 22.4.UsingNetBeans

22.1.CheckingOuttheSource
JerseysourcecodeisavailableonGitHub.Youcanbrowsethesourcesathttps://github.com/jersey/jersey. IncaseyouarenotfamiliarwithGit,werecommendreadingsomeofthemany"GettingStartedwithGit"articlesyoucanfindontheweb.Forexamplethis DZoneRefCard. ToclonetheJerseyrepositoryyoucanexecutethefollowingcommandonthecommandline(providedyouhaveacommandlineGitclientinstalledonyour machine):
g i t c l o n e g i t : / / g i t h u b . c o m / j e r s e y / j e r s e y . g i t

ThiscreatesreadonlycopyofJerseyworkspace.Ifyouwanttocontribute,pleaseuse"pullrequest":https://help.github.com/articles/creatingapullrequest. MilestonesandreleasesofJerseyaretagged.YoucanlistthetagsbyexecutingthestandardGitcommandintherepositorydirectory:
g i t t a g l

orbyvisitinghttps://github.com/jersey/jersey/tags.

22.2.BuildingtheSource
JerseysourcecoderequiresJavaSE6orgreater.ThebuildisbasedonMaven.Maven3orgreaterishighlyrecommended.Alsoitisrecommendedyouuse thefollowingMavenoptionswhenbuildingtheworkspace(canbesetinM A V E N _ O P T S environmentvariable):
X m x 1 0 4 8 m X X : P e r m S i z e = 6 4 M X X : M a x P e r m S i z e = 1 2 8 M

ItisrecommendedtobuildallofJerseyafteryouclonedthesourcecoderepository.Todothatexecutethefollowingcommandsinthedirectorywherejersey sourcerepositorywascloned(typicallythedirectorynamed"jersey"):
m v n D m a v e n . t e s t . s k i p = t r u e c l e a n i n s t a l l

ThiscommandwillbuildJersey,butskipthetestexecution.Ifyoudon'twanttoskipthetests,executethefollowinginstead:
m v n c l e a n i n s t a l l

BuildingthewholeJerseyprojectincludingtestscouldtakesignificantamountoftime.

22.3.Testing
Jerseycontainsmanytests.UnittestsareintheindividualJerseymodules,integrationandendtoendtestsareinj e r s e y / t e s t s / e 2 e directory.Youcanrun testsrelatedtoaparticularareausingthefollowingcommand:
m v n D t e s t = < p a t t e r n > t e s t

wherep a t t e r n maybeacommaseparatedsetofnamesmatchingtestsclassesorindividualmethods(likeL i n k T e s t # t e s t D e l i m i t e r s ).

22.4.UsingNetBeans
NetBeansIDEhasexcellentmavensupport.TheJerseymavenmodulescanbeloaded,builtandtestedinNetBeanswithoutanyadditionalNetBeansspecific

projectfiles.

Chapter23.MigrationGuide
TableofContents 23.1.MigratingfromJersey2.0,2.1or2.2to2.3 23.2.MigratingfromJersey1.xto2.0 23.2.1.ServerAPI 23.2.2.MigratingJerseyClientAPI

23.1.MigratingfromJersey2.0,2.1or2.2to2.3
AllexistingSSEInboundEventg e t D a t a ( . . . ) methodshavebeenmadedeprecatedandnewr e a d D a t a ( . . . ) methodshavebeenintroducedinstead forconsistencywithotherpartsofclientsideJAXRSAPI.Thedeprecatedg e t D a t a ( . . . ) methodswillberemovedinJersey2.4.AnewSSE InboundEventb y t e [ ] g e t R a w D a t a ( ) methodhasbeenintroducedtoprovideaccesstotherawSSEeventdatacontent. GenericBroadcastermethodsforadding/removingBroadcasterListenerregistrationshavebeenrenamedfrom a d d B r o a d c a s t e r L i s t e n e r / r e m o v e B r o a d c a s t e r L i s t e n e r tosimplya d d / r e m o v e . GenericBroadcaster(andtransitively,SseBroadcaster)a d d / r e m o v e methodsthatareresponsibleforadding/removingBroadcasterListenerand ChunkedOutput(orEventOutput)registrationsnolongertrytoavoidduplicateregistrationsbycomparinghashcodeoftheadded/removedinstance withthehashcodesofalreadyregisteredinstances.Thisbehaviorhasbeenidentifiedasapotentialsourceofhardtodiscoverbugsandwasremoved assuch.Theissuewiththeformerbehaviorwasthathashcodesasintegervaluesprovideonlyaverylimitedvaluespacethatcouldleadtofalse positiveduplicateregistrationrejections,especiallywithlargernumberofsimultaneouslyconnectedSSEclients(representedbyC h u n k e d O u t p u t or E v e n t O u t p u t broadcasterregistrations).Consequently,userswhorelyontheoldregistrationbehaviorintheirapplicationcodeneedtoadaptthecode totherevisedbehaviorofB r o a d c a s t e r a d d / r e m o v e methods.

23.2.MigratingfromJersey1.xto2.0
ThischapterisamigrationguideforpeopleswitchingfromJersey1.x.SincemanyoftheJersey1.xfeaturesbecamepartofJAXRS2.0standardwhich causedchangesinthepackagenames,wedecideditisagoodtimetodoamoresignificantincompatiblerefactoring,whichwillallowustointroducesome moreinterestingnewfeaturesinthefuture.Astheresult,therearemanyincompatibilitiesbetweenJersey1.xandJersey2.0.Thischaptersummarizeshow tomigratetheconceptsfoundinJersey1.xtoJersey/JAXRS2.0concepts.

23.2.1.ServerAPI
Jersey1.xcontainsnumberofproprietaryserverAPIs.ThissectioncoversmigrationofapplicationcoderelyingonthoseAPIs.

23.2.1.1.Injectingcustomobjects
Jersey1.xhaveitsowninternaldependencyinjectionframeworkwhichhandlesinjectingvariousparametersintofieldormethods.Italsoprovidesawayhow toregistercustominjectionproviderinSingletonorPerRequestscopes.Jersey2.xusesHK2asdependencyinjectionframeworkandusersarealsoableto registercustomclassesorinstancestobeinjectedinvariousscopes. MaindifferenceinJersey2.xisthatyoudon'tneedtocreatespecialclassesorprovidersforthistaskeverythingshouldbeachievableusingHK2API. CustominjectablescanberegisteredatResourceConfiglevelbyaddingnewHK2Moduleorbydynamicallyaddingbindingalmostanywhereusinginjected HK2Servicesinstance. Jersey1.xSingleton:
R e s o u r c e C o n f i g r e s o u r c e C o n f i g = n e w D e f a u l t R e s o u r c e C o n f i g ( ) r e s o u r c e C o n f i g . g e t S i n g l e t o n s ( ) . a d d ( n e w S i n g l e t o n T y p e I n j e c t a b l e P r o v i d e r < C o n t e x t , S i n g l e t o n T y p e > ( S i n g l e t o n T y p e . c l a s s , n e w S i n g l e t o n T y p e ( ) ) { } )

Jersey1.xPerRequest:
R e s o u r c e C o n f i g r e s o u r c e C o n f i g = n e w D e f a u l t R e s o u r c e C o n f i g ( ) r e s o u r c e C o n f i g . g e t S i n g l e t o n s ( ) . a d d ( n e w P e r R e q u e s t T y p e I n j e c t a b l e P r o v i d e r < C o n t e x t , P e r R e q u e s t T y p e > ( ) { @ O v e r r i d e p u b l i c I n j e c t a b l e < P e r R e q u e s t T y p e > g e t I n j e c t a b l e ( C o m p o n e n t C o n t e x t i c , C o n t e x t c o n t e x t ) { / / . . . } } )

Jersey2.0HK2Module:
p u b l i c s t a t i c c l a s s M y B i n d e r e x t e n d s A b s t r a c t B i n d e r { @ O v e r r i d e p r o t e c t e d v o i d c o n f i g u r e ( ) { / / r e q u e s t s c o p e b i n d i n g b i n d ( M y I n j e c t a b l e P e r R e q u e s t . c l a s s ) . t o ( M y I n j e c t a b l e P e r R e q u e s t . c l a s s ) . i n ( R e q u e s t S c o p e . c l a s s ) / / s i n g l e t o n b i n d i n g b i n d ( M y I n j e c t a b l e S i n g l e t o n . c l a s s ) . i n ( S i n g l e t o n . c l a s s ) / / s i n g l e t o n i n s t a n c e b i n d i n g b i n d ( n e w M y I n j e c t a b l e S i n g l e t o n ( ) ) . t o ( M y I n j e c t a b l e S i n g l e t o n . c l a s s ) } } / / r e g i s t e r m o d u l e t o R e s o u r c e C o n f i g ( c a n b e d o n e a l s o i n c o n s t r u c t o r ) R e s o u r c e C o n f i g r c = n e w R e s o u r c e C o n f i g ( ) r c . a d d C l a s s e s ( / * . . . * / ) r c . a d d B i n d e r s ( n e w M y B i n d e r ( ) )

Jersey2.0dynamicbinding:
p u b l i c s t a t i c c l a s s M y A p p l i c a t i o n e x t e n d s A p p l i c a t i o n { @ I n j e c t p u b l i c M y A p p l i c a t i o n ( S e r v i c e L o c a t o r s e r v i c e L o c a t o r ) { S y s t e m . o u t . p r i n t l n ( " R e g i s t e r i n g i n j e c t a b l e s . . . " ) D y n a m i c C o n f i g u r a t i o n d c = I n j e c t i o n s . g e t C o n f i g u r a t i o n ( s e r v i c e L o c a t o r ) / / r e q u e s t s c o p e b i n d i n g I n j e c t i o n s . a d d B i n d i n g ( I n j e c t i o n s . n e w B i n d e r ( M y I n j e c t a b l e P e r R e q u e s t . c l a s s ) . t o ( M y I n j e c t a b l e P e r R e q u e s t . c l a s s ) . i n ( R e q u e s t S c o p e d . c l a s s ) , d c )

/ / s i n g l e t o n b i n d i n g I n j e c t i o n s . a d d B i n d i n g ( I n j e c t i o n s . n e w B i n d e r ( M y I n j e c t a b l e S i n g l e t o n . c l a s s ) . t o ( M y I n j e c t a b l e S i n g l e t o n . c l a s s ) . i n ( S i n g l e t o n . c l a s s ) , d c ) / / s i n g l e t o n i n s t a n c e b i n d i n g I n j e c t i o n s . a d d B i n d i n g ( I n j e c t i o n s . n e w B i n d e r ( n e w M y I n j e c t a b l e S i n g l e t o n ( ) ) . t o ( M y I n j e c t a b l e S i n g l e t o n . c l a s s ) , d c ) / / r e q u e s t s c o p e b i n d i n g w i t h s p e c i f i e d c u s t o m a n n o t a t i o n I n j e c t i o n s . a d d B i n d i n g ( I n j e c t i o n s . n e w B i n d e r ( M y I n j e c t a b l e P e r R e q u e s t . c l a s s ) . t o ( M y I n j e c t a b l e P e r R e q u e s t . c l a s s ) . q u a l i f i e d B y ( n e w M y A n n o t a t i o n I m p l ( ) ) . i n ( R e q u e s t S c o p e d . c l a s s ) , d c ) / / c o m m i t s c h a n g e s d c . c o m m i t ( ) } @ O v e r r i d e p u b l i c S e t < C l a s s < ? > > g e t C l a s s e s ( ) { r e t u r n . . . } }

23.2.1.2.ResourceConfigReload
InJersey1,thereloadfunctionalityisbasedontwointerfaces: 1. com.sun.jersey.spi.container.ContainerListener 2. com.sun.jersey.spi.container.ContainerNotifier Containers,whichsupportthereloadfunctionalityimplementtheC o n t a i n e r L i s t e n e r interface,sothatonceyougetaccesstotheactualcontainerinstance, youcouldcallit'so n R e l o a d methodandgetthecontainerreloadtheconfig.Thesecondinterfacehelpsyoutoobtaintheactualcontainerinstance reference.Anexampleonhowthingsarewiredtogetherfollows. Example23.1.Jersey1reloaderimplementation
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 p u b l i c c l a s s R e l o a d e r i m p l e m e n t s C o n t a i n e r N o t i f i e r { L i s t < C o n t a i n e r L i s t e n e r > l s p u b l i c R e l o a d e r ( ) { l s = n e w A r r a y L i s t < C o n t a i n e r L i s t e n e r > ( ) } p u b l i c v o i d a d d L i s t e n e r ( C o n t a i n e r L i s t e n e r l ) { l s . a d d ( l ) } p u b l i c v o i d r e l o a d ( ) { f o r ( C o n t a i n e r L i s t e n e r l : l s ) { l . o n R e l o a d ( ) } } }

Example23.2.Jersey1reloaderregistration
1 2 R e l o a d e r r e l o a d e r = n e w R e l o a d e r ( ) r e s o u r c e C o n f i g . g e t P r o p e r t i e s ( ) . p u t ( R e s o u r c e C o n f i g . P R O P E R T Y _ C O N T A I N E R _ N O T I F I E R , r e l o a d e r )

InJersey2,twointerfacesareinvolvedagain,butthesehavebeenredesigned. 1. org.glassfish.jersey.server.spi.Container 2. org.glassfish.jersey.server.spi.ContainerLifecycleListener TheC o n t a i n e r interfaceintroducestwor e l o a d methods,whichyoucancalltogettheapplicationreloaded.Oneofthesemethodsallowstopassinanew R e s o u r c e C o n f i g instance.YoucanregisteryourimplementationofC o n t a i n e r L i f e c y c l e L i s t e n e r thesamewayasanyotherprovider(i.e.eitherby annotatingitby@ProviderannotationoraddingittotheJerseyResourceConfigdirectlyeitherusingtheclass(usingR e s o u r c e C o n f i g . a d d C l a s s e s ( ) )or registeringaparticularinstanceusingR e s o u r c e C o n f i g . a d d S i n g l e t o n s ( ) method. AnexampleonhowthingsworkinJersey2follows. Example23.3.Jersey2reloaderimplementation
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 p u b l i c c l a s s R e l o a d e r i m p l e m e n t s C o n t a i n e r L i f e c y c l e L i s t e n e r { C o n t a i n e r c o n t a i n e r p u b l i c v o i d r e l o a d ( R e s o u r c e C o n f i g n e w C o n f i g ) { c o n t a i n e r . r e l o a d ( n e w C o n f i g ) } p u b l i c v o i d r e l o a d ( ) { c o n t a i n e r . r e l o a d ( ) } @ O v e r r i d e p u b l i c v o i d o n S t a r t u p ( C o n t a i n e r c o n t a i n e r ) { t h i s . c o n t a i n e r = c o n t a i n e r } @ O v e r r i d e p u b l i c v o i d o n R e l o a d ( C o n t a i n e r c o n t a i n e r ) { / / i g n o r e o r d o w h a t e v e r y o u w a n t a f t e r r e l o a d h a s b e e n d o n e } @ O v e r r i d e p u b l i c v o i d o n S h u t d o w n ( C o n t a i n e r c o n t a i n e r ) { / / i g n o r e o r d o s o m e t h i n g a f t e r t h e c o n t a i n e r h a s b e e n s h u t d o w n }

2 7

Example23.4.Jersey2reloaderregistration
1 2 R e l o a d e r r e l o a d e r = n e w R e l o a d e r ( ) r e s o u r c e C o n f i g . a d d S i n g l e t o n s ( r e l o a d e r )

23.2.1.3.MessageBodyReadersandMessageBodyWritersordering
JAXRS2.0definesneworderofMessageBodyWorkerswholesetissortedbydeclarationdistance,mediatypeandsource(customprovidershavinghigher prioritythandefaultonesprovidedbyJersey).JAXRS1.xorderingcanstillbeforcedbysettingparameter M e s s a g e P r o p e r t i e s . L E G A C Y _ W O R K E R S _ O R D E R I N G (" j e r s e y . c o n f i g . w o r k e r s . l e g a c y O r d e r i n g " )tot r u e inR e s o u r c e C o n f i g orC l i e n t C o n f i g properties.

23.2.2.MigratingJerseyClientAPI
JAXRS2.0providesfunctionalitythatisequivalenttotheJersey1.xproprietaryclientAPI.HereisaroughmappingbetweentheJersey1.xandJAXRS2.0 ClientAPIclasses: Table23.1.MappingofJersey1.xtoJAXRS2.0clientclasses
Jersey1.xClass com.sun.jersey.api.client.Client com.sun.jersey.api.client.WebResource JAXRS2.0 Notes Class ClientBuilder Forthestaticfactorymethodsandconstructors. Client WebTarget Fortheinstancemethods. YoucanaccessasyncversionsoftheasyncmethodsbycallingW e b T a r g e t . r e q u e s t ( ) . a s y n c ( )

com.sun.jersey.api.client.AsyncWebResource WebTarget

Thefollowingsubsectionsshowcodeexamples.

23.2.2.1.Makingasimpleclientrequest
Jersey1.xway:
C l i e n t c l i e n t = C l i e n t . c r e a t e ( ) W e b R e s o u r c e w e b R e s o u r c e = c l i e n t . r e s o u r c e ( r e s t U R L ) . p a t h ( " m y r e s o u r c e / { p a r a m } " ) S t r i n g r e s u l t = w e b R e s o u r c e . p a t h P a r a m ( " p a r a m " , " v a l u e " ) . g e t ( S t r i n g . c l a s s )

JAXRS2.0way:
C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( ) W e b T a r g e t t a r g e t = c l i e n t . t a r g e t ( r e s t U R L ) . p a t h ( " m y r e s o u r c e / { p a r a m } " ) S t r i n g r e s u l t = t a r g e t . p a t h P a r a m ( " p a r a m " , " v a l u e " ) . g e t ( S t r i n g . c l a s s )

23.2.2.2.Registeringfilters
Jersey1.xway:
C l i e n t c l i e n t = C l i e n t . c r e a t e ( ) W e b R e s o u r c e w e b R e s o u r c e = c l i e n t . r e s o u r c e ( r e s t U R L ) w e b R e s o u r c e . a d d F i l t e r ( n e w H T T P B a s i c A u t h F i l t e r ( u s e r n a m e , p a s s w o r d ) )

JAXRS2.0way:
C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( ) W e b T a r g e t t a r g e t = c l i e n t . t a r g e t ( r e s t U R L ) t a r g e t . r e g i s t e r ( n e w H t t p B a s i c A u t h F i l t e r ( u s e r n a m e , p a s s w o r d ) )

23.2.2.3.Setting"Accept"header
Jersey1.xway:
C l i e n t c l i e n t = C l i e n t . c r e a t e ( ) W e b R e s o u r c e w e b R e s o u r c e = c l i e n t . r e s o u r c e ( r e s t U R L ) . a c c e p t ( " t e x t / p l a i n " ) C l i e n t R e s p o n s e r e s p o n s e = w e b R e s o u r c e . g e t ( C l i e n t R e s p o n s e . c l a s s )

JAXRS2.0way:
C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( ) W e b T a r g e t t a r g e t = c l i e n t . t a r g e t ( r e s t U R L ) R e s p o n s e r e s p o n s e = t a r g e t . r e q u e s t ( " t e x t / p l a i n " ) . g e t ( )

23.2.2.4.Attachingentitytorequest
Jersey1.xway:
C l i e n t c l i e n t = C l i e n t . c r e a t e ( ) W e b R e s o u r c e w e b R e s o u r c e = c l i e n t . r e s o u r c e ( r e s t U R L ) C l i e n t R e s p o n s e r e s p o n s e = w e b R e s o u r c e . p o s t ( C l i e n t R e s p o n s e . c l a s s , " p a y l o a d " )

JAXRS2.0way:
C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w C l i e n t ( ) W e b T a r g e t t a r g e t = c l i e n t . t a r g e t ( r e s t U R L ) R e s p o n s e r e s p o n s e = t a r g e t . r e q u e s t ( ) . p o s t ( E n t i t y . t e x t ( " p a y l o a d " ) )

23.2.2.5.SettingSSLContextand/orHostnameVerifier
Jersey1.xway:
H T T P S P r o p e r t i e s p r o p = n e w H T T P S P r o p e r t i e s ( h o s t n a m e V e r i f i e r , s s l C o n t e x t ) D e f a u l t C l i e n t C o n f i g d c c = n e w D e f a u l t C l i e n t C o n f i g ( ) d c c . g e t P r o p e r t i e s ( ) . p u t ( H T T P S P r o p e r t i e s . P R O P E R T Y _ H T T P S _ P R O P E R T I E S , p r o p )

C l i e n t c l i e n t = C l i e n t . c r e a t e ( d c c )

Jersey2.0way:
C l i e n t c l i e n t = C l i e n t B u i l d e r . n e w B u i l d e r ( ) . s s l C o n t e x t ( s s l C o n t e x t ) . h o s t n a m e V e r i f i e r ( h o s t n a m e V e r i f i e r ) . b u i l d ( )

AppendixA.ConfigurationProperties
TableofContents A.1.Common(client/server)configurationproperties A.2.Serverconfigurationproperties A.3.Clientconfigurationproperties

A.1.Common(client/server)configurationproperties
ListofcommonconfigurationpropertiesthatcanbefoundinCommonPropertiesclass.Allofthesepropertiescanbeoverriddenbytheirserver/client counterparts. TableA.1.Listofcommonconfigurationproperties
Constant CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE Value j e r s e y . c o n f i g . d i s a b l e A u t o D i s c o v e r y Description Disablesfeatureautodiscoverygloballyon client/server.Defaultvalueisf a l s e . DisablesconfigurationofJsonProcessing (JSR353)feature.Defaultvalueisf a l s e . DisablesMETAINF/serviceslookupglobally onclient/server.Defaultvalueisf a l s e . DisablesconfigurationofMOXyJson feature.Defaultvalueisf a l s e . Anintegervaluethatdefinesthebuffersize usedtobuffertheoutboundmessageentity inordertodetermineitssizeandsetthe valueofHTTPC o n t e n t L e n g t h header. Defaultvalueis8 1 9 2 .

e r s e y . c o n f i g . d i s a b l e J s o n P r o c e s s i n g CommonProperties.JSON_PROCESSING_FEATURE_DISABLE j CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE CommonProperties.MOXY_JSON_FEATURE_DISABLE j e r s e y . c o n f i g . d i s a b l e M e t a i n f S e r v i c e s L o o k u p j e r s e y . c o n f i g . d i s a b l e M o x y J s o n

e r s e y . c o n f i g . c o n t e n t L e n g t h . b u f f e r CommonProperties.OUTBOUND_CONTENT_LENGTH_BUFFER j

A.2.Serverconfigurationproperties
ListofserverconfigurationpropertiesthatcanbefoundinServerPropertiesclass. TableA.2.Listofserverconfigurationproperties
Constant Value Description

ServerProperties.APPLICATION_NAME

j e r s e y . c o n f i g . s e r v e r . a p p l i c a t i o n . n a m e

Definestheapplicationname.Thenameisanarbitr userdefinednamewhichisusedtodistinguishbetw Jerseyapplicationsinthecasethatmoreapplicatio deployedonthesameruntime(container).Thenam beusedforexampleforpurposesofmonitoringbyJ whennameidentifiestowhichapplicationdeployed MBeansbelongto.Thenameshouldbeuniqueinth runtime.Thepropertydoesnothaveadefaultvalue DisablesBeanValidationsupport.Defaultvalueis f a l s e .

ServerProperties.BV_FEATURE_DISABLE

j e r s e y . c o n f i g . b e a n V a l i d a t i o n . d i s a b l e . s e r v e r

j e r s e y . c o n f i g . b e a n V a l i d a t i o n ServerProperties d i s a b l e . v a l i d a t e O n E x e c u t a b l e C h e c k . s e r v e r .BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK . ServerProperties.BV_SEND_ERROR_IN_RESPONSE ServerProperties.FEATURE_AUTO_DISCOVERY_DISABLE j e r s e y . c o n f i g . b e a n V a l i d a t i o n . e n a b l e O u t p u t V a l i d a t i o n E r r o r E n t i t y . s e r v e r j e r s e y . c o n f i g . d i s a b l e A u t o D i s c o v e r y . s e r v e r

Disables@ V a l i d a t e O n E x e c u t i o n check.Defaul isf a l s e .

Enablessendingvalidationerrorinformationtothec Defaultvalueisf a l s e .

Disablesfeatureautodiscoveryonserver.Defaultv isf a l s e .

ServerProperties.HTTP_METHOD_OVERRIDE

j e r s e y . c o n f i g . s e r v e r . h t t p M e t h o d O v e r r i d e

DefinesconfigurationofHTTPmethodoverriding.T propertyisusedbyHttpMethodOverrideFiltertodet whereitshouldlookformethodoverrideinformation requestheaderorqueryparameters).

ServerProperties.JSON_PROCESSING_FEATURE_DISABLE ServerProperties.LANGUAGE_MAPPINGS ServerProperties.MEDIA_TYPE_MAPPINGS ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE ServerProperties.MOXY_JSON_FEATURE_DISABLE

j e r s e y . c o n f i g . d i s a b l e J s o n P r o c e s s i n g . s e r v e r j e r s e y . c o n f i g . s e r v e r . l a n g u a g e M a p p i n g s j e r s e y . c o n f i g . s e r v e r . m e d i a T y p e M a p p i n g s j e r s e y . c o n f i g . d i s a b l e M e t a i n f S e r v i c e s L o o k u p . s e r v e r j e r s e y . c o n f i g . d i s a b l e M o x y J s o n . s e r v e r

DisablesconfigurationofJsonProcessing(JSR353 feature.Defaultvalueisf a l s e .

DefinesmappingofURIextensionstolanguages.T propertyisusedbyUriConnegFilter.

DefinesmappingofURIextensionstomediatypes. propertyisusedbyUriConnegFilter. DisablesMETAINF/serviceslookuponserver.Def valueisf a l s e .

DisablesconfigurationofMOXyJsonfeature.Defau valueisf a l s e .

ServerProperties.MONITORING_STATISTICS_ENABLED

j e r s e y . c o n f i g . s e r v e r . m o n i t o r i n g . s t a t i s t i c s . e n a b l e d

Ift r u e ,thecalculationofmonitoringstatisticswill enabled.Thiswillenablethepossibilityofinjecting MonitoringStatisticsintoresourceandprovidersand theregisteredlistenersimplementing MonitoringStatisticsListenerwillbecalledwhenstat areavailableforprocessing.Notethatenablingstat mayhaveanegativeperformanceimpactandthere shouldbeenabledonlywhenneeded.Defaultvalue f a l s e .

ServerProperties.MONITORING_STATISTICS_MBEANS_ENABLED

j e r s e y . c o n f i g . s e r v e r . m o n i t o r i n g . s t a t i s t i c s . m b e a n s . e n a b l e d

Ift r u e thenJerseywillexposeMBeansforthecol monitoringstatistics.ExposedJMXMBeansareba onMonitoringStatisticsdataandthereforewhenena thecalculationofmonitoringstatisticsgetsautomat enabledtoo(thesameresultassettingtheproperty ServerProperties.MONITORING_STATISTICS_ENA tot r u e ).NotethatenablingMBeansformonitoring statisticsmayhaveanegativeperformanceimpact thereforeshouldbeenabledonlywhenneeded.Defa valueisf a l s e .

ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER (Jersey2.2orlater)

j e r s e y . c o n f i g . c o n t e n t L e n g t h . b u f f e r . s e r v e r

Anintegervaluethatdefinesthebuffersizeusedto theoutboundmessageentityinordertodeterminei andsetthevalueofHTTPC o n t e n t L e n g t h head Defaultvalueis8 1 9 2 . Definesoneormoreclassnamesthatimplement applicationspecificresourcesandproviders.Ifthe propertyisset,thespecifiedclasseswillbeinstant andregisteredaseitherapplicationJAXRSroot resourcesorproviders.

ServerProperties.PROVIDER_CLASSNAMES

j e r s e y . c o n f i g . s e r v e r . p r o v i d e r . c l a s s n a m e s

ServerProperties.PROVIDER_CLASSPATH

j e r s e y . c o n f i g . s e r v e r . p r o v i d e r . c l a s s p a t h

Definesclasspaththatcontainsapplicationspecific resourcesandproviders.Ifthepropertyisset,the specifiedpackageswillbescannedforJAXRSroo resourcesandproviders.

ServerProperties.PROVIDER_PACKAGES

j e r s e y . c o n f i g . s e r v e r . p r o v i d e r . p a c k a g e s

Definesoneormorepackagesthatcontainapplicat specificresourcesandproviders.Ifthepropertyiss thespecifiedpackageswillbescannedforJAXRS resourcesandproviders.

ServerProperties.PROVIDER_SCANNING_RECURSIVE ServerProperties.RESOURCE_VALIDATION_DISABLE

j e r s e y . c o n f i g . s e r v e r . p r o v i d e r . s c a n n i n g . r e c u r s i v e j e r s e y . c o n f i g . s e r v e r . r e s o u r c e . v a l i d a t i o n . d i s a b l e j e r s e y . c o n f i g . s e r v e r . r e s o u r c e . v a l i d a t i o n . i g n o r e E r r o r s j e r s e y . c o n f i g . s e r v e r . w a d l . d i s a b l e W a d l j e r s e y . c o n f i g . s e r v e r . w a d l . g e n e r a t o r C o n f i g

Setstherecursionstrategyforpackagescanning.D valueist r u e .

DisablesR e s o u r c e validation.Defaultvalueisf a l

ServerProperties.RESOURCE_VALIDATION_IGNORE_ERRORS ServerProperties.WADL_FEATURE_DISABLE ServerProperties.WADL_GENERATOR_CONFIG

Determineswhethervalidationofapplicationresourc modelsshouldfailevenincaseofafatalvalidation errors.Defaultvalueisf a l s e .

DisablesWADLgeneration.Defaultvalueisf a l s e

Definesthewadlgeneratorconfigurationthatprovid WadlGenerator.

A.3.Clientconfigurationproperties
ListofclientconfigurationpropertiesthatcanbefoundinClientPropertiesclass. TableA.3.Listofclientconfigurationproperties
Constant ClientProperties.ASYNC_THREADPOOL_SIZE Value j e r s e y . c o n f i g . c l i e n t . a s y n c . t h r e a d P o o l S i z e Description Asynchronousthreadpool size.Defaultvalueisnot set.NOTSUPPORTED. Automaticresponse bufferingincaseofan exception.Defaultvalueis t r u e .NOTSUPPORTED. Chunkedencodingsize. Defaultvalueisnotset. NOTSUPPORTED. Readtimeoutinterval,in milliseconds.Defaultvalue is0 (infinity). Disablesfeatureauto discoveryonclient. Defaultvalueisf a l s e . Declaresthattheclientwill automaticallyredirectto theURIdeclaredin3xx responses.Defaultvalue ist r u e . Declaresthattheclientwill trytosetunsupported HTTPmethodto H t t p U R L C o n n e c t i o n via reflection.Defaultvalueis f a l s e . Disablesconfigurationof JsonProcessing(JSR 353)feature.Defaultvalue isf a l s e . DisablesMETA INF/serviceslookupon client.Defaultvalueis f a l s e . Disablesconfigurationof MOXyJsonfeature. Defaultvalueisf a l s e . Anintegervaluethat

e r s e y . c o n f i g . c l i e n t . b u f f e r R e s p o n s e E n t i t y O n E x c e p t i o n ClientProperties.BUFFER_RESPONSE_ENTITY_ON_EXCEPTION j

ClientProperties.CHUNKED_ENCODING_SIZE

j e r s e y . c o n f i g . c l i e n t . c h u n k e d E n c o d i n g S i z e

ClientProperties.CONNECT_TIMEOUT

j e r s e y . c o n f i g . c l i e n t . c o n n e c t T i m e o u t

ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE

j e r s e y . c o n f i g . d i s a b l e A u t o D i s c o v e r y . c l i e n t

ClientProperties.FOLLOW_REDIRECTS

j e r s e y . c o n f i g . c l i e n t . f o l l o w R e d i r e c t s

ClientProperties .HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND

j e r s e y . c o n f i g . c l i e n t . h t t p U r l C o n n e c t i o n . s e t M e t h o d W o r k a r o u n d

ClientProperties.JSON_PROCESSING_FEATURE_DISABLE

j e r s e y . c o n f i g . d i s a b l e J s o n P r o c e s s i n g . c l i e n t

ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE

j e r s e y . c o n f i g . d i s a b l e M e t a i n f S e r v i c e s L o o k u p . c l i e n t

ClientProperties.MOXY_JSON_FEATURE_DISABLE

j e r s e y . c o n f i g . d i s a b l e M o x y J s o n . c l i e n t

ClientProperties.OUTBOUND_CONTENT_LENGTH_BUFFER (Jersey2.2orlater)

j e r s e y . c o n f i g . c o n t e n t L e n g t h . b u f f e r . c l i e n t

definesthebuffersize usedtobufferthe outboundmessageentity inordertodetermineits sizeandsetthevalueof HTTPC o n t e n t L e n g t h header.Defaultvalueis 8 1 9 2 . Readtimeoutinterval,in milliseconds.Defaultvalue is0 (infinity).

ClientProperties.READ_TIMEOUT

j e r s e y . c o n f i g . c l i e n t . r e a d T i m e o u t

Ift r u e ,thestrict validationofHTTP specificationcompliance forclientsiderequestswill besuppressed.When ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION compliancechecksare j e r s e y . c o n f i g . c l i e n t . s u p p r e s s H t t p C o m p l i a n c e V a l i d a t i o n (Jersey2.2orlater) suppressed,anyviolations willbemerelyloggedas warnings,ratherthan causingexceptionsbeing raisedinJerseyruntime. Defaultvalueisf a l s e . Indicatesthevalueof C o n t e n t E n c o d i n g propertytheEncodingFilter shouldbeadding.Default valueisnotset.

ClientProperties.USE_ENCODING

j e r s e y . c o n f i g . c l i e n t . u s e E n c o d i n g

Вам также может понравиться