Example usage for org.springframework.http HttpHeaders setContentType

List of usage examples for org.springframework.http HttpHeaders setContentType

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders setContentType.

Prototype

public void setContentType(@Nullable MediaType mediaType) 

Source Link

Document

Set the MediaType media type of the body, as specified by the Content-Type header.

Usage

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>//  w w w  .ja  v a2  s  .co  m
 * HTTP Header? ??  ?.
 * </pre>
 * @return
 */
private HttpEntity<Object> setHTTPEntity(Object body, String rootElementName) {
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    acceptableMediaTypes.add(MediaType.APPLICATION_XML);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_XML);
    requestHeaders.setAccept(acceptableMediaTypes);
    requestHeaders.set(HOST_HEADER_KEY, host);
    requestHeaders.set(AUTH_HEADER_KEY, getCredential());

    if (body != null) {
        logger.debug("Content Body => {}", marshal(body, rootElementName));
        return new HttpEntity<Object>(marshal(body, rootElementName), requestHeaders);
    } else {
        return new HttpEntity<Object>(requestHeaders);
    }
}

From source file:edu.sjsu.cmpe275.lab2.service.ManagePersonController.java

/** Get a person object
 2 Path: person/ {id}?format={json | xml | html}
 Method: GET// ww  w  .j  a  v  a2 s .  co  m
 This returns a full person object with the given ID in the given format in its HTTP payload.
 ? All existing fields, including the optional organization and list of friends should be
 returned.
  The payload should contain the full organization object, if present.
        
 The list of friends can be either (a) list of person IDs, or (b) list of  shallow ?
 person objects that do not have their friends list populated. If you take option
 (b), you want to use techniques like lazy loading to avoid serializing the whole
 social network starting from the requested person in the returned payload.
 ? If the person of the given user ID does not exist, the HTTP return code should be 404;
 otherwise, 200.
 ? The format parameter is optional, and the value is case insensitive. If missing, JSON is
 assumed.
        
 * @param a         Description of a
 * @param b         Description of b
 * @return         Description of c
 */

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getPerson(@PathVariable("id") long id,
        @RequestParam(value = "format", required = true) String format) {
    Transaction transaction = null;
    Session session = null;
    Person person = null;
    HttpHeaders httpHeaders = new HttpHeaders();

    if ("json".equals(format)) {
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    } else if ("xml".equals(format)) {
        httpHeaders.setContentType((MediaType.APPLICATION_XML));
    } else if ("html".equals(format)) {
        httpHeaders.setContentType(MediaType.TEXT_HTML);
    } else {
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    }

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        person = (Person) session.get(Person.class, id);
        if (person == null) {
            throw new HibernateException("Can't find record with id = " + id);
        }
        transaction.commit();

    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
        return new ResponseEntity<Object>("Can't find record with id = " + id, httpHeaders,
                HttpStatus.NOT_FOUND);
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return new ResponseEntity<>(person, httpHeaders, HttpStatus.OK);
}

From source file:com.dbi.jmmerge.MapController.java

@ExceptionHandler
public ResponseEntity<Map> handleException(Exception ex, HttpServletRequest request) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    Map msgs = new HashMap();
    ResponseEntity<Map> ret = new ResponseEntity<Map>(msgs, headers, HttpStatus.INTERNAL_SERVER_ERROR);
    msgs.put("message", "An error occurred . . . contact your administrator for details.");
    msgs.put("error", ex.getMessage());
    LOG.error("An error occurred handling a " + request.getMethod() + " to URL " + request.getRequestURL(), ex);
    return ret;// ww  w.  ja va 2  s  . com
}

From source file:com.founder.zykc.controller.FdbzcrjryController.java

