Example usage for org.springframework.http.server ServletServerHttpResponse ServletServerHttpResponse

List of usage examples for org.springframework.http.server ServletServerHttpResponse ServletServerHttpResponse

Introduction

In this page you can find the example usage for org.springframework.http.server ServletServerHttpResponse ServletServerHttpResponse.

Prototype

public ServletServerHttpResponse(HttpServletResponse servletResponse) 

Source Link

Document

Construct a new instance of the ServletServerHttpResponse based on the given HttpServletResponse .

Usage

From source file:org.craftercms.commons.rest.HttpMessageConvertingResponseWriter.java

public <T> void writeWithMessageConverters(T returnValue, HttpServletRequest request,
        HttpServletResponse response) throws IOException, HttpMediaTypeNotAcceptableException {
    Class<?> returnValueClass = returnValue.getClass();
    List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
    List<MediaType> producibleMediaTypes = getProducibleMediaTypes(returnValueClass);

    Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
    for (MediaType r : requestedMediaTypes) {
        for (MediaType p : producibleMediaTypes) {
            if (r.isCompatibleWith(p)) {
                compatibleMediaTypes.add(getMostSpecificMediaType(r, p));
            }/*from  ww w .  j  a va 2s  .c  om*/
        }
    }
    if (compatibleMediaTypes.isEmpty()) {
        throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
    }

    List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
    MediaType.sortBySpecificityAndQuality(mediaTypes);

    MediaType selectedMediaType = null;
    for (MediaType mediaType : mediaTypes) {
        if (mediaType.isConcrete()) {
            selectedMediaType = mediaType;
            break;
        } else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
            selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
            break;
        }
    }

    if (selectedMediaType != null) {
        selectedMediaType = selectedMediaType.removeQualityValue();
        for (HttpMessageConverter<?> messageConverter : messageConverters) {
            if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
                ((HttpMessageConverter<T>) messageConverter).write(returnValue, selectedMediaType,
                        new ServletServerHttpResponse(response));

                logger.debug(LOG_KEY_WRITTEN_WITH_MESSAGE_CONVERTER, returnValue, selectedMediaType,
                        messageConverter);

                return;
            }
        }
    }

    throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
}

From source file:com.wbss.mycoffee.ui.services.ApiController.java

/**
 * Write json data to response stream//from w  ww .  j a  v a2 s . co  m
 * @param json
 * @param response
 * @throws Exception
 */
private void wirteJsonToResponse(String json, HttpServletResponse response) throws Exception {

    AbstractHttpMessageConverter<String> stringHttpMessageConverter = new StringHttpMessageConverter(
            Charset.forName("UTF-8"));
    MediaType jsonMimeType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("UTF-8"));

    if (stringHttpMessageConverter.canWrite(String.class, jsonMimeType)) {
        stringHttpMessageConverter.write(json, jsonMimeType, new ServletServerHttpResponse(response));
    }

}

From source file:com.epam.ta.reportportal.commons.exception.rest.RestExceptionHandler.java

@SuppressWarnings({ "rawtypes", "unchecked", "resource" })
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws HttpMessageNotWritableException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*w w w .  j  a  va  2s . c o  m*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.messageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    // return empty model and view to short circuit the
                    // iteration and to let
                    // Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:org.ayfaar.app.spring.handler.RestExceptionHandler.java

@SuppressWarnings("unchecked")
protected ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*w w w.j  a  va2 s  . c  o  m*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:org.appverse.web.framework.backend.frontfacade.json.controllers.JSONController.java

