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:org.cloudfoundry.identity.api.web.ServerRunning.java

public ResponseEntity<String> postForString(String path, MultiValueMap<String, String> formData,
        HttpHeaders headers) {//from  w ww.  j  av a 2  s  . c  om
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }
    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(formData, headers), String.class);
}

From source file:org.cloudfoundry.identity.api.web.ServerRunning.java

@SuppressWarnings("rawtypes")
public ResponseEntity<Map> postForMap(String path, MultiValueMap<String, String> formData,
        HttpHeaders headers) {//from  w  w  w. j  a va 2  s.  c o m
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }
    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class);
}

From source file:org.cloudfoundry.identity.batch.integration.ServerRunning.java

public ResponseEntity<Void> postForResponse(String path, HttpHeaders headers,
        MultiValueMap<String, String> params) {
    HttpHeaders actualHeaders = new HttpHeaders();
    actualHeaders.putAll(headers);// w  w w . ja  v  a2s. c  o m
    actualHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(params, actualHeaders), null);
}

From source file:org.shaf.server.controller.CmdActionController.java

/**
 * Gets data from the server.//w  w  w. ja va  2s. com
 * 
 * @param storage
 *            the resource type.
 * @param alias
 *            the data alias.
 * @return the entity for downloading data.
 * @throws Exception
 *             if an error occurs.
 */
@RequestMapping(value = "/download/{storage}/{alias}", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<InputStreamResource> onDownload(@PathVariable String storage,
        @PathVariable String alias) throws Exception {
    LOG.debug("CALL service: /cmd/download/{" + storage + "}/{" + alias + "}");

    Firewall firewall = super.getFirewall();
    String username = super.getUserName();
    StorageDriver driver = OPER.getStorageDriver(firewall, username, StorageType.CONSUMER, storage);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    header.setContentLength(driver.getLength(alias));
    header.setContentDispositionFormData("attachment", alias);

    return new ResponseEntity<InputStreamResource>(new InputStreamResource(driver.getInputStream(alias)),
            header, HttpStatus.OK);
}

From source file:io.github.microcks.web.RestController.java

@RequestMapping(value = "/{service}/{version}/**")
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay,
        @RequestBody(required = false) String body, HttpServletRequest request) {

    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version,
            request.getRequestURI(), request.getMethod());
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;//from   w  w  w .  j a v a 2s.c  om

    try {
        // Build the encoded URI fragment to retrieve simple resourcePath.
        serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
        resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    } catch (UnsupportedEncodingException e1) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    log.info("Found resourcePath: " + resourcePath);

    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(),
                rOperation.getDispatcherRules());

        Response response = null;
        String uriPattern = getURIPattern(rOperation.getName());
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            ScriptEngineManager sem = new ScriptEngineManager();
            try {
                // Evaluating request with script coming from operation dispatcher rules.
                ScriptEngine se = sem.getEngineByExtension("groovy");
                SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
                dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules());
            } catch (Exception e) {
                log.error("Error during Script evaluation", e);
            }
        }
        // New cases related to services/operations/messages coming from a postman collection file.
        else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) {
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        if (response != null) {
            // Setting delay to default one if not set.
            if (delay == null && rOperation.getDefaultDelay() != null) {
                delay = rOperation.getDefaultDelay();
            }

            if (delay != null && delay > -1) {
                log.debug("Mock delay is turned on, waiting if necessary...");
                long duration = System.currentTimeMillis() - startTime;
                if (duration < delay) {
                    Object semaphore = new Object();
                    synchronized (semaphore) {
                        try {
                            semaphore.wait(delay - duration);
                        } catch (Exception e) {
                            log.debug("Delay semaphore was interrupted");
                        }
                    }
                }
                log.debug("Delay now expired, releasing response !");
            }

            // Publish an invocation event before returning.
            MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                    response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
            applicationContext.publishEvent(event);
            log.debug("Mock invocation event has been published");

            HttpStatus status = (response.getStatus() != null
                    ? HttpStatus.valueOf(Integer.parseInt(response.getStatus()))
                    : HttpStatus.OK);

            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }

            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = "http://" + request.getServerName() + ":" + request.getServerPort()
                                + request.getContextPath() + "/rest" + serviceAndVersion
                                + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            return new ResponseEntity<Object>(response.getContent(), responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

From source file:org.apigw.authserver.ServerRunning.java

public ResponseEntity<Void> postForStatus(String path, HttpHeaders headers,
        MultiValueMap<String, String> formData) {
    HttpHeaders actualHeaders = new HttpHeaders();
    actualHeaders.putAll(headers);/*from   w ww  . jav  a  2s .  c o m*/
    actualHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(formData, actualHeaders), Void.class);
}

From source file:cz.cvut.via.androidrestskeleton.SkeletonActivity.java

/** Called with the activity is first created. */
@Override/*from w  w w  . j av  a2s . c  o m*/
public void onCreate(Bundle savedInstanceState) {

    // DISABLE policy not allowing network connections from main application thread
    // these calls normally HAVE to be done from worker threads/asynchronous threads/services ..
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    super.onCreate(savedInstanceState);

    // Inflate our UI from its XML layout description.
    setContentView(R.layout.skeleton_activity);

    requestView = (CheckedTextView) findViewById(R.id.checkedTextRequest);
    responseView = (CheckedTextView) findViewById(R.id.checkedTextResponse);

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.create)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            PostalAddress address = new PostalAddress();
            address.setCity("new city");
            address.setCountry("new country");
            address.setStreet("new street");
            address.setZipCode("zipcode");

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/";

            new AsyncPOST<PostalAddress>(requestEntity) {
                protected void onPostExecute(Response<String> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n"
                            + request.getBody().toJSONString());
                    responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                            + result.getResponseEntity().getHeaders().toString());
                    lastCreatedLocation = result.getResponseEntity().getHeaders().getLocation().getPath();
                };
            }.execute(url);
        }
    });

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.list)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            RestTemplate restTemplate = new RestTemplate();

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/";

            new AsyncGET<PostalAddress[]>(requestEntity, PostalAddress[].class) {
                protected void onPostExecute(Response<PostalAddress[]> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        StringBuilder text = new StringBuilder();
                        for (PostalAddress address : result.getResponseEntity().getBody()) {
                            text.append(address.toJSONString() + "\n\n");
                        }
                        //+ requestEntity.getBody().toJSONString());
                        responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                                + result.getResponseEntity().getHeaders().toString() + "\n\n" + text);
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.update)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            PostalAddress address = new PostalAddress();
            address.setCity("updated city");
            address.setCountry("new country");
            address.setStreet("new street");
            address.setZipCode("zipcode");

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation;

            new AsyncPUT<PostalAddress>(requestEntity) {
                protected void onPostExecute(Response<Object> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n"
                            + request.getBody().toJSONString());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        responseView.setText("PUT method in Spring does not support return values..");
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.delete)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation;

            // get reponse
            new AsyncDELETE() {
                protected void onPostExecute(Response<Object> result) {
                    requestView.setText(url);

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        responseView.setText("PUT method in Spring does not support return values..");
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.query)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            HashMap<String, String> query = new HashMap<String, String>();
            query.put("setFilter", "street == streetParam");
            query.put("declareParameters", "String streetParam");
            query.put("setOrdering", "street desc");

            HashMap<String, String> parameters = new HashMap<String, String>();
            parameters.put("streetParam", "new street");

            RESTQuery q = new RESTQuery();
            q.setQuery(query);
            q.setParameters(parameters);

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<RESTQuery> requestEntity = new HttpEntity<RESTQuery>(q, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/q";

            // get reponse
            new AsyncPOST_QUERY<RESTQuery, PostalAddress[]>(requestEntity, PostalAddress[].class) {
                @Override
                protected void onPostExecute(Response<PostalAddress[]> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {

                        StringBuilder text = new StringBuilder();
                        for (PostalAddress address : result.getResponseEntity().getBody()) {
                            text.append(address.toJSONString() + "\n\n");
                        }

                        responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                                + result.getResponseEntity().getHeaders().toString() + "\n\n" + text);
                    }
                }
            }.execute(url);
        }
    });

}

