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.boundlessgeo.geoserver.api.controllers.IconController.java

@RequestMapping(value = "/{wsName}/{icon:.+}", method = RequestMethod.GET)
public HttpEntity raw(@PathVariable String wsName, @PathVariable String icon) throws IOException {

    WorkspaceInfo ws;//  ww  w .j a v a 2s . c  o m
    Resource resource;

    if (wsName == null) {
        ws = null;
        resource = dataDir().getRoot("styles", icon);
    } else {
        ws = findWorkspace(wsName, catalog());
        resource = dataDir().get(ws, "styles", icon);
    }

    if (resource.getType() != Type.RESOURCE) {
        throw new NotFoundException("Icon " + icon + " not found");
    }
    String ext = fileExt(icon);
    if (!ICON_FORMATS.containsKey(ext)) {
        throw new NotFoundException("Icon " + icon + " format unsupported");
    }
    String mimeType = ICON_FORMATS.get(ext.toLowerCase());

    try (InputStream in = resource.in();) {
        byte[] bytes = IOUtils.toByteArray(in);
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(mimeType));
        headers.setLastModified(resource.lastmodified());
        return new HttpEntity(bytes, headers);
    }
}

From source file:org.opentides.rest.impl.BaseCrudRestServiceImpl.java

/**
 * Make sure RestTemplate is properly set.
 *///from   w w  w . j  av  a 2 s  .co  m
@SuppressWarnings("unchecked")
@PostConstruct
public final void afterPropertiesSet() throws Exception {
    try {
        this.entityBeanType = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    } catch (ClassCastException cc) {
        // if dao is extended from the generic dao class
        this.entityBeanType = (Class<T>) ((ParameterizedType) getClass().getSuperclass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }

    // setup entity(headers) for basic authentication.
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    this.entity = new HttpEntity<String>(headers);

    // setup the rest template
    if (restTemplate == null) {
        restTemplate = new RestTemplate();
    }

    Assert.notNull(this.entityBeanType,
            "Unable to retrieve entityBeanType for " + this.getClass().getSimpleName());

}

From source file:com.athena.dolly.controller.module.couchbase.CouchbaseClient.java

/**
 * <pre>//ww  w.j av a 2 s.c o  m
 * HTTP Header? ??  ?.
 * </pre>
 * @return
 */
private HttpEntity<Object> setHTTPEntity(String body) {
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    acceptableMediaTypes.add(MediaType.APPLICATION_JSON);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.setAccept(acceptableMediaTypes);

    if (getCredential() != null) {
        requestHeaders.set(AUTH_HEADER_KEY, getCredential());
    }

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

From source file:org.cbioportal.session_service.SessionServiceTest.java

private HttpEntity<String> prepareData(String data) throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    if (data != null) {
        data = "{" + data + "}";
    }//from w w w . j  a v  a 2  s .  c  om
    return new HttpEntity<String>(data, headers);
}

From source file:org.mitreid.multiparty.web.ResourceController.java

/**
 * @param oldSharedResourceSet/*from w  w w.j  a  va 2 s. co  m*/
 * @param accessTokenValue
 */
private void unregisterOldResourceSet(SharedResourceSet oldSharedResourceSet, String accessTokenValue,
        Principal p) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + accessTokenValue);

    HttpEntity<String> request = new HttpEntity<>(headers);

    restTemplate.exchange(oldSharedResourceSet.getLocation(), HttpMethod.DELETE, request, String.class);

    resourceService.unshareResourceSet(p);
}

From source file:org.venice.piazza.servicecontroller.controller.ServiceController.java

