Example usage for org.springframework.http HttpHeaders set

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

Introduction

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

Prototype

@Override
public void set(String headerName, @Nullable String headerValue) 

Source Link

Document

Set the given, single header value under the given name.

Usage

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

/**
 * Populates the Spring Security context with a
 * {@link UsernamePasswordAuthenticationToken} referring to the client
 * that authenticates using the basic authorization header.
 *///from   ww w  .j a v  a2s.  co m
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest servletRequest = (HttpServletRequest) request;
    String header = servletRequest.getHeader("Authorization");
    if (header == null || !header.startsWith("Basic ")) {
        chain.doFilter(request, response);
        return;
    }

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", header);

    try {

        ResponseEntity<BaseClientDetails> result = restTemplate.exchange(clientInfoUrl, HttpMethod.GET,
                new HttpEntity<Void>(headers), BaseClientDetails.class);

        ClientDetails client = result.getBody();
        String clientId = client.getClientId();
        validateClient(client);

        Authentication authResult = new UsernamePasswordAuthenticationToken(clientId, "<NONE>",
                client.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authResult);

    } catch (RuntimeException e) {
        logger.debug("Authentication failed");
        authenticationEntryPoint.commence(servletRequest, (HttpServletResponse) response,
                new BadCredentialsException("Could not authenticate", e));
        return;
    }

    chain.doFilter(request, response);

}

