Example usage for org.springframework.http HttpHeaders setAccept

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

Introduction

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

Prototype

public void setAccept(List<MediaType> acceptableMediaTypes) 

Source Link

Document

Set the list of acceptable MediaType media types , as specified by the Accept header.

Usage

From source file:org.cloudfoundry.identity.uaa.login.SamlRemoteUaaController.java

@RequestMapping(value = "/oauth/token", method = RequestMethod.POST, params = "grant_type=password")
@ResponseBody/*w w  w.  ja va 2 s  .  c o m*/
public ResponseEntity<byte[]> tokenEndpoint(HttpServletRequest request, HttpEntity<byte[]> entity,
        @RequestParam Map<String, String> parameters, Map<String, Object> model, Principal principal)
        throws Exception {

    // Request has a password. Owner password grant with a UAA password
    if (null != request.getParameter("password")) {
        return passthru(request, entity, model);
    } else {
        //
        MultiValueMap<String, String> requestHeadersForClientInfo = new LinkedMultiValueMap<String, String>();
        requestHeadersForClientInfo.add(AUTHORIZATION, request.getHeader(AUTHORIZATION));

        ResponseEntity<byte[]> clientInfoResponse = getDefaultTemplate().exchange(
                getUaaBaseUrl() + "/clientinfo", HttpMethod.POST,
                new HttpEntity<MultiValueMap<String, String>>(null, requestHeadersForClientInfo), byte[].class);

        if (clientInfoResponse.getStatusCode() == HttpStatus.OK) {
            String path = extractPath(request);

            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.setAll(parameters);
            if (principal != null) {
                map.set("source", "login");
                map.set("client_id", getClientId(clientInfoResponse.getBody()));
                map.setAll(getLoginCredentials(principal));
                map.remove("credentials"); // legacy vmc might break otherwise
            } else {
                throw new BadCredentialsException("No principal found in authorize endpoint");
            }

            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.putAll(getRequestHeaders(requestHeaders));
            requestHeaders.remove(AUTHORIZATION.toLowerCase());
            requestHeaders.remove(ACCEPT.toLowerCase());
            requestHeaders.remove(CONTENT_TYPE.toLowerCase());
            requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            requestHeaders.remove(COOKIE);
            requestHeaders.remove(COOKIE.toLowerCase());

            ResponseEntity<byte[]> response = getAuthorizationTemplate().exchange(getUaaBaseUrl() + "/" + path,
                    HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(map, requestHeaders),
                    byte[].class);

            saveCookie(response.getHeaders(), model);

            byte[] body = response.getBody();
            if (body != null) {
                HttpHeaders outgoingHeaders = getResponseHeaders(response.getHeaders());
                return new ResponseEntity<byte[]>(response.getBody(), outgoingHeaders,
                        response.getStatusCode());
            }

            throw new IllegalStateException("Neither a redirect nor a user approval");
        } else {
            throw new BadCredentialsException(new String(clientInfoResponse.getBody()));
        }
    }
}

From source file:ru.anr.base.facade.web.api.RestClient.java

/**
 * Applying for default headers//w w  w  .j  a  v a 2 s  . c  o  m
 * 
 * @return {@link HttpHeaders} object
 */
protected HttpHeaders applyHeaders() {

    HttpHeaders hh = new HttpHeaders();
    if (contentType != null) {
        hh.setContentType(contentType);
    }
    if (accept != null) {
        hh.setAccept(list(accept));
        hh.setAcceptCharset(list(Charset.forName("utf-8")));
    }

    if (basicCredentials != null) {
        hh.add("Authorization", basicCredentials);
    }

    return hh;
}

From source file:com.orange.ngsi2.client.Ngsi2Client.java

/**
 * Retrieve the attribute of an entity//ww w . ja v a 2  s.c  om
 * @param entityId the entity ID
 * @param type optional entity type to avoid ambiguity when multiple entities have the same ID, null or zero-length for empty
 * @param attributeName the attribute name
 * @return
 */
public ListenableFuture<String> getAttributeValueAsString(String entityId, String type, String attributeName) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}/attrs/{attributeName}/value");
    addParam(builder, "type", type);
    HttpHeaders httpHeaders = cloneHttpHeaders();
    httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_PLAIN));
    return adapt(request(HttpMethod.GET, builder.buildAndExpand(entityId, attributeName).toUriString(),
            httpHeaders, null, String.class));
}

From source file:org.cloudfoundry.identity.uaa.api.common.impl.UaaConnectionHelper.java

/**
 * Add the Authorization, Content-Type, and Accept headers to the request
 * /*from www.j a va  2s .co m*/
 * @param headers
 */