/**
 * Method to handle all requests to the Appverse Services Presentation
 * Layer. It only accepts POST requests, with the parameter set on the
 * payload. The URL must contain the servicename (spring name of the
 * Presentation Service) and also the method name. The URL musb be something
 * like: {protocol}://{host}:{port}/{appcontext}/{servicename}/{methodname}
 * //from   w w w.j  a v a2 s.c om
 * @param requestServiceName
 *            The "spring" name of the Service.
 * @param requestMethodName
 *            The method name
 * @param response
 *            The HttpServletResponse, injected by Jersey.
 * @param payload
 *            The payload must contain the parameter as json.
 * @return
 * @throws Exception
 *             In case of any Bad Request or an uncontrolled exception
 *             raised by the Service.
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{servicename}/{methodname}")
public String handleRequest(@PathParam("servicename") String requestServiceName,
        @PathParam("methodname") String requestMethodName, @Context HttpServletRequest request,
        @Context HttpServletResponse response, String payload) throws Exception {
    // String path = request.getServletPath();
    System.out.println("Request Received - " + requestServiceName + "." + requestMethodName);

    Object presentationService = applicationContext.getBean(requestServiceName);
    if (presentationService == null) {
        throw new BadRequestException("Requested ServiceFacade don't exists " + requestServiceName);
    }
    if (!(presentationService instanceof AuthenticationServiceFacade)) {
        SecurityHelper.checkXSRFToken(request);
    }
    if (presentationService instanceof AuthenticationServiceFacade
            && requestMethodName.equals("getXSRFSessionToken")) {
        ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
        customMappingJacksonHttpMessageConverter.write(SecurityHelper.createXSRFToken(request),
                org.springframework.http.MediaType.APPLICATION_JSON, outputMessage);
        addDefaultResponseHeaders(response);
        return "";

    }

    // Determine if method exist by name.
    Method[] methods = presentationService.getClass().getMethods();
    List<Method> availableMethod = new ArrayList<Method>();
    for (Method methodItem : methods) {
        if (methodItem.getName().equals(requestMethodName)) {
            availableMethod.add(methodItem);
            // method = methodItem;
            // break;
        }
    }
    if (availableMethod != null && availableMethod.size() == 0) {
        throw new BadRequestException("Requested Method don't exists " + requestMethodName
                + " for serviceFacade " + requestServiceName);
    }
    boolean badRequest = false;
    StringBuffer sbf = new StringBuffer();
    Method methodFound = null;
    Object parameterFound = null;
    Object[] parametersFound = null;
    // Identify on the available methods the correct method to execute,
    // based on the parameters and its types (trying to convert them).
    for (Method methodItem : availableMethod) {
        Class<?>[] parameterTypes = methodItem.getParameterTypes();
        Class<?> parameterType = null;
        if (parameterTypes.length > 1) {
            try {
                parametersFound = customMappingJacksonHttpMessageConverter.readInternal(parameterTypes,
                        payload);
                methodFound = methodItem;
                badRequest = false;
                //method found and objects correctly parsed
                break;
            } catch (Throwable th) {
                badRequest = true;
                sbf.append("{Error parsing json [" + th.getMessage() + "]");
            }
        }
        if (parameterTypes.length > 0) {
            parameterType = parameterTypes[0];
            try {
                parameterFound = customMappingJacksonHttpMessageConverter.readInternal(parameterType, payload);
                methodFound = methodItem;
                badRequest = false;
                break; //found the correct method to execute.
            } catch (Throwable th) {
                badRequest = true;
                sbf.append("{Parameter of type " + parameterType.getCanonicalName() + " can't be parsed}");
            }
        } else {
            // only accepting parameters less methods in case payload is
            // empty
            if (payload != null && payload.length() == 0) {
                methodFound = methodItem;
                badRequest = false;
                break; //found the correct method to execute
            }
        }
    }
    if (badRequest) {
        sbf.append(" from [" + payload + "]");
        throw new BadRequestException(sbf.toString());
    }
    try {
        //invoke the method
        Object result = null;
        if (parameterFound != null) { //method with one parameter
            result = methodFound.invoke(presentationService, parameterFound);
        } else if (parametersFound != null) { //method with multiple parameters
            result = methodFound.invoke(presentationService, parametersFound);
        } else { //method with no parameters
            result = methodFound.invoke(presentationService);
        }
        // return Response.ok(result, MediaType.APPLICATION_JSON).build();
        ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
        if (result != null) {
            //only write result in case it is not void!
            customMappingJacksonHttpMessageConverter.write(result,
                    org.springframework.http.MediaType.APPLICATION_JSON, outputMessage);
        }
        addDefaultResponseHeaders(response);
    } catch (Throwable th) {
        // response.sendError(500, th.getMessage());
        th.printStackTrace();
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity("Service Internal Error [" + th.getCause() != null ? th.getCause().getMessage()
                        : th.getMessage() + "]")
                .build());
        /*ResponseBuilderImpl builder = new ResponseBuilderImpl();
        builder.status(Response.Status.INTERNAL_SERVER_ERROR);
        builder.entity("Service Internal Error [" + th.getCause() != null ? th
              .getCause().getMessage() : th.getMessage() + "]");
        Response resp = builder.build();
        throw new WebApplicationException(resp);*/
    }
    return "";

}