/**
 * Healthcheck to see if the Piazza Service Controller is up and running. This service is meant for internal Piazza
 * use, Swiss-Army-Knife (SAK) administration and for testing of the serviceController.
 * /* www .j  a va2  s  .c o  m*/
 * @return welcome message
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public ResponseEntity<String> healthCheck() {
    logger.log("Health Check called", Severity.DEBUG);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.valueOf("text/html"));
    String htmlMessage = "<HTML><TITLE>Piazza Service Controller Welcome</TITLE>";
    htmlMessage = htmlMessage + "<BODY><BR> Welcome from the Piazza Service Controller. "
            + "<BR>For details on running and using the ServiceController, "
            + "<BR>see The Piazza Developer's Guide<A> for details." + "<BODY></HTML>";
    ResponseEntity<String> response = new ResponseEntity<String>(htmlMessage, responseHeaders, HttpStatus.OK);

    return response;
}

From source file:org.mitreid.multiparty.web.ResourceController.java

/**
 * @param incomingAccessToken//from   w  ww.j av  a  2  s .  c o  m
 * @param server
 * @param client
 * @param protectionAccessTokenValue
 * @return
 */
private JsonObject introspectToken(String incomingAccessToken, MultipartyServerConfiguration server,
        RegisteredClient client, String protectionAccessTokenValue) {

    // POST to the introspection endpoint and get the results

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("token", incomingAccessToken);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add("Authorization", "Bearer " + protectionAccessTokenValue);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

    HttpEntity<String> responseEntity = restTemplate.postForEntity(server.getIntrospectionEndpointUri(),
            request, String.class);

    JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();

    return rso;
}

From source file:org.messic.server.facade.controllers.rest.AlbumController.java

@ApiMethod(path = "/services/albums/{resourceSid}/resource", verb = ApiVerb.GET, description = "Get a resource of an album", produces = {
        MediaType.APPLICATION_OCTET_STREAM_VALUE })
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"),
        @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"),
        @ApiError(code = NotFoundMessicRESTException.VALUE, description = "Resource not found"),
        @ApiError(code = IOMessicRESTException.VALUE, description = "IO internal server error"), })
@RequestMapping(value = "/{resourceSid}/resource", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)/*from  www . j av  a2s.  c o m*/
@ResponseBody
@ApiResponseObject
public ResponseEntity<byte[]> getAlbumResource(
        @PathVariable @ApiParam(name = "resourceSid", description = "SID of the resource to get", paramType = ApiParamType.PATH, required = true) Long resourceSid)
        throws UnknownMessicRESTException, NotAuthorizedMessicRESTException, NotFoundMessicRESTException,
        IOMessicRESTException {

    User user = SecurityUtil.getCurrentUser();
    try {
        byte[] content = albumAPI.getAlbumResource(user, resourceSid);
        if (content == null || content.length == 0) {
            InputStream is = AlbumController.class.getResourceAsStream("/org/messic/img/unknowncover.jpg");
            content = Util.readInputStream(is);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.OK);
    } catch (SidNotFoundMessicException e) {
        throw new NotFoundMessicRESTException(e);
    } catch (ResourceNotFoundMessicException e) {
        throw new NotFoundMessicRESTException(e);
    } catch (IOException e) {
        throw new IOMessicRESTException(e);
    }
}

From source file:org.mitreid.multiparty.web.ResourceController.java

/**
 * @param resourceSet/*from   w  w w .  ja v a 2s .  c om*/
 * @param protectionAccessTokenValue 
 * @param client 
 * @param server 
 * @return
 */
private String getTicket(SharedResourceSet resourceSet, MultipartyServerConfiguration server,
        RegisteredClient client, String protectionAccessTokenValue) {

    JsonObject requestJson = new JsonObject();
    requestJson.addProperty("resource_set_id", resourceSet.getRsid());
    JsonArray scopes = new JsonArray();
    requestJson.add("resource_set_scopes", scopes);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + protectionAccessTokenValue);

    HttpEntity<String> request = new HttpEntity<String>(requestJson.toString(), headers);

    HttpEntity<String> responseEntity = restTemplate.postForEntity(server.getPermissionRegistrationEndpoint(),
            request, String.class);

    JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();

    String ticket = rso.get("ticket").getAsString();

    return ticket;
}

From source file:org.mitreid.multiparty.web.ClientController.java