private void getHeaders(HttpHeaders headers) {
    OAuth2AccessToken token = getAccessToken();
    headers.add("Authorization", token.getTokenType() + " " + token.getValue());

    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_JSON);
    }

    if (headers.getAccept() == null || headers.getAccept().size() == 0) {
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    }
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

public void send(final Context context) {
    final StringHttpMessageConverter stringHttpMessageConverter;

    try {/* www.j  av a 2  s.  co m*/
        /**
        * Charset.availableCharsets() called by StringHttpMessageConverter constructor is not multi-thread safe.
        * Calling it on the main thread to avoid a possible crash.
        * More details here: https://code.google.com/p/android/issues/detail?id=42769
        */
        stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName(UTF8));
    } catch (Exception e) {
        handleResponse(new PlayHavenException(e.getMessage()));
        return;
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                /**
                 * First, check if we are mocking the URL
                 */
                String mockJsonResponse = getMockJsonResponse();
                if (mockJsonResponse != null) {
                    /**
                     * Mock the response
                     */
                    PlayHaven.v("Mock Response: %s", mockJsonResponse);
                    handleResponse(mockJsonResponse);
                    return;
                }

                /**
                 * Not mocking the response. Do an actual server call.
                 */
                String url = getUrl(context);
                PlayHaven.v("Request(%s) %s: %s", PlayHavenRequest.this.getClass().getSimpleName(), restMethod,
                        url);

                // Add the gzip Accept-Encoding header
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setAcceptEncoding(ContentCodingType.GZIP);
                requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));

                // Create our REST handler
                RestTemplate rest = new RestTemplate();
                rest.setErrorHandler(new ServerErrorHandler());

                // Capture the JSON for signature verification
                rest.getMessageConverters().add(stringHttpMessageConverter);

                ResponseEntity<String> entity = null;

                switch (restMethod) {
                case POST:
                    SharedPreferences pref = PlayHaven.getPreferences(context);
                    String apiServer = getString(pref, APIServer)
                            + context.getResources().getString(getApiPath(context));
                    url = url.replace(apiServer, "");
                    if (url.startsWith("?") && url.length() > 1)
                        url = url.substring(1);

                    requestHeaders.setContentType(new MediaType("application", "x-www-form-urlencoded"));
                    entity = rest.exchange(apiServer, restMethod, new HttpEntity<>(url, requestHeaders),
                            String.class);
                    break;
                default:
                    entity = rest.exchange(url, restMethod, new HttpEntity<>(requestHeaders), String.class);
                    break;
                }

                String json = entity.getBody();

                List<String> digests = entity.getHeaders().get("X-PH-DIGEST");
                String digest = (digests == null || digests.size() == 0) ? null : digests.get(0);

                validateSignatures(context, digest, json);

                HttpStatus statusCode = entity.getStatusCode();
                PlayHaven.v("Response (%s): %s", statusCode, json);

                serverSuccess(context);
                handleResponse(json);
            } catch (PlayHavenException e) {
                handleResponse(e);
            } catch (IOException e2) {
                handleResponse(new PlayHavenException(e2));
            } catch (Exception e3) {
                handleResponse(new PlayHavenException(e3.getMessage()));
            }
        }
    }).start();
}

From source file:com.javafxpert.wikibrowser.WikiVisGraphController.java

/**
 * Calls the Neo4j Transactional Cypher service and returns an object that holds results
 * @param neoCypherUrl/*from  w w w.jav a 2 s. com*/
 * @param postString
 * @return
 */
