Essay for you

Responsebuilder Header Example For Essay

Category: Essay

Description

RESTful JAX-RS File Download Example

RESTful JAX-RS File Download Example

We can download text files, image files, pdf files, excel files in java by JAX-RS API. To do so we need to write few lines of code only. Here, we are using jersey implementation for developing JAX-RS file download examples.

You need to specify different content type to download different files. The @Produces annotation is used to specify the type of file content.

  1. @Produces("text/plain"). for downloading text file.
  2. @Produces("image/png"). for downloading png image file.
  3. @Produces("application/pdf"). for downloading PDF file.
  4. @Produces("application/vnd.ms-excel"). for downloading excel file.
  5. @Produces("application/msword"). for downloading ms word file.
Click me to download jersey jar files. JAX-RS Text File Download

Now run this application on server, you will see the following output:


Click me to download this example

JAX-RS Image File Download

Same as above example.

JAX-RS PDF File Download

Same as above example.

Tel. 0120-4256464
Mob. +91 9990449935
Email. enquiry@sssit.org
Address: 2nd Floor, G-13,
(Near 16 Metro Station),
Sec - 3, Noida,
201301, UP, India
» Contact Us
» Privacy Policy


© 2011-2014 Javatpoint.
All Rights Reserved.

Video

Other articles

NseBuilder (Java EE 6 )

javax.ws.rs.core
Class Response.ResponseBuilder

A class used to build Response instances that contain metadata instead of or in addition to an entity. An initial instance may be obtained via static methods of the Response class, instance methods provide the ability to set metadata. E.g. to create a response that indicates the creation of a new resource:

Several methods have parameters of type URI, UriBuilder provides convenient methods to create such values as does URI.create() .

Where multiple variants of the same method are provided, the type of the supplied parameter is retained in the metadata of the built Response .

Response.ResponseBuilder ()
Protected constructor, use one of the static methods of Response to obtain an instance.

build ()
Create a Response instance from the current ResponseBuilder.

cacheControl (CacheControl cacheControl)
Set the cache control data on the ResponseBuilder.

clone ()
Create a copy of the ResponseBuilder preserving its state.

contentLocation (java.net.URI location)
Set the content location on the ResponseBuilder.

entity (java.lang.Object entity)
Set the entity on the ResponseBuilder.

expires (java.util.Date expires)
Set the expires date on the ResponseBuilder.

header (java.lang.String name, java.lang.Object value)
Add a header to the ResponseBuilder.

language (java.util.Locale language)
Set the language on the ResponseBuilder.

language (java.lang.String language)
Set the language on the ResponseBuilder.

lastModified (java.util.Date lastModified)
Set the last modified date on the ResponseBuilder.

NseBuilder (Java(TM) EE 7 Specification APIs)

Class Response.ResponseBuilder

A class used to build Response instances that contain metadata instead of or in addition to an entity. An initial instance may be obtained via static methods of the Response class, instance methods provide the ability to set metadata. E.g. to create a response that indicates the creation of a new resource:

Several methods have parameters of type URI, UriBuilder provides convenient methods to create such values as does URI.create() .

Where multiple variants of the same method are provided, the type of the supplied parameter is retained in the metadata of the built Response .

Constructor Summary

Constructor and Description

Protected constructor, use one of the static methods of Response to obtain an instance.

Method Summary

Modifier and Type

Method and Description

Set the list of allowed methods for the resource.

Set the list of allowed methods for the resource.

Create a Response instance from the current ResponseBuilder.

Set the cache control data of the message.

Set the content location.

Add cookies to the response message.

Set the message entity content encoding.

Set the response entity in the builder.

Set the response entity in the builder.

Set the response expiration date.

Add an arbitrary header.

Set the message entity language.

Set the message entity language.

Set the response entity last modification date.

Add a link header.

Add a link header.

Add one or more link headers.

Set the location.

Create a new builder instance.

Replaces all existing headers with the newly supplied headers.

Set the status on the ResponseBuilder.

Set the status on the ResponseBuilder.

Set the status on the ResponseBuilder.

Set a response entity tag.

Set a strong response entity tag.

Set the message entity media type.

Set the message entity media type.

Set message entity representation metadata.