@SuppressWarnings("static-access")
@RequestMapping(value = "/queryFdbzcrjryPhoto.jpg", method = RequestMethod.GET)
public HttpEntity<byte[]> queryFdbzcrjryPhoto(String rydh, SessionBean sessionBean) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    sessionBean = getSessionBean(sessionBean);

    byte[] pictureByte = null;

    String url = "http://10.78.17.154:9999/lbs";
    String zpParameter = "operation=ForbiddenDepartureManagement_GetPhotoByID_v001&license=a756244eb0236bdc26061cb6b6bdb481&content=";
    String zpContent = "{\"data\":[{\"RYDH\":\"" + rydh + "\"}]}";
    try {/*from  ww w .  j a v a 2  s . c  o  m*/

        zpContent = zpParameter + java.net.URLEncoder.encode(zpContent, "UTF-8");
        PostMethod postMethod = new PostMethod(url);
        byte[] b = zpContent.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);
        HttpClient httpClient = new HttpClient();
        HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
        managerParams.setConnectionTimeout(50000);
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == 200) {
            String soapResponseData = postMethod.getResponseBodyAsString();
            JSONObject jb = JSONObject.fromObject(soapResponseData);
            if ((Integer) jb.get("datalen") > 0) {
                JSONObject jo = jb.getJSONArray("data").getJSONObject(0);

                try {
                    pictureByte = new BASE64Decoder().decodeBuffer(jo.getString("PHOTO"));
                } catch (Exception ex) {
                }
                if (pictureByte != null) {

                } else {
                    System.out.println("??" + statusCode);
                    byte[] empty_ryzp = SystemConfig.getByteArray("empty_ryzp");
                    headers.setContentLength(empty_ryzp.length);
                    return new HttpEntity(empty_ryzp, headers);
                }

            } else {
                System.out.println("??" + statusCode);
                byte[] empty_ryzp = SystemConfig.getByteArray("empty_ryzp");
                headers.setContentLength(empty_ryzp.length);
                return new HttpEntity(empty_ryzp, headers);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    headers.setContentLength(pictureByte.length);
    return new HttpEntity(pictureByte, headers);

}

From source file:com.github.ibm.domino.client.BaseClient.java

protected HttpEntity<String> getHttpEntity() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
    headers.setContentType(MediaType.APPLICATION_JSON);
    return new HttpEntity<>(headers);
}

From source file:com.allogy.amazonaws.elasticbeanstalk.worker.simulator.application.WorkerApplication.java

private HttpEntity<String> createHttpEntity(MessageWrapper messageWrapper, Message message) {
    String messageId = message.getMessageId();

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-Agent", "aws-sqsd/1.1 (simulated bridge)");
    headers.set("X-Aws-Sqsd-Msgid", messageId);
    headers.set("X-Aws-Sqsd-Queue", messageWrapper.getQueueName());
    headers.set("X-Aws-Sqsd-Receive-Count", Integer.toString(messageWrapper.getMessageCount()));
    headers.setContentType(MediaType.APPLICATION_JSON);

    return new HttpEntity<>(message.getBody(), headers);
}

From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java

@RequestMapping(value = "executor/execution/{executionId}/input", method = RequestMethod.GET)
public ResponseEntity<String> getInputputXml(@PathVariable String executionId) throws Exception {
    File xml = fileSystemResolver.getFiles(executionId).getInputQdmXml();

    String xmlString = FileUtils.readFileToString(xml, "UTF-8");

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);

    return new ResponseEntity<String>(xmlString, headers, HttpStatus.OK);
}

From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java

@RequestMapping(value = "executor/execution/{executionId}/xslt/eMeasure.xsl", method = RequestMethod.GET)
public ResponseEntity<String> getMeasureXslt(@PathVariable String executionId) throws Exception {
    File xml = fileSystemResolver.getFiles(executionId).getInputQdmXml();

    String xmlString = IOUtils.toString(new ClassPathResource("/eMeasure.xsl").getInputStream(), "UTF-8");

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);

    return new ResponseEntity<String>(xmlString, headers, HttpStatus.OK);
}

From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java

/**
 * Gets the xml.//w  w w. j av a  2s  . c  o  m
 *
 * @param executionId the execution id
 * @return the xml
 * @throws Exception the exception
 */
