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.apigw.authserver.ServerRunning.java

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

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

public ResponseEntity<TokenResponseDTO> postForToken(String path, HttpHeaders headers,
        MultiValueMap<String, String> formData) {
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }//from w  w  w. ja  v  a 2s.  com

    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
            formData, headers);
    return client.exchange(getUrl(path), HttpMethod.POST, requestEntity, TokenResponseDTO.class);
}

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

@ApiMethod(path = "/services/albums/{albumSid}/cover", verb = ApiVerb.GET, description = "Get cover for a certain album", produces = {
        MediaType.IMAGE_JPEG_VALUE })//from w ww  .  java 2  s .  c o  m
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"),
        @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"),
        @ApiError(code = NotFoundMessicRESTException.VALUE, description = "Album or Cover not found"),
        @ApiError(code = IOMessicRESTException.VALUE, description = "IO internal server error"), })
@RequestMapping(value = "/{albumSid}/cover", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@ApiResponseObject
public ResponseEntity<byte[]> getAlbumCover(
        @PathVariable @ApiParam(name = "albumSid", description = "SID of the album to get the cover", paramType = ApiParamType.PATH, required = true) Long albumSid,
        @RequestParam(value = "preferredWidth", required = false) @ApiParam(name = "preferredWidth", description = "desired width for the image returned.  The service will try to provide the desired width, it is just only informative, to try to optimize the performance, avoiding to return images too much big", paramType = ApiParamType.QUERY, required = false, format = "Integer") Integer preferredWidth,
        @RequestParam(value = "preferredHeight", required = false) @ApiParam(name = "preferredHeight", description = "desired height for the image returned.  The service will try to provide the desired height, it is just only informative, to try to optimize the performance, avoiding to return images too much big", paramType = ApiParamType.QUERY, required = false, format = "Integer") Integer preferredHeight)
        throws UnknownMessicRESTException, NotAuthorizedMessicRESTException, NotFoundMessicRESTException,
        IOMessicRESTException {

    User user = SecurityUtil.getCurrentUser();
    try {
        byte[] content = albumAPI.getAlbumCover(user, albumSid, preferredWidth, preferredHeight);
        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) {
        InputStream is = AlbumController.class.getResourceAsStream("/org/messic/img/unknowncover.jpg");
        byte[] content = null;
        try {
            content = Util.readInputStream(is);
        } catch (IOException e1) {
            throw new NotFoundMessicRESTException(e);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.OK);
    } catch (IOException e) {
        throw new IOMessicRESTException(e);
    }
}

From source file:eu.supersede.gr.rest.GameRest.java

@RequestMapping("/{gameId}/exportGameResults")
public ResponseEntity<?> exportGameResults(@PathVariable Long gameId) {
    HAHPGame g = games.findOne(gameId);//from  w  w w .jav a  2s  . c  om

    if (g == null) {
        throw new NotFoundException();
    }

    StringBuilder result = new StringBuilder();

    result.append("REQUIREMENT").append(SEPARATOR).append("RESULT").append(NEW_LINE);
    List<HAHPCriteriasMatrixData> criteriasMatrixDataList = criteriasMatricesData.findByGame(g);
    Map<String, Double> rs = AHPRest.CalculateAHP(g.getCriterias(), g.getRequirements(),
            criteriasMatrixDataList, g.getRequirementsMatrixData());

    for (Entry<String, Double> e : rs.entrySet()) {
        result.append(requirements.getOne(new Long(e.getKey())).getName()).append(SEPARATOR)
                .append(e.getValue()).append(NEW_LINE);
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(new MediaType("text", "csv", Charset.forName("utf-8")));
    httpHeaders.setContentDispositionFormData("attachment", "dmp_" + g.getGameId() + "_results.csv");

    return new ResponseEntity<>(result.toString(), httpHeaders, HttpStatus.OK);
}

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

private String registerResourceSet(Principal p, String issuer, MultipartyServerConfiguration server,
        String accessTokenValue) {
    JsonObject requestJson = new JsonObject();
    /*//  w  w w.  j a  va2 s.c om
     rs.setId(getAsLong(o, "_id"));
    rs.setName(getAsString(o, "name"));
    rs.setIconUri(getAsString(o, "icon_uri"));
    rs.setType(getAsString(o, "type"));
    rs.setScopes(getAsStringSet(o, "scopes"));
    rs.setUri(getAsString(o, "uri"));
            
     */
    requestJson.addProperty("name", p.getName() + "'s Resources");
    JsonArray scopes = new JsonArray();
    scopes.add(new JsonPrimitive("read"));
    scopes.add(new JsonPrimitive("write"));
    requestJson.add("resource_set_scopes", scopes);

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

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

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

    JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
    String location = responseEntity.getHeaders().getLocation().toString();

    SharedResourceSet srs = new SharedResourceSet();
    srs.setIssuer(issuer);
    srs.setRsid(rso.get("_id").getAsString());
    srs.setUserAccessPolicyUri(rso.get("user_access_policy_uri").getAsString());
    srs.setLocation(location);

    resourceService.shareResourceForUser(srs, p);

    return "redirect:";
}

From source file:eu.supersede.gr.rest.GameRest.java

@RequestMapping("/{gameId}/exportGameData")
public ResponseEntity<?> exportGameData(@PathVariable Long gameId) {
    HAHPGame g = games.findOne(gameId);//from  ww w.  j ava  2  s  .  co m

    if (g == null) {
        throw new NotFoundException();
    }

    StringBuilder result = new StringBuilder();

    result.append("REQUIREMENT1").append(SEPARATOR).append("REQUIREMENT2").append(SEPARATOR).append("CRITERIA")
            .append(SEPARATOR).append("USER").append(SEPARATOR).append("VOTE").append(SEPARATOR)
            .append("VOTE_TIME").append(NEW_LINE);

    for (HAHPRequirementsMatrixData rmd : g.getRequirementsMatrixData()) {
        for (HAHPPlayerMove pm : rmd.getPlayerMoves()) {
            if (pm.getPlayed()) {
                result.append(rmd.getRowRequirement().getName()).append(SEPARATOR)
                        .append(rmd.getColumnRequirement().getName()).append(SEPARATOR)
                        .append(rmd.getCriteria().getName()).append(SEPARATOR).append(pm.getPlayer().getName())
                        .append(SEPARATOR).append(pm.getValue()).append(SEPARATOR);

                if (pm.getPlayedTime() == null) {
                    result.append(ZERO_TIME);
                } else {
                    result.append(dateFormat.format(pm.getPlayedTime()));
                }

                result.append(NEW_LINE);
            }
        }
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(new MediaType("text", "csv", Charset.forName("utf-8")));
    httpHeaders.setContentDispositionFormData("attachment", "dmp_" + g.getGameId() + "_data.csv");

    return new ResponseEntity<>(result.toString(), httpHeaders, HttpStatus.OK);
}

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

@RequestMapping(value = "/fetch", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_FORM_URLENCODED_VALUE)
public String fetch(@RequestParam("resource") String resource, Model m, HttpSession session) {

    // get the access token if we have one
    String accessTokenValue = acccessTokenService.getAccessToken(resource);

    // send our request to the resource

    HttpHeaders headers = new HttpHeaders();
    if (!Strings.isNullOrEmpty(accessTokenValue)) {
        headers.add("Authorization", "Bearer " + accessTokenValue);
    }/*from  w w w . j  a  va2  s  . c o m*/

    @SuppressWarnings("rawtypes")
    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(resource, 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 {
        // if we get back an error, try to get an access token
        List<String> authHeaders = responseEntity.getHeaders().get(HttpHeaders.WWW_AUTHENTICATE);
        // assume there's only one auth header for now
        String authHeader = Iterators.getOnlyElement(authHeaders.iterator());

        // parse the header to get the good bits
        String authServerUri = null;
        String ticket = null;
        Iterable<String> parts = Splitter.on(",").split(authHeader.substring("UMA ".length()));
        for (String part : parts) {
            List<String> subparts = Splitter.on("=").splitToList(part.trim());
            if (subparts.get(0).equals("as_uri")) {
                authServerUri = subparts.get(1);
                // strip quotes
                authServerUri = authServerUri.substring(1, authServerUri.length() - 1);
            } else if (subparts.get(0).equals("ticket")) {
                ticket = subparts.get(1);
                // strip quotes
                ticket = ticket.substring(1, ticket.length() - 1);
            }
        }

        // find the AS we need to talk to (maybe discover)
        MultipartyServerConfiguration server = serverConfig.getServerConfiguration(authServerUri);

        // 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, resource);
                session.setAttribute(AUTHSERVERURI_SESSION_VAR, authServerUri);

                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

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

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

            request = new HttpEntity<>(headers);

            responseEntity = restTemplate.exchange(resource, 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";
            }
        }

    }

}

From source file:gateway.controller.ServiceController.java

/**
 * Proxies an ElasticSearch DSL query to the Pz-Search component to return a
 * list of Service items.// w ww. j  av  a 2s .  c o m
 * 
 * @see http 
 *      ://pz-swagger.stage.geointservices.io/#!/Service/post_service_query
 * 
 * @return The list of Services matching the query.
 */
@RequestMapping(value = "/service/query", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Query Metadata in Piazza Services", notes = "Sends a complex query message to the Piazza Search component, that allow users to search for registered Services. Searching is capable of filtering by keywords, spatial metadata, or other dynamic information.", tags = {
        "Search", "Service" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "The list of Search results that match the query string.", response = ServiceListResponse.class),
        @ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = ErrorResponse.class),
        @ApiResponse(code = 500, message = "Internal Error", response = ErrorResponse.class) })