Add a Vary header that lists the available variants.

Add a Vary header that lists the available variants.

Methods inherited from class java.lang.Object Constructor Detail ResponseBuilder

Protected constructor, use one of the static methods of Response to obtain an instance.

Method Detail newInstance

Create a new builder instance.

build

Create a Response instance from the current ResponseBuilder. The builder is reset to a blank state equivalent to calling the ok method.

clone

Create a copy of the ResponseBuilder preserving its state.

status

Set the status on the ResponseBuilder.

Parameters: status - the response status. Returns: the updated response builder. Throws: IllegalArgumentException - if status is less than 100 or greater than 599.
  • status

    Set the status on the ResponseBuilder.

    Parameters: status - the response status. Returns: the updated response builder. Throws: IllegalArgumentException - if status is null. Since: 1.1
  • status

    Set the status on the ResponseBuilder.

    Parameters: status - the response status. Returns: the updated response builder. Throws: IllegalArgumentException - if status is null.
  • entity

    Set the response entity in the builder.

    Any Java type instance for a response entity, that is supported by the runtime can be passed. It is the callers responsibility to wrap the actual entity with GenericEntity if preservation of its generic type is required. Note that the entity can be also set as an input stream.

    A specific entity media type can be set using one of the type(. ) methods.

    entity

    Set the response entity in the builder.

    Any Java type instance for a response entity, that is supported by the runtime can be passed. It is the callers responsibility to wrap the actual entity with GenericEntity if preservation of its generic type is required. Note that the entity can be also set as an input stream.

    A specific entity media type can be set using one of the type(. ) methods.

    allow

    Set the list of allowed methods for the resource. Any duplicate method names will be truncated to a single entry.

    Parameters: methods - the methods to be listed as allowed for the resource, if null any existing allowed method list will be removed. Returns: the updated response builder. Since: 2.0
  • allow

    Set the list of allowed methods for the resource.

    Parameters: methods - the methods to be listed as allowed for the resource, if null any existing allowed method list will be removed. Returns: the updated response builder. Since: 2.0
  • cacheControl

    Set the cache control data of the message.

    Parameters: cacheControl - the cache control directives, if null any existing cache control directives will be removed. Returns: the updated response builder.
  • encoding

    Set the message entity content encoding.

    Parameters: encoding - the content encoding of the message entity, if null any existing value for content encoding will be removed. Returns: the updated response builder. Since: 2.0
  • header

    Add an arbitrary header.

    Parameters: name - the name of the header value - the value of the header, the header will be serialized using a RuntimeDelegate.HeaderDelegate if one is available via RuntimeDelegate.createHeaderDelegate(java.lang.Class) for the class of value or using its toString method if a header delegate is not available. If value is null then all current headers of the same name will be removed. Returns: the updated response builder.
  • replaceAll

    Replaces all existing headers with the newly supplied headers.

    Parameters: headers - new headers to be set, if null all existing headers will be removed. Returns: the updated response builder. Since: 2.0
  • language

    Set the message entity language.

    Parameters: language - the language of the message entity, if null any existing value for language will be removed. Returns: the updated response builder.
  • language

    Set the message entity language.

    Parameters: language - the language of the message entity, if null any existing value for type will be removed. Returns: the updated response builder.
  • type

    Set the message entity media type.

    Parameters: type - the media type of the message entity. If null. any existing value for type will be removed. Returns: the updated response builder.
  • type

    Set the message entity media type.

    Parameters: type - the media type of the message entity. If null. any existing value for type will be removed. Returns: the updated response builder.
  • variant

    Set message entity representation metadata.

    Equivalent to setting the values of content type, content language, and content encoding separately using the values of the variant properties.

    Parameters: variant - metadata of the message entity, a null value is equivalent to a variant with all null properties. Returns: the updated response builder. Since: 2.0 See Also: encoding(java.lang.String). language(java.util.Locale). type(javax.ws.rs.core.MediaType)
  • contentLocation

    Set the content location.

    Parameters: location - the content location. Relative or absolute URIs may be used for the value of content location. If null any existing value for content location will be removed. Returns: the updated response builder.
  • cookie

    Add cookies to the response message.

    Parameters: cookies - new cookies that will accompany the response. A null value will remove all cookies, including those added via the header(java.lang.String, java.lang.Object) method. Returns: the updated response builder.
  • expires

    Set the response expiration date.

    Parameters: expires - the expiration date, if null removes any existing expires value. Returns: the updated response builder.
  • lastModified

    Set the response entity last modification date.

    Parameters: lastModified - the last modified date, if null any existing last modified value will be removed. Returns: the updated response builder.
  • location

    Set the location.

    Parameters: location - the location. If a relative URI is supplied it will be converted into an absolute URI by resolving it relative to the base URI of the application (see UriInfo.getBaseUri() ). If null any existing value for location will be removed. Returns: the updated response builder.
  • tag

    Set a response entity tag.

    Parameters: tag - the entity tag, if null any existing entity tag value will be removed. Returns: the updated response builder.
  • tag

    Set a strong response entity tag.

    This is a shortcut for tag(new EntityTag(value )) .

    Parameters: tag - the string content of a strong entity tag. The JAX-RS runtime will quote the supplied value when creating the header. If null any existing entity tag value will be removed. Returns: the updated response builder.
  • variants

    Add a Vary header that lists the available variants.

    Parameters: variants - a list of available representation variants, a null value will remove an existing value for Vary header. Returns: the updated response builder. Since: 2.0
  • variants

    Add a Vary header that lists the available variants.

    Parameters: variants - a list of available representation variants, a null value will remove an existing value for Vary header. Returns: the updated response builder.
  • links

    Add one or more link headers.

    Parameters: links - links to be added to the message as headers, a null value will remove any existing Link headers. Returns: the updated response builder. Since: 2.0
  • link

    Add a link header.

    Parameters: uri - underlying URI for link header. rel - value of "rel" parameter. Returns: the updated response builder. Since: 2.0
  • link

    Add a link header.

    Parameters: uri - underlying URI for link header. rel - value of "rel" parameter. Returns: the updated response builder. Since: 2.0

