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:gateway.controller.EventController.java

/**
 * Proxies an ElasticSearch DSL query to the Pz-Workflow component to return a list of Event items.
 * //from   w ww  .  j av  a 2  s.c  o  m
 * @see TBD
 * 
 * @return The list of Event items matching the query.
 */
@RequestMapping(value = "/event/query", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Query Events in Piazza Workflow", notes = "Sends a complex query message to the Piazza Workflow component, that allow users to search for Events. Searching is capable of filtering by keywords or other dynamic information.", tags = {
        "Event", "Workflow", "Search" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "The list of Event results that match the query string.", response = EventListResponse.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> searchEvents(
        @ApiParam(value = "The Query string for the Workflow component.", 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) Integer page,
        @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "perPage", required = false) Integer perPage,
        @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false) String order,
        @ApiParam(value = "The data field to sort by.") @RequestParam(value = "sortBy", required = false) String sortBy,
        Principal user) {
    try {
        // Log the request
        logger.log(String.format("User %s sending a complex query for Workflow.",
                gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO);

        // Send the query to the Pz-Workflow component
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<Object>(query, headers);

        String paramPage = (page == null) ? "" : "page=" + page.toString();
        String paramPerPage = (perPage == null) ? "" : "perPage=" + perPage.toString();
        String paramOrder = (order == null) ? "" : "order=" + order;
        String paramSortBy = (sortBy == null) ? "" : "sortBy=" + sortBy;

        EventListResponse searchResponse = restTemplate.postForObject(String.format("%s/%s/%s?%s&%s&%s&%s",
                WORKFLOW_URL, "event", "query", paramPage, paramPerPage, paramOrder, paramSortBy), entity,
                EventListResponse.class);
        // Respond
        return new ResponseEntity<PiazzaResponse>(searchResponse, HttpStatus.OK);
    } catch (Exception exception) {
        String error = String.format("Error Querying Data 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:gateway.controller.EventController.java

/**
 * Proxies an ElasticSearch DSL query to the Pz-Workflow component to return a list of EventType items.
 * //w  ww. ja  v  a  2s. c  o  m
 * @see TBD
 * 
 * @return The list of EventType items matching the query.
 */
@RequestMapping(value = "/eventType/query", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Query EventTypes in Piazza Workflow", notes = "Sends a complex query message to the Piazza Workflow component, that allow users to search for EventTypes. Searching is capable of filtering by keywords or other dynamic information.", tags = {
        "EventType", "Workflow", "Search" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "The list of EventType results that match the query string.", response = EventTypeListResponse.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> searchEventTypes(
        @ApiParam(value = "The Query string for the Workflow component.", 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) Integer page,
        @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "perPage", required = false) Integer perPage,
        @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false) String order,
        @ApiParam(value = "The data field to sort by.") @RequestParam(value = "sortBy", required = false) String sortBy,
        Principal user) {
    try {
        // Log the request
        logger.log(String.format("User %s sending a complex query for Workflow.",
                gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO);

        // Send the query to the Pz-Workflow component
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<Object>(query, headers);

        String paramPage = (page == null) ? "" : "page=" + page.toString();
        String paramPerPage = (perPage == null) ? "" : "perPage=" + perPage.toString();
        String paramOrder = (order == null) ? "" : "order=" + order;
        String paramSortBy = (sortBy == null) ? "" : "sortBy=" + sortBy;

        EventTypeListResponse searchResponse = restTemplate.postForObject(String.format("%s/%s/%s?%s&%s&%s&%s",
                WORKFLOW_URL, "eventType", "query", paramPage, paramPerPage, paramOrder, paramSortBy), entity,
                EventTypeListResponse.class);
        // Respond
        return new ResponseEntity<PiazzaResponse>(searchResponse, HttpStatus.OK);
    } catch (Exception exception) {
        String error = String.format("Error Querying Data 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:io.seldon.client.services.ApiServiceImpl.java

private ResourceBean getTokenResource(String url) {
    ResourceBean bean;/*from   w w w.ja  va 2  s.c o  m*/
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    try {
        ResponseEntity<TokenBean> res = new RestTemplate().exchange(url, HttpMethod.GET, entity,
                TokenBean.class);
        bean = res.getBody();
    } catch (Exception e) {
        HttpEntity<ErrorBean> res = new RestTemplate().exchange(url, HttpMethod.GET, entity, ErrorBean.class);
        bean = res.getBody();
    }
    return bean;
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

@RequestMapping(value = "/app/image", method = RequestMethod.GET, params = { "id" })
public ResponseEntity<byte[]> getIcon(@RequestParam("id") Long id) {
    Application application = appManagement.getApplication(id);

    if (application == null) {
        throw new IllegalArgumentException("No application found with id " + id);
    }/*from  www .jav a 2s  . c om*/
    byte[] content = application.getIcon();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<byte[]>(content, headers, HttpStatus.OK);
}

From source file:io.seldon.client.services.ApiServiceImpl.java

private ResourceBean performPostGet(final String endpointUrl, final ResourceBean resourceBean, Class c) {
    ResourceBean bean;//w w  w  .  j a  v a  2 s  .com
    if (token == null) {
        ResourceBean r = getToken();
        if (r instanceof ErrorBean)
            return r;
    }
    String url = endpointUrl + "&oauth_token=" + token;
    //header
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<ResourceBean> entity = new HttpEntity<ResourceBean>(resourceBean, headers);
    RestTemplate template = createRestTemplate();
    try {
        logger.debug("* Posting: " + resourceBean);
        logger.debug("** Endpoint: " + url);
        // API return types for posts vary: Map on success, ErrorBean on failure -- we're forced to use Object here:
        ResponseEntity<ResourceBean> responseEntity;
        responseEntity = template.postForEntity(url, entity, c);
        bean = responseEntity.getBody();
    } catch (Exception e) {
        if (e.getCause() instanceof SocketTimeoutException) {
            return createTimeoutBean();
        }
        logger.error("Exception class: " + e.getClass());
        //logger.error("Failed Api Call for url: " + urlWithToken + " : " + e.toString());
        logger.error("*** NOK (" + url + "): " + e.getMessage());
        HttpEntity<ErrorBean> res;
        try {
            res = template.postForEntity(url, entity, ErrorBean.class);
        } catch (ResourceAccessException rae) {
            return createTimeoutBean();
        }
        bean = res.getBody();
    }
    if (bean instanceof ErrorBean) {
        if (((ErrorBean) bean).getError_id() != Constants.TOKEN_EXPIRED) {
            return bean;
        } else {
            logger.info("Token expired; fetching a new one.");
            ResourceBean r = getToken();
            if (r instanceof ErrorBean) {
                return r;
            } else {
                return performPostGet(endpointUrl, resourceBean, c);
            }
        }
    } else {
        return bean;
    }
}

From source file:io.seldon.client.services.ApiServiceImpl.java

private ResourceBean getResource(final String url, Class<?> c) {
    logger.info("* GET Endpoint: " + url);
    ResourceBean bean;//from  w  ww .j  av  a2  s .c om
    if (token == null) {
        ResourceBean r = getToken();
        if (r instanceof ErrorBean)
            return r;
    }

    String urlWithToken = url + "&oauth_token=" + token;
    logger.debug("** Token: " + token);
    logger.debug("** Class: " + c.getName());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    RestTemplate restTemplate = createRestTemplate();
    try {
        //logger.info("Calling end point: " + urlWithToken + " for class: " + c.getName());
        @SuppressWarnings("unchecked")
        HttpEntity<ResourceBean> res = (HttpEntity<ResourceBean>) restTemplate.exchange(urlWithToken,
                HttpMethod.GET, entity, c);
        logger.debug("Result: " + res.toString() + " : " + res.getBody());
        bean = res.getBody();
        logger.debug("*** OK (" + urlWithToken + ")");
    } catch (Exception e) {
        if (e.getCause() instanceof SocketTimeoutException) {
            return createTimeoutBean();
        }
        logger.error("Exception class: " + e.getClass());
        //logger.error("Failed Api Call for url: " + urlWithToken + " : " + e.toString());
        logger.error("*** NOK (" + urlWithToken + "): " + e.getMessage());
        HttpEntity<ErrorBean> res = null;
        try {
            res = restTemplate.exchange(urlWithToken, HttpMethod.GET, entity, ErrorBean.class);
        } catch (RestClientException e1) {
            if (e1.getCause() instanceof SocketTimeoutException) {
                return createTimeoutBean();
            }
        }
        bean = res.getBody();
    }
    if (bean instanceof ErrorBean) {
        if (((ErrorBean) bean).getError_id() != Constants.TOKEN_EXPIRED) {
            return bean;
        } else {
            logger.info("Token expired; fetching a new one.");
            ResourceBean r = getToken();
            if (r instanceof ErrorBean) {
                return r;
            } else {
                return getResource(url, c);
            }
        }
    } else {
        return bean;
    }
}

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  ww. j a  v a 2  s  .  c  o  m*/
 * @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:it.geosolutions.opensdi.operations.FolderManagerOperationController.java

/**
 * Download a file with a stream/*www .  ja  v  a 2  s . co m*/
 * 
 * @param resp
 * @param fileName
 * @param filePath
 * @return
 */
@SuppressWarnings("resource")
private ResponseEntity<byte[]> download(HttpServletResponse resp, String fileName, String filePath) {

    final HttpHeaders headers = new HttpHeaders();
    File toServeUp = new File(filePath);
    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream(toServeUp);
    } catch (FileNotFoundException e) {

        // Also useful, this is a good was to serve down an error message
        String msg = "ERROR: Could not find the file specified.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);

    }

    resp.setContentType("application/octet-stream");
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    Long fileSize = toServeUp.length();
    resp.setContentLength(fileSize.intValue());

    OutputStream outputStream = null;

    try {
        outputStream = resp.getOutputStream();
    } catch (IOException e) {
        String msg = "ERROR: Could not generate output stream.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    byte[] buffer = new byte[1024];

    int read = 0;
    try {

        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }

        // close the streams to prevent memory leaks
        outputStream.flush();
        outputStream.close();
        inputStream.close();

    } catch (Exception e) {
        String msg = "ERROR: Could not read file.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    return null;
}