From source file:com.sybase365.mobiliser.custom.project.channels.HttpChannelEnd.java

@SuppressWarnings("unchecked")
@Override/*from  w w w .j a v a  2 s  .co  m*/
public void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("Incoming {} request", request.getMethod());

    checkAndPrepare(request, response, false);

    final MultiValueMap<String, String> result = (MultiValueMap<String, String>) this.converter.read(null,
            new ServletServerHttpRequest(request));

    final List<String> textList = result.get("text");
    final List<String> fromList = result.get("from");
    final List<String> toList = result.get("to");
    final List<String> typeList = result.get("type");

    if (textList == null || textList.isEmpty()) {
        throw new MissingServletRequestParameterException("text", "string");
    }

    if (fromList == null || fromList.isEmpty()) {
        throw new MissingServletRequestParameterException("from", "string");
    }

    if (toList == null || toList.isEmpty()) {
        throw new MissingServletRequestParameterException("to", "string");
    }

    final String type;
    if (null == typeList || typeList.isEmpty()) {
        type = "sms";
    } else {
        type = typeList.get(0);
    }

    final Message req = this.messagingEngine.parseSimpleTextMessage(type, textList.get(0));
    req.setSender(fromList.get(0));
    req.setRecipient(toList.get(0));

    if (LOG.isDebugEnabled()) {
        LOG.debug("{} message received for {} from {}",
                new Object[] { type, req.getRecipient(), req.getSender() });
    }

    final Future<Message> responseMessage = this.receiveCallback.receiveAndRespondMessage(req, this.channelId,
            this.incomingChannelId);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Handed off message to {} for {} awaiting response", this.receiveCallback,
                this.incomingChannelId);
    }

    final Message message;
    try {
        message = responseMessage.get();

        if (message == null) {
            LOG.warn("Timed out waiting for response from {}", responseMessage);

            throw new NestedServletException("Timed out waiting for message");
        }
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt(); // reset flag

        throw new NestedServletException("Interrupted during processing", e);

    } catch (final ExecutionException e) {
        if (e.getCause() instanceof InterruptedException) {
            throw new NestedServletException( // NOSONAR
                    "Interrupted during processing", e.getCause());
        }

        throw new NestedServletException("Processing message failed", // NOSONAR
                e.getCause());
    }

    LOG.debug("Writing response back to client");

    final LinkedMultiValueMap<String, Object> responseMap = new LinkedMultiValueMap<String, Object>();

    responseMap.add("from", message.getSender().getAddress());
    responseMap.add("to", message.getRecipient().getAddress());

    if (message instanceof SmsMessage) {
        responseMap.add("text", new String(((SmsMessage) message).getText().getContent(),
                ((SmsMessage) message).getText().getCharset()));
    } else if (message instanceof UssdTextMessage) {
        responseMap.add("text", new String(((UssdTextMessage) message).getText().getContent(),
                ((UssdTextMessage) message).getText().getCharset()));
    }

    this.converter.write(responseMap, this.mediaType, new ServletServerHttpResponse(response));

}

From source file:it.unitn.disi.smatch.web.server.api.handlers.ExceptionDetailsExceptionResolver.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {
    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*from   w  ww  . j a v a2  s . c om*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:de.iteratec.iteraplan.presentation.ajax.DojoUtils.java

public static void write(Object data, HttpServletResponse response) throws IOException {
    HttpMessageConverter<Object> converter = getConverter();
    if (!converter.canWrite(data.getClass(), MediaType.APPLICATION_JSON)) {
        throw new IllegalArgumentException("The object cannot be serialized to JSON");
    }//from w w  w.  j  a v  a  2s . c  o m

    converter.write(data, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
}

From source file:com.oolong.platform.web.error.RestExceptionHandler.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }//from ww  w  .  ja  v  a  2s.co m

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    // return empty model and view to short circuit the
                    // iteration and to let
                    // Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:com.novation.eligibility.rest.spring.web.servlet.handler.RestExceptionHandler.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }//from   w  w  w .  ja v  a2s  .  c  o  m

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}