@RequestMapping(value = "executor/execution/{executionId}/xml", method = RequestMethod.GET)
public ResponseEntity<String> getOutputXml(@PathVariable String executionId) throws Exception {
    File xml = fileSystemResolver.getFiles(executionId).getOuptutResultXml();

    String xmlString = FileUtils.readFileToString(xml, "UTF-8");

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);

    return new ResponseEntity<String>(xmlString, headers, HttpStatus.OK);
}

From source file:org.devefx.httpmapper.binding.MapperMethod.java

@SuppressWarnings("unchecked")
public Object execute(RestTemplate restTemplate, Object[] args) throws Exception {
    Object result = null;//from   w w w.j  a v a  2s  .c om

    do {
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(command.getContentType()));

        Map<String, Object> paramMap = null;
        Object param = method.convertArgsToCommandParam(args);
        if (param instanceof Map) {
            paramMap = (Map<String, Object>) param;
            body.setAll(paramMap);
        }

        URI uri = expandURI(command.getUrl(), args);

        RequestEntity requestEntity = new RequestEntity(body, headers, command.getHttpMethod(), uri,
                method.getReturnType());

        mappedHandler.onRequest(requestEntity);

        // FIXME: application/x-www-form-urlencoded
        if (headers.getContentType().includes(MediaType.APPLICATION_FORM_URLENCODED)) {
            if (paramMap != null) {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    Object value = entry.getValue();
                    if (value != null && !ReflectUtils.isUserType(value)) {
                        entry.setValue(String.valueOf(value));
                    }
                }
                body.setAll(paramMap);
            } else if (param != null && ReflectUtils.isUserType(param)) {
                body.setAll(mapper.<Map<String, Object>>convertValue(param, mapType));
            }
        }

        if (requestEntity.getMethod() == HttpMethod.GET) {
            uri = appendUrlParams(requestEntity.getUrl(), body);
            requestEntity.setUrl(uri);
        }

        if (logger.isInfoEnabled()) {
            String preStr = command.getName() + " ====> ";
            logger.info(preStr + "Request: " + requestEntity.getUrl());
            logger.info(preStr + "Parameters: " + requestEntity.getBody());
            logger.info(preStr + "Headers: " + requestEntity.getHeaders());
        }

        ResponseEntity<JsonNode> responseEntity = restTemplate.exchange(requestEntity.getUrl(),
                requestEntity.getMethod(),
                new HttpEntity<>(requestEntity.getBody(), requestEntity.getHeaders()), JsonNode.class);

        if (logger.isInfoEnabled()) {
            StringBuffer buf = new StringBuffer();
            buf.append(command.getName() + " ====> ");
            buf.append("Response: [status=").append(responseEntity.getStatusCode()).append("] ");
            if (responseEntity.hasBody()) {
                buf.append(responseEntity.getBody());
            }
            logger.info(buf.toString());
        }

        if (responseEntity != null) {
            org.devefx.httpmapper.http.ResponseEntity entity = new org.devefx.httpmapper.http.ResponseEntity(
                    responseEntity.getBody(), responseEntity.getHeaders(), responseEntity.getStatusCode());

            mappedHandler.onResponse(requestEntity, entity);

            if (entity.hasBody()) {
                Object responseBody = entity.getBody();
                if (method.getRawType().isInstance(responseBody)) {
                    result = responseBody;
                    break;
                }

                JavaType valueType = mapper.getTypeFactory().constructType(method.getReturnType());
                if (responseBody instanceof String) {
                    result = mapper.readValue((String) responseBody, valueType);
                } else {
                    result = mapper.convertValue(responseBody, valueType);
                }
            }
        }

    } while (false);

    if (result == null && method.returnsPrimitive() && !method.returnsVoid()) {
        throw new BindingException("Mapper method '" + command.getUrl()
                + " attempted to return null from a method with a primitive return type ("
                + method.getReturnType() + ").");
    }
    return result;
}