List of header() Examples

        for ( Annotation annot. orderAnnots ) <

            if ( annot instanceof WebParam ) <

                WebParam webParam = ( WebParam ) annot;

                WebParamAnnot wpAnnot = WebParamAnnot.createWebParamAnnotImpl () ;

                wpAnnot.setHeader ( webParam.header ()) ;

                wpAnnot.setMode ( webParam.mode ()) ;

                wpAnnot.setName ( webParam.name ()) ;

                wpAnnot.setPartName ( webParam.partName ()) ;

                wpAnnot.setTargetNamespace ( webParam.targetNamespace ()) ;

                pdc.setWebParamAnnot ( wpAnnot ) ;

                hp0.setHeaderType ( "Client setup Header Type for HeaderPart0" ) ;

                HeaderPart1 hp1 = new HeaderPart1 () ;

                hp1.setHeaderType ( "Client setup Header Type for HeaderPart0" ) ;

                Holder<HeaderPart0> holder = new Holder<HeaderPart0> ( hp0 ) ;

                DocLitWrap proxy = getProxy () ;

                HeaderResponse hr = proxy.header ( header, holder, hp1 ) ;

                TestLogger.logger.debug ( "Holder Response String =" + hp0.getHeaderType ()) ;

                TestLogger.logger.debug ( "Header Response Long =" + hr.getOut ()) ;

                // Repeat to ensure correct behavior

Red Hat JBoss Fuse - Developing RESTful Web Services - Handling more advanced responses

Overview

The Response class methods provide short cuts for creating responses for common cases. When you need to address more complicated cases such as specifying cache control directives, adding custom HTTP headers, or sending a status not handled by the Response class, you need to use the ResponseBuilder classes methods to populate the response before using the build() method to generate the response object.

Tip

As discussed in Getting a response builder. you can use the Apache CXF ResponseBuilderImpl class to create a response builder instance that can be manipulated directly.

Adding custom headers

Custom headers are added to a response using the ResponseBuilder class' header() method. The header() method takes two parameters:

name —a string specifying the name of the header

value —a Java object containing the data stored in the header

You can set multiple headers on the message by calling the header() method repeatedly.

Example 27 shows code for adding a header to a response.

Example 27. Adding a header to a response

Adding a cookie