public ResponseEntity<PiazzaResponse> searchServices(
        @ApiParam(value = "The Query string for the Search component.", name = "search", required = true) @Valid @RequestBody SearchRequest query,
        @ApiParam(value = "Paginating large datasets. This will determine the starting page for the query.") @RequestParam(value = "page", required = false, defaultValue = DEFAULT_PAGE) Integer page,
        @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "perPage", required = false, defaultValue = DEFAULT_PAGE_SIZE) Integer perPage,
        @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false, defaultValue = DEFAULT_ORDER) String order,
        @ApiParam(value = "The data field to sort by.") @RequestParam(value = "sortBy", required = false, defaultValue = DEFAULT_SERVICE_SORTBY) String sortBy,
        Principal user) {
    try {
        // Log the request
        logger.log(String.format("User %s sending a complex query for Search Services.",
                gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO);
        // Send the query to the Pz-Search component
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<Object>(query, headers);
        ServiceListResponse searchResponse = restTemplate
                .postForObject(
                        String.format("%s/%s?page=%s&perPage=%s&order=%s&sortBy=%s", SEARCH_URL,
                                SEARCH_ENDPOINT, page, perPage, order, sortBy),
                        entity, ServiceListResponse.class);
        // Respond
        return new ResponseEntity<PiazzaResponse>(searchResponse, HttpStatus.OK);
    } catch (Exception exception) {
        String error = String.format("Error Querying Services by user %s: %s",
                gatewayUtil.getPrincipalName(user), exception.getMessage());
        LOGGER.error(error, exception);
        logger.log(error, PiazzaLogger.ERROR);
        return new ResponseEntity<PiazzaResponse>(new ErrorResponse(error, "Gateway"),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:business.services.RequestService.java

public HttpEntity<InputStreamResource> writeRequestListCsv(List<RequestRepresentation> requests) {
    try {/*  ww  w. j a v a 2s  .  c  o  m*/
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out, CSV_CHARACTER_ENCODING);
        CSVWriter csvwriter = new CSVWriter(writer, ';', '"');
        csvwriter.writeNext(CSV_COLUMN_NAMES);

        for (RequestRepresentation request : requests) {
            List<String> values = new ArrayList<>();
            values.add(request.getRequestNumber());
            values.add(DATE_FORMATTER.print(request.getDateCreated(), LOCALE));
            values.add(request.getTitle());
            values.add(request.getStatus().toString());
            values.add(booleanToString(request.isLinkageWithPersonalData()));
            values.add(request.getLinkageWithPersonalDataNotes());
            values.add(booleanToString(request.isStatisticsRequest()));
            values.add(booleanToString(request.isExcerptsRequest()));
            values.add(booleanToString(request.isPaReportRequest()));
            values.add(booleanToString(request.isMaterialsRequest()));
            values.add(booleanToString(request.isClinicalDataRequest()));
            values.add(request.getRequesterName());
            values.add(request.getLab() == null ? "" : request.getLab().getNumber().toString());
            values.add(request.getRequester() == null ? "" : request.getRequester().getSpecialism());
            values.add(labRequestService.countHubAssistanceLabRequestsForRequest(request.getProcessInstanceId())
                    .toString());
            values.add(request.getPathologistName());
            csvwriter.writeNext(values.toArray(new String[] {}));
        }
        csvwriter.flush();
        writer.flush();
        out.flush();
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        csvwriter.close();
        writer.close();
        out.close();
        InputStreamResource resource = new InputStreamResource(in);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("text/csv"));
        String filename = "requests_" + DATE_FORMATTER.print(new Date(), LOCALE) + ".csv";
        headers.set("Content-Disposition", "attachment; filename=" + filename);
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        log.info("Returning reponse.");
        return response;
    } catch (IOException e) {
        log.error(e.getStackTrace());
        log.error(e.getMessage());
        throw new FileDownloadError();
    }

}