Example usage for org.springframework.http HttpHeaders add

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

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

/**
 * Returns a Basic Authorization Http Headers.
 * @param user String/*from  ww  w  .ja v  a  2  s  .  c  om*/
 * @param password String
 * @return HttpHeaders
 */
protected HttpHeaders getBasicAuthorization(final String user, final String password) {

    String plainCreds = user + ":" + password;
    byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.UTF_8);
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes, StandardCharsets.UTF_8);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    return headers;
}

From source file:com.controller.ProfilesController.java

@RequestMapping(value = "/profiles/createResume/{id}", method = RequestMethod.GET)
public void createResumeView(@PathVariable int id, HttpServletRequest request, HttpServletResponse response)
        throws ParseException, IOException, COSVisitorException {
    String imagePath = request.getContextPath() + "//resources//images//logo-infosupport.png";
    Employee emp = empService.getEmployee(id);
    List<SkillRating> skillList = sri.getSkillRatingUserCv(id);
    System.out.println("size: " + skillList.size());
    List<Preceeding> preceedings = new ArrayList();
    for (Preceeding p : proceedingService.getPreceedingInEmployeeCv(empService.getEmployee(id))) {
        preceedings.add(p);//w  w w .j a  va 2 s. co  m
    }
    List<EmployeeHasEducation> educations = educationService.getEmployeeEducationsCv(id);
    ArrayList<Certificate> certificateList = (ArrayList<Certificate>) certService.getCertificateesCv(id);
    Resume resume = new Resume(preceedings, emp, (ArrayList<EmployeeHasEducation>) educations, certificateList,
            (ArrayList<SkillRating>) skillList, imagePath);
    ByteArrayOutputStream output = resume.createResume();

    // Force to download
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/force-download");
    responseHeaders.add("Content-Disposition", "attachment; filename=\"cv.pdf\"");
    response.getOutputStream().flush();
    response.getOutputStream().write(output.toByteArray());
    // ToDo: Open the pdf in a new tab

}

From source file:com.controller.ProfilesController.java

@RequestMapping(value = "/profiles/createResume", method = RequestMethod.GET)
public void createResume(HttpServletRequest request, HttpServletResponse response)
        throws ParseException, IOException, COSVisitorException {
    String imagePath = request.getContextPath() + "/resources/images/logo-infosupport.png";
    int id = (Integer) request.getSession().getAttribute("loggedIn");
    Employee emp = empService.getEmployee(id);
    List<SkillRating> skillList = sri.getSkillRatingUserCv(id);

    List<Preceeding> preceedings = new ArrayList();
    for (Preceeding p : proceedingService.getPreceedingInEmployeeCv(
            empService.getEmployee((Integer) request.getSession().getAttribute("loggedIn")))) {
        preceedings.add(p);//from w ww .j  av  a 2s .  c om
    }
    List<EmployeeHasEducation> educations = educationService.getEmployeeEducationsCv(id);
    ArrayList<Certificate> certificateList = (ArrayList<Certificate>) certService.getCertificateesCv(id);
    Resume resume = new Resume(preceedings, emp, (ArrayList<EmployeeHasEducation>) educations, certificateList,
            (ArrayList<SkillRating>) skillList, imagePath);
    ByteArrayOutputStream output = resume.createResume();

    // Force to download
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/force-download");
    responseHeaders.add("Content-Disposition", "attachment; filename=\"cv.pdf\"");
    response.getOutputStream().flush();
    response.getOutputStream().write(output.toByteArray());

}

From source file:com.netflix.genie.web.controllers.JobRestController.java

private void copyRequestHeaders(final HttpServletRequest request, final ClientHttpRequest forwardRequest) {
    // Copy all the headers (necessary for ACCEPT and security headers especially). Do not copy the cookie header.
    final HttpHeaders headers = forwardRequest.getHeaders();
    final Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            final String headerName = headerNames.nextElement();
            if (!NAME_HEADER_COOKIE.equals(headerName)) {
                final String headerValue = request.getHeader(headerName);
                log.debug("Request Header: name = {} value = {}", headerName, headerValue);
                headers.add(headerName, headerValue);
            }/* w ww.j a v  a  2  s  . c o  m*/
        }
    }
    // Lets add the cookie as an header
    final Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        StringBuilder builder = null;
        for (final Cookie cookie : request.getCookies()) {
            if (builder == null) {
                builder = new StringBuilder();
            } else {
                builder.append(",");
            }
            builder.append(cookie.getName()).append("=").append(cookie.getValue());
        }
        if (builder != null) {
            final String cookieValue = builder.toString();
            headers.add(NAME_HEADER_COOKIE, cookieValue);
            log.debug("Request Header: name = {} value = {}", NAME_HEADER_COOKIE, cookieValue);
        }
    }
    // This method only called when need to forward so add the forwarded from header
    headers.add(JobConstants.GENIE_FORWARDED_FROM_HEADER, request.getRequestURL().toString());
}

From source file:com.jaspersoft.android.sdk.client.JsRestClient.java

/**
 * Retrives all data for the root folder
 */// w w  w  .  j a  va 2  s.  c  o  m