Custom headers are added to a response using the ResponseBuilder class' cookie() method. The cookie() method takes one or more cookies. Each cookie is stored in a javax.ws.rs.core.NewCookie object. The easiest of the NewCookie class' contructors to use takes two parameters:

name —a string specifying the name of the cookie

value —a string specifying the value of the cookie

You can set multiple cookies by calling the cookie() method repeatedly.

Example 28 shows code for adding a cookie to a response.

Example 28. Adding a cookie to a response

Warning

Calling the cookie() method with a null parameter list erases any cookies already associated with the response.

Setting the response status

When you want to return a status other than one of the statuses supported by the Response class' helper methods, you can use the ResponseBuilder class' status() method to set the response's status code. The status() method has two variants. One takes an int that specifies the response code. The other takes a Response.Status object to specify the response code.

The Response.Status class is an enumeration enclosed in the Response class. It has entries for most of the defined HTTP response codes.

Example 29 shows code for setting the response status to 404 Not Found .

Example 29. Adding a header to a response

Setting cache control directives

The ResponseBuilder class' cacheControl() method allows you to set the cache control headers on the response. The cacheControl() method takes a javax.ws.rs.CacheControl object that specifies the cache control directives for the response.

The CacheControl class has methods that correspond to all of the cache control directives supported by the HTTP specification. Where the directive is a simple on or off value the setter method takes a boolean value. Where the directive requires a numeric value, such as the max-age directive, the setter takes an int value.

Example 30 shows code for setting the no-store cache control directive.

Example 30. Adding a header to a response

Implementando CORS em Web Services com JAX-RS (Jersey)

Implementando CORS em Web Services com JAX-RS (Jersey)

Este post apresenta o CORS e sua aplicação no tratamento de requisições HTTP, além de demonstrar a implementação desse mecanismo utilizando os filtros do JAX-RS no Jersey.
Por fim, é ilustrada a comunicação entre o Web Service e um cliente AngularJS.

Linguagens de script web como o Javascript utilizam uma API chamada XMLHttpRequest (ou XHR) para enviar requisições HTTP/HTTPS, não só para requisições com conteúdo em formato XML como o nome sugere, mas também em JSON e outros formatos. Essa API é a base do funcionamento do AJAX, usada para atualizar os dados de uma página sem precisar recarregar todo seu conteúdo através de comunicação assíncrona.
Contudo, devido a questões de segurança que envolvem ataques por Cross-site Scripting (XSS), as requisições XHR seguem uma política chamada Same-Origin Policy. a qual limita o envio de requisições entre domínios distintos, ou seja, essa política determina que o XHR só pode enviar requisições para o mesmo domínio de onde está sendo enviado.

Devido a necessidade de existir uma forma segura de enviar requisições com XHR para o mundo externo, o W3C definiu o Cross-Origin Resource Sharing (CORS). Esse mecanismo possibilita o envio dessas requisições com a adição de um cabeçalho HTTP no servidor, o Access-Control-Allow-Origin, que determina quais domínios tem permissão para enviar requisições cross-domain ao servidor.

Ou dessa forma para aceitar de qualquer domínio…

Requisições Preflighted

Em alguns casos, como quando a requisição não é GET ou HEAD. ou quando é necessário utilizar cabeçalhos não-padrões, o fluxo da requisição ocorre de forma diferente, o que é denominado de requisição preflighted .
Nesse fluxo, antes da requisição em si ser enviada, primeiramente é enviada uma requisição OPTIONS intermediária ao servidor, que retorna informações que permitem identificar se a requisição principal é permitida. Em caso positivo, então a requisição é enviada.
Além disso o servidor precisa adicionar mais alguns cabeçalhos para lidar com esse cenário, o Access-Control-Request-Methods e o Access-Control-Request-Headers. que determina quais metódos podem ser usados e quais cabeçalhos não-padrões são permitidos, respectivamente.

A necessidade de enviar uma requisição extra(OPTIONS ), leva a duplicação da quantidade de requisições na comunicação com o servidor, e devido a isso foi definido também o cabeçalho Access-Control-Max-Age, que configura um tempo para a resposta da requisição OPTIONS ficar armazenada em cache no cliente, não precisando ser enviada repetidamente.