From source file:org.cloudfoundry.identity.uaa.oauth.RemoteTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);

    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }/* w ww .j av a2s.  co  m*/

    Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) map.get("client_id");

    Set<String> scope = new HashSet<String>();
    if (map.containsKey("scope")) {
        @SuppressWarnings("unchecked")
        Collection<String> values = (Collection<String>) map.get("scope");
        scope.addAll(values);
    }
    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);

    if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<String>();
        if (map.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("resource_ids");
            resourceIds.addAll(values);
        }
        Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>();
        if (map.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }
    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (map.containsKey(ClaimConstants.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(ClaimConstants.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(map.get(ClaimConstants.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));

    Authentication userAuthentication = getUserAuthentication(map, scope);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}

From source file:org.exem.flamingo.web.filesystem.hdfs.HdfsBrowserController.java

/**
 *  ?? .//w  w w .jav  a 2  s.c  om
 *
 * @return REST Response JAXB Object
 */
@RequestMapping(value = "download", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public ResponseEntity download(HttpServletResponse res, @RequestParam String srcPath,
        @RequestParam String fullyQualifiedPath) {
    String srcFilePath = getPathFilter(srcPath);
    String username = SessionUtils.getUsername();

    HttpHeaders headers = new HttpHeaders();

    if (org.apache.commons.lang.StringUtils.isEmpty(fullyQualifiedPath)) {
        headers.set("message", "Invalid parameter.");
        return new ResponseEntity(headers, HttpStatus.BAD_REQUEST);
    }

    //TODO HDFS  ? ? 
    /*List<String> paths = hdfsBrowserAuthService.getHdfsBrowserPatternAll(username);
    String hdfsPathPattern = hdfsBrowserAuthService.validateHdfsPathPattern(srcFilePath, paths);
    Map fileMap = new HashMap();
            
    fileMap.put("username", username);
    fileMap.put("hdfsPathPattern", hdfsPathPattern);
    fileMap.put("condition", "downloadFile");
            
    hdfsBrowserAuthService.getHdfsBrowserUserDirAuth(fileMap);*/
    boolean isRemoteEngine = Boolean.parseBoolean(isRemote);

    // Remote ? ? ?, Remote? Store and Forward 
    if (!isRemoteEngine) {
        String filSplit[] = fullyQualifiedPath.split("/");
        String filename = filSplit[filSplit.length - 1];

        fileSystemService.validatePath(srcFilePath);

        HttpResponse execute;
        try {
            String namenodeAgentUrl = MessageFormatter
                    .arrayFormat("http://{}:{}/remote/agent/transfer/download?fullyQualifiedPath={}",
                            new Object[] { namenodeAgentAddress, namenodeAgentPort,
                                    URLEncoder.encode(fullyQualifiedPath, "UTF-8") })
                    .getMessage();

            HttpGet httpGet = new HttpGet(namenodeAgentUrl);
            execute = httpClient.execute(httpGet);
        } catch (Exception ex) {
            throw new WholeBodyException("File Download Failed");
        }

        if (execute.getStatusLine().getStatusCode() != 200) {
            throw new WholeBodyException("File Download Failed");
        } else {
            try {
                InputStream is = execute.getEntity().getContent();
                res.setHeader("Content-Length", "" + execute.getEntity().getContentLength());
                res.setHeader("Content-Transfer-Encoding", "binary");
                res.setHeader("Content-Type", "application/force-download");
                res.setHeader("Content-Disposition",
                        MessageFormatter.format("attachment; fullyQualifiedPath={}; filename={};",
                                URLEncoder.encode(fullyQualifiedPath, "UTF-8"), filename).getMessage());
                res.setStatus(200);

                FileCopyUtils.copy(is, res.getOutputStream());
                res.flushBuffer();

                fileSystemService.validateBeforeDownload(srcFilePath, fullyQualifiedPath, username);

                return new ResponseEntity(HttpStatus.OK);
            } catch (Exception ex) {
                throw new WholeBodyException("File Download Failed", ex);
            }
        }
    } else {
        try {
            byte[] bytes = fileSystemService.load(srcFilePath, fullyQualifiedPath, username);

            res.setHeader("Content-Length", "" + bytes.length);
            res.setHeader("Content-Transfer-Encoding", "binary");
            res.setHeader("Content-Type", "application/force-download");
            res.setHeader("Content-Disposition", MessageFormatter.format("attachment; fullyQualifiedPath={};",
                    URLEncoder.encode(fullyQualifiedPath, "UTF-8")).getMessage());
            res.setStatus(200);

            FileCopyUtils.copy(bytes, res.getOutputStream());
            res.flushBuffer();
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            throw new WholeBodyException("File Download Failed", ex);
        }
    }
}

From source file:org.flowable.cmmn.rest.service.api.repository.CaseDefinitionImageResource.java

@ApiOperation(value = "Get a case definition image", tags = { "Case Definitions" })
@ApiResponses(value = {//  ww  w .j a  v a  2 s  . com
        @ApiResponse(code = 200, message = "Indicates request was successful and the case definitions are returned"),
        @ApiResponse(code = 404, message = "Indicates the requested case definition was not found.") })
@GetMapping("/cmmn-repository/case-definitions/{caseDefinitionId}/image")
public ResponseEntity<byte[]> getImageResource(
        @ApiParam(name = "caseDefinitionId") @PathVariable String caseDefinitionId) {
    CaseDefinition caseDefinition = getCaseDefinitionFromRequest(caseDefinitionId);
    InputStream imageStream = repositoryService.getCaseDiagram(caseDefinition.getId());

    if (imageStream != null) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "image/png");
        try {
            return new ResponseEntity<>(IOUtils.toByteArray(imageStream), responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            throw new FlowableException("Error reading image stream", e);
        }
    } else {
        throw new FlowableObjectNotFoundException(
                "Case definition with id '" + caseDefinition.getId() + "' has no image.");
    }
}

From source file:org.flowable.cmmn.rest.service.api.runtime.caze.CaseInstanceDiagramResource.java

@ApiOperation(value = "Get diagram for a case instance", tags = { "Case Instances" })
@ApiResponses(value = {/*  ww  w.  j av a  2s . co m*/
        @ApiResponse(code = 200, message = "Indicates the case instance was found and the diagram was returned."),
        @ApiResponse(code = 400, message = "Indicates the requested case instance was not found but the process does not contain any graphical information (CMMN DI) and no diagram can be created."),
        @ApiResponse(code = 404, message = "Indicates the requested case instance was not found.") })
@GetMapping(value = "/cmmn-runtime/case-instances/{caseInstanceId}/diagram")
public ResponseEntity<byte[]> getCaseInstanceDiagram(
        @ApiParam(name = "caseInstanceId") @PathVariable String caseInstanceId, HttpServletResponse response) {
    CaseInstance caseInstance = getCaseInstanceFromRequest(caseInstanceId);

    CaseDefinition caseDef = repositoryService.getCaseDefinition(caseInstance.getCaseDefinitionId());

    if (caseDef != null && caseDef.hasGraphicalNotation()) {
        CmmnModel cmmnModel = repositoryService.getCmmnModel(caseDef.getId());
        CaseDiagramGenerator diagramGenerator = cmmnEngineConfiguration.getCaseDiagramGenerator();
        InputStream resource = diagramGenerator.generateDiagram(cmmnModel, "png",
                cmmnEngineConfiguration.getActivityFontName(), cmmnEngineConfiguration.getLabelFontName(),
                cmmnEngineConfiguration.getAnnotationFontName(), cmmnEngineConfiguration.getClassLoader(), 1.0);

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "image/png");
        try {
            return new ResponseEntity<>(IOUtils.toByteArray(resource), responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            throw new FlowableIllegalArgumentException("Error exporting diagram", e);
        }

    } else {
        throw new FlowableIllegalArgumentException(
                "Case instance with id '" + caseInstance.getId() + "' has no graphical notation defined.");
    }
}

From source file:org.flowable.content.rest.service.api.content.ContentItemDataResource.java

@ApiOperation(value = "Get the data of a content item", tags = {
        "Content item" }, notes = "The response body contains the binary content. By default, the content-type of the response is set to application/octet-stream unless the content item type contains a valid mime type.")
@ApiResponses(value = {//w  w  w. j av a 2 s .c  o m
        @ApiResponse(code = 200, message = "Indicates the content item was found and the requested content is returned."),
        @ApiResponse(code = 404, message = "Indicates the content item was not found or the content item does not have a binary stream available. Status message provides additional information.") })
@GetMapping(value = "/content-service/content-items/{contentItemId}/data")
public ResponseEntity<byte[]> getContentItemData(
        @ApiParam(name = "contentItemId") @PathVariable("contentItemId") String contentItemId,
        HttpServletResponse response) {

    ContentItem contentItem = getContentItemFromRequest(contentItemId);
    if (!contentItem.isContentAvailable()) {
        throw new FlowableException("No data available for content item " + contentItemId);
    }

    InputStream dataStream = contentService.getContentItemData(contentItemId);
    if (dataStream == null) {
        throw new FlowableObjectNotFoundException(
                "Content item with id '" + contentItemId + "' doesn't have content associated with it.");
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    MediaType mediaType = null;
    if (contentItem.getMimeType() != null) {
        try {
            mediaType = MediaType.valueOf(contentItem.getMimeType());
            responseHeaders.set("Content-Type", contentItem.getMimeType());
        } catch (Exception e) {
            // ignore if unknown media type
        }
    }

    if (mediaType == null) {
        responseHeaders.set("Content-Type", "application/octet-stream");
    }

    try {
        return new ResponseEntity<>(IOUtils.toByteArray(dataStream), responseHeaders, HttpStatus.OK);
    } catch (Exception e) {
        throw new FlowableException("Error getting content item data " + contentItemId, e);
    }
}

From source file:org.flowable.rest.content.service.api.content.ContentItemDataResource.java

@ApiOperation(value = "Get the data of a content item", tags = {
        "Content item" }, notes = "The response body contains the binary content. By default, the content-type of the response is set to application/octet-stream unless the content item type contains a valid mime type.")
@ApiResponses(value = {// w w w  .j  a va  2s.  c  om
        @ApiResponse(code = 200, message = "Indicates the content item was found and the requested content is returned."),
        @ApiResponse(code = 404, message = "Indicates the content item was not found or the content item doesnt have a binary stream available. Status message provides additional information.") })
@RequestMapping(value = "/content-service/content-items/{contentItemId}/data", method = RequestMethod.GET)
public ResponseEntity<byte[]> getContentItemData(
        @ApiParam(name = "contentItemId") @PathVariable("contentItemId") String contentItemId,
        HttpServletResponse response) {

    ContentItem contentItem = getContentItemFromRequest(contentItemId);
    if (!contentItem.isContentAvailable()) {
        throw new FlowableException("No data available for content item " + contentItemId);
    }

    InputStream dataStream = contentService.getContentItemData(contentItemId);
    if (dataStream == null) {
        throw new FlowableObjectNotFoundException(
                "Content item with id '" + contentItemId + "' doesn't have content associated with it.");
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    MediaType mediaType = null;
    if (contentItem.getMimeType() != null) {
        try {
            mediaType = MediaType.valueOf(contentItem.getMimeType());
            responseHeaders.set("Content-Type", contentItem.getMimeType());
        } catch (Exception e) {
            // ignore if unknown media type
        }
    }

    if (mediaType == null) {
        responseHeaders.set("Content-Type", "application/octet-stream");
    }

    try {
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(dataStream), responseHeaders, HttpStatus.OK);
    } catch (Exception e) {
        throw new FlowableException("Error getting content item data " + contentItemId, e);
    }
}

From source file:org.flowable.rest.service.api.identity.UserPictureResource.java

@ApiOperation(value = "Get a users picture", tags = {
        "Users" }, notes = "The response body contains the raw picture data, representing the users picture. The Content-type of the response corresponds to the mimeType that was set when creating the picture.")
@ApiResponses(value = {//from w  w w  . j a  v  a 2s  . c  om
        @ApiResponse(code = 200, message = "Indicates the user was found and has a picture, which is returned in the body."),
        @ApiResponse(code = 404, message = "Indicates the requested user was not found or the user does not have a profile picture. Status-description contains additional information about the error.") })
@RequestMapping(value = "/identity/users/{userId}/picture", method = RequestMethod.GET)
public ResponseEntity<byte[]> getUserPicture(@ApiParam(name = "userId") @PathVariable String userId,
        HttpServletRequest request, HttpServletResponse response) {
    User user = getUserFromRequest(userId);
    Picture userPicture = identityService.getUserPicture(user.getId());

    if (userPicture == null) {
        throw new FlowableObjectNotFoundException(
                "The user with id '" + user.getId() + "' does not have a picture.", Picture.class);
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    if (userPicture.getMimeType() != null) {
        responseHeaders.set("Content-Type", userPicture.getMimeType());
    } else {
        responseHeaders.set("Content-Type", "image/jpeg");
    }

    try {
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(userPicture.getInputStream()), responseHeaders,
                HttpStatus.OK);
    } catch (Exception e) {
        throw new FlowableException("Error exporting picture: " + e.getMessage(), e);
    }
}

From source file:org.flowable.rest.service.api.repository.ProcessDefinitionImageResource.java

@ApiOperation(value = "Get a process definition image", tags = { "Process Definitions" })
@ApiResponses(value = {/*w ww .  j a  v  a  2  s.c o  m*/
        @ApiResponse(code = 200, message = "Indicates request was successful and the process-definitions are returned"),
        @ApiResponse(code = 404, message = "Indicates the requested process definition was not found.") })
@RequestMapping(value = "/repository/process-definitions/{processDefinitionId}/image", method = RequestMethod.GET)
public ResponseEntity<byte[]> getModelResource(
        @ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId) {
    ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId);
    InputStream imageStream = repositoryService.getProcessDiagram(processDefinition.getId());

    if (imageStream != null) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "image/png");
        try {
            return new ResponseEntity<byte[]>(IOUtils.toByteArray(imageStream), responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            throw new FlowableException("Error reading image stream", e);
        }
    } else {
        throw new FlowableIllegalArgumentException(
                "Process definition with id '" + processDefinition.getId() + "' has no image.");
    }
}

From source file:org.flowable.rest.service.api.runtime.process.ProcessInstanceDiagramResource.java

@ApiOperation(value = "Get diagram for a process instance", tags = { "Process Instances" })
@ApiResponses(value = {/*from   w  ww  .  j ava  2  s . c  o m*/
        @ApiResponse(code = 200, message = "Indicates the process instance was found and the diagram was returned."),
        @ApiResponse(code = 400, message = "Indicates the requested process instance was not found but the process doesnt contain any graphical information (BPMN:DI) and no diagram can be created."),
        @ApiResponse(code = 404, message = "Indicates the requested process instance was not found.") })
@RequestMapping(value = "/runtime/process-instances/{processInstanceId}/diagram", method = RequestMethod.GET)
public ResponseEntity<byte[]> getProcessInstanceDiagram(
        @ApiParam(name = "processInstanceId") @PathVariable String processInstanceId,
        HttpServletResponse response) {
    ProcessInstance processInstance = getProcessInstanceFromRequest(processInstanceId);

    ProcessDefinition pde = repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

    if (pde != null && pde.hasGraphicalNotation()) {
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pde.getId());
        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
        InputStream resource = diagramGenerator.generateDiagram(bpmnModel, "png",
                runtimeService.getActiveActivityIds(processInstance.getId()), Collections.<String>emptyList(),
                processEngineConfiguration.getActivityFontName(), processEngineConfiguration.getLabelFontName(),
                processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader(),
                1.0);

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "image/png");
        try {
            return new ResponseEntity<byte[]>(IOUtils.toByteArray(resource), responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            throw new FlowableIllegalArgumentException("Error exporting diagram", e);
        }

    } else {
        throw new FlowableIllegalArgumentException("Process instance with id '" + processInstance.getId()
                + "' has no graphical notation defined.");
    }
}