private VisGraphResponseNear queryProcessSearchResponse(String neoCypherUrl, String postString) {
    log.info("neoCypherUrl: " + neoCypherUrl);
    log.info("postString: " + postString);

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders httpHeaders = WikiBrowserUtils.createHeaders(wikiBrowserProperties.getCypherUsername(),
            wikiBrowserProperties.getCypherPassword());

    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    HttpEntity request = new HttpEntity(postString, httpHeaders);

    GraphResponseFar graphResponseFar = null;
    VisGraphResponseNear visGraphResponseNear = new VisGraphResponseNear();
    try {
        ResponseEntity<GraphResponseFar> result = restTemplate.exchange(neoCypherUrl, HttpMethod.POST, request,
                GraphResponseFar.class);
        graphResponseFar = result.getBody();
        log.info("graphResponseFar: " + graphResponseFar);

        // Populate VisGraphResponseNear instance from GraphResponseFar instance
        HashMap<String, VisGraphNodeNear> visGraphNodeNearMap = new HashMap<>();
        HashMap<String, VisGraphEdgeNear> visGraphEdgeNearMap = new HashMap<>();

        List<ResultFar> resultFarList = graphResponseFar.getResultFarList();
        if (resultFarList.size() > 0) {
            List<DataFar> dataFarList = resultFarList.get(0).getDataFarList();
            Iterator<DataFar> dataFarIterator = dataFarList.iterator();

            while (dataFarIterator.hasNext()) {
                GraphFar graphFar = dataFarIterator.next().getGraphFar();

                List<GraphNodeFar> graphNodeFarList = graphFar.getGraphNodeFarList();
                Iterator<GraphNodeFar> graphNodeFarIterator = graphNodeFarList.iterator();

                while (graphNodeFarIterator.hasNext()) {
                    GraphNodeFar graphNodeFar = graphNodeFarIterator.next();
                    VisGraphNodeNear visGraphNodeNear = new VisGraphNodeNear();

                    //visGraphNodeNear.setDbId(graphNodeFar.getId());  // Database ID for this node
                    visGraphNodeNear.setDbId(graphNodeFar.getGraphNodePropsFar().getItemId().substring(1));

                    visGraphNodeNear.setTitle(graphNodeFar.getGraphNodePropsFar().getTitle());
                    visGraphNodeNear.setLabelsList(graphNodeFar.getLabelsList());
                    visGraphNodeNear.setItemId(graphNodeFar.getGraphNodePropsFar().getItemId());

                    String itemId = visGraphNodeNear.getItemId();
                    String articleTitle = visGraphNodeNear.getTitle();

                    // Retrieve the article's image
                    String thumbnailUrl = null;

                    String articleLang = "en";
                    // TODO: Add a language property to Item nodes stored in Neo4j that aren't currently in English,
                    //       and use that property to mutate articleTitleLang

                    // First, try to get the thumbnail by ID from cache
                    thumbnailUrl = ThumbnailCache.getThumbnailUrlById(itemId, articleLang);

                    if (thumbnailUrl == null) {
                        // If not available, try to get thumbnail by ID from ThumbnailService
                        try {
                            String thumbnailByIdUrl = this.wikiBrowserProperties
                                    .getThumbnailByIdServiceUrl(itemId, articleLang);
                            thumbnailUrl = new RestTemplate().getForObject(thumbnailByIdUrl, String.class);

                            if (thumbnailUrl != null) {
                                visGraphNodeNear.setImageUrl(thumbnailUrl);
                            } else {
                                // If thumbnail isn't available by ID, try to get thumbnail by article title
                                try {
                                    String thumbnailByTitleUrl = this.wikiBrowserProperties
                                            .getThumbnailByTitleServiceUrl(articleTitle, articleLang);
                                    thumbnailUrl = new RestTemplate().getForObject(thumbnailByTitleUrl,
                                            String.class);

                                    if (thumbnailUrl != null) {
                                        visGraphNodeNear.setImageUrl(thumbnailUrl);
                                    } else {
                                        visGraphNodeNear.setImageUrl("");
                                    }
                                    //log.info("thumbnailUrl:" + thumbnailUrl);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.info("Caught exception when calling /thumbnail?title=" + articleTitle
                                            + " : " + e);
                                }
                            }
                            //log.info("thumbnailUrl:" + thumbnailUrl);
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.info("Caught exception when calling /thumbnail?id=" + itemId + " : " + e);
                        }
                    } else {
                        visGraphNodeNear.setImageUrl(thumbnailUrl);
                    }

                    /*
                    // Check cache for thumbnail
                    thumbnailUrl = ThumbnailCache.getThumbnailUrlById(itemId, articleLang);
                            
                    if (thumbnailUrl != null && thumbnailUrl.length() > 0) {
                      // Thumbnail image found in cache by ID, which is the preferred location
                      visGraphNodeNear.setImageUrl(thumbnailUrl);
                    }
                    else {
                      // Thumbnail image not found in cache by ID, so look with Wikimedia API by article title
                      log.info("Thumbnail not found in cache for itemId: " + itemId + ", lang: " + articleLang + " so looking with Wikimedia API by article title");
                            
                      try {
                        String url = this.wikiBrowserProperties.getThumbnailByTitleServiceUrl(articleTitle, articleLang);
                        thumbnailUrl = new RestTemplate().getForObject(url,
                            String.class);
                            
                        if (thumbnailUrl != null && thumbnailUrl.length() > 0) {
                          visGraphNodeNear.setImageUrl(thumbnailUrl);
                        }
                        else {
                          log.info("Thumbnail not found for articleTitle: " + articleTitle + ", trying by itemId: " + itemId);
                            
                          try {
                            String url = this.wikiBrowserProperties.getThumbnailByIdServiceUrl(itemId, articleLang);
                            thumbnailUrl = new RestTemplate().getForObject(url,
                                String.class);
                            
                            if (thumbnailUrl != null) {
                              visGraphNodeNear.setImageUrl(thumbnailUrl);
                            
                              // Because successful, cache by article title
                              ThumbnailCache.setThumbnailUrlByTitle(articleTitle, articleLang, thumbnailUrl);
                            }
                            else {
                              visGraphNodeNear.setImageUrl("");
                            }
                            //log.info("thumbnailUrl:" + thumbnailUrl);
                          }
                          catch (Exception e) {
                            e.printStackTrace();
                            log.info("Caught exception when calling /thumbnail?id=" + itemId + " : " + e);
                          }
                            
                        }
                        //log.info("thumbnailUrl:" + thumbnailUrl);
                      } catch (Exception e) {
                        e.printStackTrace();
                        log.info("Caught exception when calling /thumbnail?title=" + articleTitle + " : " + e);
                      }
                    }
                    */

                    // Note: The key in the graphNodeNearMap is the Neo4j node id, not the Wikidata item ID
                    visGraphNodeNearMap.put(graphNodeFar.getId(), visGraphNodeNear);
                }

                List<GraphRelationFar> graphRelationFarList = graphFar.getGraphRelationFarList();
                Iterator<GraphRelationFar> graphRelationFarIterator = graphRelationFarList.iterator();

                while (graphRelationFarIterator.hasNext()) {
                    GraphRelationFar graphRelationFar = graphRelationFarIterator.next();
                    VisGraphEdgeNear visGraphEdgeNear = new VisGraphEdgeNear();

                    // Use the Neo4j node ids from the relationship to retrieve the Wikidata Item IDs from the graphNodeNearMap
                    String neo4jStartNodeId = graphRelationFar.getStartNode();
                    String wikidataStartNodeItemId = visGraphNodeNearMap.get(neo4jStartNodeId).getItemId();
                    String neo4jEndNodeId = graphRelationFar.getEndNode();
                    String wikidataEndNodeItemId = visGraphNodeNearMap.get(neo4jEndNodeId).getItemId();

                    //visGraphEdgeNear.setFromDbId(neo4jStartNodeId);
                    visGraphEdgeNear.setFromDbId(wikidataStartNodeItemId.substring(1));

                    //visGraphEdgeNear.setToDbId(neo4jEndNodeId);
                    visGraphEdgeNear.setToDbId(wikidataEndNodeItemId.substring(1));

                    visGraphEdgeNear.setLabel(graphRelationFar.getType());
                    visGraphEdgeNear.setArrowDirection("to");
                    visGraphEdgeNear.setPropId(graphRelationFar.getGraphRelationPropsFar().getPropId());

                    visGraphEdgeNear.setFromItemId(wikidataStartNodeItemId);
                    visGraphEdgeNear.setToItemId(wikidataEndNodeItemId);

                    // Note: The key in the graphLinkNearMap is the Neo4j node id, not the Wikidata item ID
                    visGraphEdgeNearMap.put(graphRelationFar.getId(), visGraphEdgeNear);
                }
            }

            // Create and populate a List of nodes to set into the graphResponseNear instance
            List<VisGraphNodeNear> visGraphNodeNearList = new ArrayList<>();
            visGraphNodeNearMap.forEach((k, v) -> {
                visGraphNodeNearList.add(v);
            });
            visGraphResponseNear.setVisGraphNodeNearList(visGraphNodeNearList);

            // Create and populate a List of links to set into the graphResponseNear instance
            List<VisGraphEdgeNear> visGraphEdgeNearList = new ArrayList<>();
            visGraphEdgeNearMap.forEach((k, v) -> {
                visGraphEdgeNearList.add(v);
            });
            visGraphResponseNear.setVisGraphEdgeNearList(visGraphEdgeNearList);
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.info("Caught exception when calling Neo Cypher service " + e);
    }

    return visGraphResponseNear;
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Sends Rest API.//from  w  w  w . ja  va  2 s. c o m
 * @param method HttpMethod
 * @param url String
 * @param acceptableMediaTypes {@link List}
 * @return ResponseEntity&lt;byte[]&gt;
 */
protected ResponseEntity<byte[]> exchangeRestReturnBytes(final HttpMethod method, final String url,
        final List<MediaType> acceptableMediaTypes) {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(acceptableMediaTypes);
    HttpEntity<String> e = new HttpEntity<>("parameters", headers);

    ResponseEntity<byte[]> entity = getTemplate().exchange(url, method, e, byte[].class);

    return entity;
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Sends Rest API.//w  ww.  j  a v  a 2  s  . c  o m
 * @param method HttpMethod
 * @param url String
 * @return ResponseEntity&lt;String&gt;
 */
protected ResponseEntity<String> exchangeRestBasicAuth(final HttpMethod method, final String url) {

    HttpHeaders headers = getBasicAuthorization(getClientId(), getClientSecret());

    headers.setAccept(Arrays.asList(ACCEPT_HEADER_V1_JSON));
    HttpEntity<String> e = new HttpEntity<>("parameters", headers);

    ResponseEntity<String> entity = getTemplate().exchange(url, method, e, String.class);

    return entity;
}