Porém na prática esse recurso não funciona como deveria, pois cada browser define um limite para esse tempo, que geralmente é pequeno, buscando evitar problemas de segurança.

Filtros JAX-RS

O JAX-RS é uma especificação do Java para a construção de Web Services RESTful, sendo o Jersey API uma das suas implementações mais populares, que através de anotações e outros recursos tornou mais simples o desenvolvimento desses serviços.
Um recurso ideal do JAX-RS para a implementação do CORS é o conceito de Filtros, que são rotinas executadas antes de cada requisição ser tratada, ou antes de cada resposta ser enviada.
No código abaixo um Filtro é implementado para adicionar os cabeçalhos do CORS a cada resposta do serviço.

No Jersey, além da implementação acima também é necessário adicionar o filtro no arquivo web.xml .

Testando com um cliente AngularJS

O AngularJS é um framework javascript mantido pelo Google que, entre outras coisas, é muito útil na comunicação com serviços externos, executando todo seu código na máquina cliente. Para essa comunicação o AngularJS se baseia na XMLHttpRequest API, onde uma requisição POST pode ser implementada como apresentado abaixo.

O quadro a seguir ilustra a comunicação cliente-servidor, nesse caso a requisição é preflighted por incluir um cabeçalho não-padrão(Foo-Header ), e também por ser do tipo POST com conteúdo em formato JSON.

Se o servidor não retornar as permissões necessárias nos cabeçalhos do CORS, um erro é lançado pelo XMLHttpRequest :

XMLHttpRequest cannot load http. //server.example/resources/post. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Referências
  • W3C; “Access Control for Cross-Site Requests”; Link .
  • MDN; “HTTP access control (CORS)”; Link .
  • Jersey Documentation; “Filters and Interceptors”; Link .
  • AngularJS Docs; “$http Service”; Link .
Post navigation Follow Blog via Email Referências

Examples of r()

    private Response getCompositeExceptionResponse ( final SyncopeClientCompositeErrorException ex ) <

        ResponseBuilder responseBuilder = Response.status ( ex.getStatusCode () .value ()) ;

        for ( SyncopeClientException sce. ex.getExceptions ()) <

            responseBuilder.header ( EXCEPTION_TYPE_HEADER, sce.getType () .getHeaderValue ()) ;

            for ( String attributeName. sce.getElements ()) <

                responseBuilder.header ( sce.getType () .getElementHeaderName (). attributeName ) ;

        ResponseBuilder responseBuilder = Response.status ( ex.getStatusCode () .value ()) ;

        for ( SyncopeClientException sce. ex.getExceptions ()) <

            responseBuilder.header ( EXCEPTION_TYPE_HEADER, sce.getType () .getHeaderValue ()) ;

            for ( String attributeName. sce.getElements ()) <

                responseBuilder.header ( sce.getType () .getElementHeaderName (). attributeName ) ;

        return responseBuilder.build () ;

        > else if ( ex instanceof InvalidEntityException ) <

            SyncopeClientExceptionType exType = SyncopeClientExceptionType.valueOf ( "Invalid"

                    + (( InvalidEntityException ) ex ) .getEntityClassSimpleName ()) ;

            responseBuilder.header ( SyncopeClientErrorHandler.EXCEPTION_TYPE_HEADER, exType.getHeaderValue ()) ;

            for ( @SuppressWarnings ( "rawtypes" ) Map.Entry<Class, Set<EntityViolationType>> violation

                   . (( InvalidEntityException ) ex ) .getViolations () .entrySet ()) <

                for ( EntityViolationType violationType. violation.getValue ()) <

            for ( @SuppressWarnings ( "rawtypes" ) Map.Entry<Class, Set<EntityViolationType>> violation

                   . (( InvalidEntityException ) ex ) .getViolations () .entrySet ()) <

                for ( EntityViolationType violationType. violation.getValue ()) <

                    responseBuilder.header ( exType.getElementHeaderName ().

                            violation.getClass () .getSimpleName () + ": " + violationType ) ;

            return responseBuilder.build () ;

        > else if ( ex instanceof WorkflowException ) <

            if ( entry.getValue () .size () > 0 ) <

                if ( HttpUtils.isDateRelatedHeader ( entry.getKey ())) <

                    currentResponseBuilder.header ( entry.getKey (). entry.getValue () .get ( 0 )) ;

                    continue ;                   

                boolean splitPossible =. ( HttpHeaders.SET_COOKIE.equalsIgnoreCase ( entry.getKey ())

                                          && entry.getValue () .get ( 0 ) .contains ( HttpHeaders.EXPIRES )) ;

                for ( String val. entry.getValue ()) <

                for ( String val. entry.getValue ()) <

                    String [] values = splitPossible. val.split ( "," ). new String []< val > ;

                    for ( String s. values ) <

                        String theValue = s.trim () ;

                        if ( theValue.length () > 0 ) <

                            currentResponseBuilder.header ( entry.getKey (). theValue ) ;

    public static ResponseBuilder createResponseBuilder ( ClassResourceInfo cri, int status, boolean addAllow ) <

        ResponseBuilder rb = Response.status ( status ) ;

        if ( addAllow ) <

            Set<String> allowedMethods = cri.getAllowedMethods () ;

            for ( String m. allowedMethods ) <

                rb.header ( "Allow". m ) ;

            // "OPTIONS" are supported all the time really

            if ( !allowedMethods.contains ( "OPTIONS" )) <

                rb.header ( "Allow". "OPTIONS" ) ;

                rb.header ( "Allow". m ) ;

            // "OPTIONS" are supported all the time really

            if ( !allowedMethods.contains ( "OPTIONS" )) <

                rb.header ( "Allow". "OPTIONS" ) ;

            if ( !allowedMethods.contains ( "HEAD" ) && allowedMethods.contains ( "GET" )) <

                rb.header ( "Allow". "HEAD" ) ;