From source file:de.hska.ld.core.AbstractIntegrationTest.java

private HttpEntity<String> createHeaderAndBody(Object obj, Cookie auth) {
    String json = null;//from   w  w w .  j a va 2s .c om
    if (obj != null) {
        try {
            json = objectMapper.writeValueAsString(obj);
            /*if (obj instanceof User) {
            // Workaround to transfer password
            json = json.substring(0, json.length() - 1);
            json += ",\"password\":\"" + PASSWORD + "\"}";
            }*/
        } catch (JsonProcessingException e) {
            // do nothing
        }
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    if (auth != null) {
        headers.add("Cookie", "JSESSIONID=" + auth.getValue());
    }

    if (json == null) {
        return new HttpEntity<>(headers);
    } else {
        return new HttpEntity<>(json, headers);
    }
}

From source file:org.mitre.openid.connect.web.ClientAPI.java

/**
 * Get the logo image for a client//from   w  ww  .j a v a 2  s .c  o m
 * @param id
 */
@RequestMapping(value = "/{id}/logo", method = RequestMethod.GET, produces = { MediaType.IMAGE_GIF_VALUE,
        MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE })
public ResponseEntity<byte[]> getClientLogo(@PathVariable("id") Long id, Model model) {

    ClientDetailsEntity client = clientService.getClientById(id);

    if (client == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else if (Strings.isNullOrEmpty(client.getLogoUri())) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else {
        // get the image from cache
        CachedImage image = clientLogoLoadingService.getLogo(client);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(image.getContentType()));
        headers.setContentLength(image.getLength());

        return new ResponseEntity<>(image.getData(), headers, HttpStatus.OK);
    }
}