public FolderDataResponse getRootFolderData() {
    String fullUri = jsServerProfile.getServerUrl() + REST_SERVICES_V2_URI + REST_RESOURCES_URI;
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", "application/repository.folder+xml");
    headers.add("Content-Type", "application/xml");
    HttpEntity<String> httpEntity = new HttpEntity<String>("", headers);

    ResponseEntity<FolderDataResponse> responseEntity = restTemplate.exchange(fullUri, HttpMethod.GET,
            httpEntity, FolderDataResponse.class);

    return responseEntity.getBody();
}

From source file:io.github.microcks.web.RestController.java

@RequestMapping(value = "/{service}/{version}/**")
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay,
        @RequestBody(required = false) String body, HttpServletRequest request) {

    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version,
            request.getRequestURI(), request.getMethod());
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;//from ww  w  . j  av a2s .  c o m

    try {
        // Build the encoded URI fragment to retrieve simple resourcePath.
        serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
        resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    } catch (UnsupportedEncodingException e1) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    log.info("Found resourcePath: " + resourcePath);

    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(),
                rOperation.getDispatcherRules());

        Response response = null;
        String uriPattern = getURIPattern(rOperation.getName());
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            ScriptEngineManager sem = new ScriptEngineManager();
            try {
                // Evaluating request with script coming from operation dispatcher rules.
                ScriptEngine se = sem.getEngineByExtension("groovy");
                SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
                dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules());
            } catch (Exception e) {
                log.error("Error during Script evaluation", e);
            }
        }
        // New cases related to services/operations/messages coming from a postman collection file.
        else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) {
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        if (response != null) {
            // Setting delay to default one if not set.
            if (delay == null && rOperation.getDefaultDelay() != null) {
                delay = rOperation.getDefaultDelay();
            }

            if (delay != null && delay > -1) {
                log.debug("Mock delay is turned on, waiting if necessary...");
                long duration = System.currentTimeMillis() - startTime;
                if (duration < delay) {
                    Object semaphore = new Object();
                    synchronized (semaphore) {
                        try {
                            semaphore.wait(delay - duration);
                        } catch (Exception e) {
                            log.debug("Delay semaphore was interrupted");
                        }
                    }
                }
                log.debug("Delay now expired, releasing response !");
            }

            // Publish an invocation event before returning.
            MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                    response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
            applicationContext.publishEvent(event);
            log.debug("Mock invocation event has been published");

            HttpStatus status = (response.getStatus() != null
                    ? HttpStatus.valueOf(Integer.parseInt(response.getStatus()))
                    : HttpStatus.OK);

            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }

            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = "http://" + request.getServerName() + ":" + request.getServerPort()
                                + request.getContextPath() + "/rest" + serviceAndVersion
                                + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            return new ResponseEntity<Object>(response.getContent(), responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

From source file:eu.dime.dnsregister.controllers.RecordsController.java

@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody String json) {

    HttpHeaders headers = new HttpHeaders();

    try {// w  w  w. ja va 2s  .  co  m

        // Obtain Data from JSON
        Records records = Records.fromJsonToRecords(json);

        String[] url = records.getName().split("\\.");

        String search = url[url.length - 1];
        int subdominis = 0;
        for (int i = url.length - 2; i >= 0; i--) {
            switch (subdominis) {
            case 0:
                //buscar a la taula domains - provisional hard coded
                if (search.equals("dns.dime-project.eu")) {
                    //Search domainId in table domains - provisional hard coded
                    records.setDomainId(1);
                    //saltar a construir ordername
                    subdominis = 1;
                    search = url[i];
                } else
                    search = url[i] + "." + search;
                break;
            case 1:
                search = search + " " + url[i];
                break;
            }
        }

        records.setOrdername(search);
        records.setType("A");
        records.setPrio(null);
        records.setAuth(true);

        // Save Data
        records.persist();

    } catch (Exception e) {
        headers.add("Content-Type", "text/plain");
        return new ResponseEntity<String>("No correct JSON: [" + e.getMessage() + "]", headers,
                HttpStatus.BAD_REQUEST);
    }

    headers.add("Content-Type", "text/plain");
    return new ResponseEntity<String>("Created OK", headers, HttpStatus.CREATED);

}

From source file:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    ResponseEntity<Map> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());//from w  w  w . j a  va  2s  . c o m
    headers = getAppBasicAuthHttpHeaders();
    headers.add("Cookie", cookies.get(0));

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true").build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token")
            .queryParam("response_type", "token").queryParam("grant_type", "authorization_code")
            .queryParam("code", newCode).queryParam("redirect_uri", appUrl).build().toUriString();

    ResponseEntity<Map> tokenResponse = template.exchange(tokenUrl, HttpMethod.POST,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    ResponseEntity<Void> loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());
    headers.clear();
    headers.add("Cookie", cookies.get(0));
    restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, headers), Void.class);

    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

From source file:org.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java

private InputStream getFileInputStream(DriveFile driveFile, String mimetype)
        throws GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException, GoogleDocsServiceException {
    RestTemplate restTemplate = new RestTemplate();

    String url = getExportLink(driveFile, mimetype);
    log.debug("Google Export Format (mimetype) link: " + url);

    if (url == null) {
        throw new GoogleDocsServiceException("Google Docs Export Format not found.",
                HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE);
    }//ww  w .  ja  v  a  2 s . c om

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + getConnection().getApi().getAccessToken());
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(body,
            headers);

    ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);

    return new ByteArrayInputStream(response.getBody());
}