Responsebuilder header example for essay

ResponseBuilder trait ResponseBuilder extends AnyRef

Defines how responses will be handled. The 'standard' implementation is BufferedResponseBuilder, which returns responses buffered in byte arrays (and also strings). When an HTTP request is made, captureResponse will usually be called once. However, during authentication, it may be called more than once, all times except the last are transient; implementations need to handle this correctly.

Ordering
  1. Alphabetic
  2. By inheritance
Abstract Value Members abstract def captureResponse ( request: Request. status: Status. mediaType: Option [MediaType ]. headers: Headers. cookies: Option [CookieJar ]. stream: InputStream ). Unit

Defines the method to be invoked when the response is first received.

Concrete Value Members final def != ( arg0: AnyRef ). Boolean

Definition Classes AnyRef

final def != ( arg0: Any ). Boolean

Definition Classes Any

final def ## (). Int

Definition Classes AnyRef → Any

final def == ( arg0: AnyRef ). Boolean

Definition Classes AnyRef

final def == ( arg0: Any ). Boolean

Definition Classes Any

final def asInstanceOf [ T0 ]. T0

Definition Classes Any

def clone (). AnyRef

Attributes protected[java.lang ] Definition Classes AnyRef Annotations @throws ()

final def eq ( arg0: AnyRef ). Boolean

Definition Classes AnyRef

def equals ( arg0: Any ). Boolean

Definition Classes AnyRef → Any

def finalize (). Unit

Attributes protected[java.lang ] Definition Classes AnyRef Annotations @throws ()

final def getClass (). Class [_]

Definition Classes AnyRef → Any

def hashCode (). Int

Definition Classes AnyRef → Any

final def isInstanceOf [ T0 ]. Boolean

Definition Classes Any

final def ne ( arg0: AnyRef ). Boolean

Definition Classes AnyRef

final def notify (). Unit

Definition Classes AnyRef

final def notifyAll (). Unit

Definition Classes AnyRef

def response. Option [Response ]

Gets the response that was captured earlier.

final def synchronized [ T0 ] ( arg0: ⇒ T0 ). T0

Definition Classes AnyRef

def toString (). String

Definition Classes AnyRef → Any

final def wait (). Unit

Definition Classes AnyRef Annotations @throws ()

final def wait ( arg0: Long. arg1: Int ). Unit

Definition Classes AnyRef Annotations @throws ()

final def wait ( arg0: Long ). Unit

Definition Classes AnyRef Annotations @throws ()