@RequestMapping(value = "claims_submitted")
public String claimsSubmissionCallback(@RequestParam("authorization_state") String authorizationState,
        @RequestParam("state") String returnState, @RequestParam("ticket") String ticket, HttpSession session,
        Model m) {//  w w w . j a  v  a  2 s .co  m

    // get our saved information out of the session
    String savedState = (String) session.getAttribute(STATE_SESSION_VAR);
    String savedResource = (String) session.getAttribute(RESOURCE_SESSION_VAR);
    String savedAuthServerUri = (String) session.getAttribute(AUTHSERVERURI_SESSION_VAR);

    // make sure the state matches
    if (Strings.isNullOrEmpty(returnState) || !returnState.equals(savedState)) {
        // it's an error if it doesn't
        logger.error("Unable to match states");
        return "home";
    }

    if (authorizationState.equals("claims_submitted")) {
        // claims have been submitted, let's go try to get a token again
        // find the AS we need to talk to (maybe discover)
        MultipartyServerConfiguration server = serverConfig.getServerConfiguration(savedAuthServerUri);

        // find the client configuration (maybe register)
        RegisteredClient client = clientConfig.getClientConfiguration(server);

        HttpHeaders tokenHeaders = new HttpHeaders();
        tokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // send request to the token endpoint
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();

        params.add("client_id", client.getClientId());
        params.add("client_secret", client.getClientSecret());
        params.add("grant_type", "urn:ietf:params:oauth:grant_type:multiparty-delegation");
        params.add("ticket", ticket);
        //params.add("scope", "read write");

        HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(params, tokenHeaders);

        ResponseEntity<String> tokenResponse = restTemplate.postForEntity(server.getTokenEndpointUri(),
                tokenRequest, String.class);
        JsonObject o = parser.parse(tokenResponse.getBody()).getAsJsonObject();

        if (o.has("error")) {
            if (o.get("error").getAsString().equals("need_info")) {
                // if we get need info, redirect

                JsonObject details = o.get("error_details").getAsJsonObject();

                // this is the URL to send the user to
                String claimsEndpoint = details.get("requesting_party_claims_endpoint").getAsString();
                String newTicket = details.get("ticket").getAsString();

                // set a state value for our return
                String state = UUID.randomUUID().toString();
                session.setAttribute(STATE_SESSION_VAR, state);

                // save bits about the request we were trying to make
                session.setAttribute(RESOURCE_SESSION_VAR, savedResource);
                session.setAttribute(AUTHSERVERURI_SESSION_VAR, savedAuthServerUri);

                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(claimsEndpoint)
                        .queryParam("client_id", client.getClientId()).queryParam("ticket", newTicket)
                        .queryParam("claims_redirect_uri", client.getClaimsRedirectUris().iterator().next()) // get the first one and punt
                        .queryParam("state", state);

                return "redirect:" + builder.build();
            } else {
                // it's an error we don't know how to deal with, give up
                logger.error("Unknown error from token endpoint: " + o.get("error").getAsString());
                return "home";
            }
        } else {
            // if we get an access token, try it again

            String accessTokenValue = o.get("access_token").getAsString();
            acccessTokenService.saveAccesstoken(savedResource, accessTokenValue);

            HttpHeaders headers = new HttpHeaders();
            if (!Strings.isNullOrEmpty(accessTokenValue)) {
                headers.add("Authorization", "Bearer " + accessTokenValue);
            }

            HttpEntity<Object> request = new HttpEntity<>(headers);

            ResponseEntity<String> responseEntity = restTemplate.exchange(savedResource, HttpMethod.GET,
                    request, String.class);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                // if we get back data, display it
                JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
                m.addAttribute("label", rso.get("label").getAsString());
                m.addAttribute("value", rso.get("value").getAsString());
                return "home";
            } else {
                logger.error("Unable to get a token");
                return "home";
            }
        }
    } else {
        logger.error("Unknown response from claims endpoing: " + authorizationState);
        return "home";
    }

}