Example usage for org.springframework.http HttpHeaders LOCATION

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

Introduction

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

Prototype

String LOCATION

To view the source code for org.springframework.http HttpHeaders LOCATION.

Click Source Link

Document

The HTTP Location header field name.

Usage

From source file:org.openwms.core.uaa.api.UsersController.java

/**
 * Takes a newly created <tt>User</tt> instance and persists it. <p> <p> <table> <tr> <td>URI</td> <td>/users</td> </tr> <tr>
 * <td>Verb</td> <td>POST</td> </tr> <tr> <td>Auth</td> <td>YES</td> </tr> <tr> <td>Header</td> <td></td> </tr> </table> </p> <p>
 * Request Body <p>//from   w  w  w.j a  v a2 s.  c  o  m
 * <pre>
 *   {
 *     "username" : "testuser"
 *   }
 * </pre>
 * <p> Parameters: <ul> <li>username (String):</li> The unique username. </ul> </p> <p> Response Body <p>
 * <pre>
 *   {
 *     "id" : 4711,
 *     "username" : "testuser",
 *     "token" : "876sjh36ejwhd",
 *     "version" : 1
 *   }
 * </pre>
 * <p> <ul> <li>id (Integer (32bit)):</li> The internal unique technical key for the stored instance. <li>username (String):</li> The
 * unique username. <li>token (String):</li> A generated token that is used to authenticate each request. <li>version (Integer
 * (32bit)):</li> A version number used internally for optimistic locking. </ul> </p>
 *
 * @param user The user to create
 * @return a responseVO
 */
@PostMapping
@ResponseBody
public ResponseEntity<Response<UserVO>> create(@RequestBody @Valid @NotNull UserVO user, HttpServletRequest req,
        HttpServletResponse resp) {
    User createdUser = service.create(m.map(user, User.class));
    resp.addHeader(HttpHeaders.LOCATION, getLocationForCreatedResource(req, createdUser.getPk().toString()));
    return buildResponse(HttpStatus.CREATED, translate(Messages.CREATED), Messages.CREATED);
}

From source file:example.company.UrlLevelSecurityTests.java

@Test
public void allowsPostRequestForAdmin() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.ACCEPT, "application/hal+json");
    headers.set(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encode(("ollie:gierke").getBytes())));

    mvc.perform(get("/employees").//
            headers(headers)).//
            andExpect(content().contentType(MediaTypes.HAL_JSON)).//
            andExpect(status().isOk()).//
            andDo(print());//  w w w. j av  a2  s .  c  o m

    headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    String location = mvc.perform(post("/employees").//
            content(PAYLOAD).//
            headers(headers)).//
            andExpect(status().isCreated()).//
            andDo(print()).//
            andReturn().getResponse().getHeader(HttpHeaders.LOCATION);

    ObjectMapper mapper = new ObjectMapper();

    String content = mvc.perform(get(location)).//
            andReturn().getResponse().getContentAsString();
    Employee employee = mapper.readValue(content, Employee.class);

    assertThat(employee.getFirstName(), is("Saruman"));
    assertThat(employee.getLastName(), is("the White"));
    assertThat(employee.getTitle(), is("Wizard"));
}

From source file:org.openwms.tms.DocumentationBase.java

protected MvcResult postTOAndValidate(CreateTransportOrderVO vo, String outputFile) throws Exception {
    MvcResult res;/* ww w .j  a  v a 2 s  .c o  m*/
    if (NOTLOGGED.equals(outputFile)) {
        res = mockMvc
                .perform(post(TMSConstants.ROOT_ENTITIES).contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(vo)))
                .andExpect(status().isCreated()).andReturn();
    } else {
        res = mockMvc
                .perform(post(TMSConstants.ROOT_ENTITIES).contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(vo)))
                .andExpect(status().isCreated()).andDo(document(outputFile)).andReturn();
    }

    String toLocation = (String) res.getResponse().getHeaderValue(HttpHeaders.LOCATION);
    toLocation = toLocation.substring(0, toLocation.length() - 1);
    vo.setpKey(toLocation.substring(toLocation.lastIndexOf("/") + 1));
    return res;
}

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

private String submitJob(final int documentationId, final JobRequest jobRequest,
        final List<MockMultipartFile> attachments) throws Exception {
    final MvcResult result;

    if (attachments != null) {
        final RestDocumentationResultHandler createResultHandler = MockMvcRestDocumentation.document(
                "{class-name}/" + documentationId + "/submitJobWithAttachments/",
                Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
                Preprocessors.preprocessResponse(Preprocessors.prettyPrint()),
                HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                        .description(MediaType.MULTIPART_FORM_DATA_VALUE)), // Request headers
                RequestDocumentation.requestParts(
                        RequestDocumentation.partWithName("request").description(
                                "The job request JSON. Content type must be application/json for part"),
                        RequestDocumentation.partWithName("attachment").description(
                                "An attachment file. There can be multiple. Type should be octet-stream")), // Request parts
                Snippets.LOCATION_HEADER // Response Headers
        );//from w  w  w  .  j a  v a 2  s .  co  m

        final MockMultipartFile json = new MockMultipartFile("request", "", MediaType.APPLICATION_JSON_VALUE,
                this.objectMapper.writeValueAsBytes(jobRequest));

        final MockMultipartHttpServletRequestBuilder builder = RestDocumentationRequestBuilders
                .fileUpload(JOBS_API).file(json);

        for (final MockMultipartFile attachment : attachments) {
            builder.file(attachment);
        }

        builder.contentType(MediaType.MULTIPART_FORM_DATA);
        result = this.mvc.perform(builder).andExpect(MockMvcResultMatchers.status().isAccepted())
                .andExpect(MockMvcResultMatchers.header().string(HttpHeaders.LOCATION, Matchers.notNullValue()))
                .andDo(createResultHandler).andReturn();
    } else {
        // Use regular POST
        final RestDocumentationResultHandler createResultHandler = MockMvcRestDocumentation.document(
                "{class-name}/" + documentationId + "/submitJobWithoutAttachments/",
                Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
                Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), Snippets.CONTENT_TYPE_HEADER, // Request headers
                Snippets.getJobRequestRequestPayload(), // Request Fields
                Snippets.LOCATION_HEADER // Response Headers
        );

        result = this.mvc
                .perform(MockMvcRequestBuilders.post(JOBS_API).contentType(MediaType.APPLICATION_JSON)
                        .content(this.objectMapper.writeValueAsBytes(jobRequest)))
                .andExpect(MockMvcResultMatchers.status().isAccepted())
                .andExpect(MockMvcResultMatchers.header().string(HttpHeaders.LOCATION, Matchers.notNullValue()))
                .andDo(createResultHandler).andReturn();
    }

    return this.getIdFromLocation(result.getResponse().getHeader(HttpHeaders.LOCATION));
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@SuppressWarnings("unchecked")
@Override//from  w  w  w  .  ja  v  a  2s .co m
public Map<String, Object> loginForClient(String username, String password, String clientId,
        UriComponents inUrlComponents) {
    final Map<String, Object> responsePayload = new HashMap<String, Object>();

    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());

    // login for csrf
    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("login").build();

    ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.GET, null, headers,
            String.class);

    final List<String> cookies = new ArrayList<String>();
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", username);
    formData.add("password", password);
    formData.add(CSRF, getCsrf(cookies));

    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));
    headers.add(HttpHeaders.REFERER, loginUri.toUriString());

    // login.do
    response = exchangeForType(uriBuilder.cloneBuilder().pathSegment("login.do").build().toUriString(),
            HttpMethod.POST, formData, headers, String.class);

    if (response.getStatusCode() != HttpStatus.FOUND
            || response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("login")) {
        responsePayload.put("error", "bad credentials");
        return responsePayload;
    }

    removeCookie(cookies, "X-Uaa-Csrf");
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));
    removeExpiredCookies(cookies);
    headers.remove(HttpHeaders.REFERER);
    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));

    // authorize
    final ResponseEntity<JsonNode> authResponse = exchangeForType(
            uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
                    .queryParam("response_type", "code").queryParam("client_id", clientId)
                    .queryParam("redirect_uri", inUrlComponents.toUriString()).build().toUriString(),
            HttpMethod.GET, null, headers, JsonNode.class);

    if (authResponse.getStatusCode() == HttpStatus.OK) {
        removeCookie(cookies, "X-Uaa-Csrf");
        cookies.addAll(authResponse.getHeaders().get(HttpHeaders.SET_COOKIE));
        // return approval data
        final List<HttpCookie> parsedCookies = new ArrayList<HttpCookie>();

        for (final String cookie : cookies) {
            parsedCookies.add(HttpCookie.parse(cookie).get(0));
        }

        responsePayload.put(HttpHeaders.SET_COOKIE, new ArrayList<String>());

        for (final HttpCookie parsedCookie : parsedCookies) {
            if (!parsedCookie.getName().startsWith("Saved-Account")) {
                parsedCookie.setPath(inUrlComponents.getPath());
                ((List<String>) responsePayload.get(HttpHeaders.SET_COOKIE))
                        .add(httpCookieToString(parsedCookie));
            }
        }

        responsePayload.put("json", authResponse.getBody());
    } else {
        // get auth_code from Location Header
        responsePayload.put("code", authResponse.getHeaders().getLocation().getQuery().split("=")[1]);
    }

    return responsePayload;
}

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

private String submitJob(final int documentationId, final JobRequest jobRequest,
        @Nullable final List<MockMultipartFile> attachments) throws Exception {
    if (attachments != null) {
        final RestDocumentationFilter createResultFilter = RestAssuredRestDocumentation.document(
                "{class-name}/" + documentationId + "/submitJobWithAttachments/",
                HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                        .description(MediaType.MULTIPART_FORM_DATA_VALUE)), // Request headers
                RequestDocumentation.requestParts(
                        RequestDocumentation.partWithName("request").description(
                                "The job request JSON. Content type must be application/json for part"),
                        RequestDocumentation.partWithName("attachment").description(
                                "An attachment file. There can be multiple. Type should be octet-stream")), // Request parts
                Snippets.LOCATION_HEADER // Response Headers
        );//w  ww  .  j a v  a2  s.  com

        final RequestSpecification jobRequestSpecification = RestAssured.given(this.getRequestSpecification())
                .filter(createResultFilter).contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
                .multiPart("request", GenieObjectMapper.getMapper().writeValueAsString(jobRequest),
                        MediaType.APPLICATION_JSON_VALUE);

        for (final MockMultipartFile attachment : attachments) {
            jobRequestSpecification.multiPart("attachment", attachment.getOriginalFilename(),
                    attachment.getBytes(), MediaType.APPLICATION_OCTET_STREAM_VALUE);
        }

        return this.getIdFromLocation(jobRequestSpecification.when().port(this.port).post(JOBS_API).then()
                .statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
                .header(HttpHeaders.LOCATION, Matchers.notNullValue()).extract().header(HttpHeaders.LOCATION));
    } else {
        // Use regular POST
        final RestDocumentationFilter createResultFilter = RestAssuredRestDocumentation.document(
                "{class-name}/" + documentationId + "/submitJobWithoutAttachments/",
                Snippets.CONTENT_TYPE_HEADER, // Request headers
                Snippets.getJobRequestRequestPayload(), // Request Fields
                Snippets.LOCATION_HEADER // Response Headers
        );

        return this.getIdFromLocation(RestAssured.given(this.getRequestSpecification())
                .filter(createResultFilter).contentType(MediaType.APPLICATION_JSON_VALUE)
                .body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest)).when().port(this.port)
                .post(JOBS_API).then().statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
                .header(HttpHeaders.LOCATION, Matchers.notNullValue()).extract().header(HttpHeaders.LOCATION));
    }
}

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

/**
 * Test the job submit method for when the job is killed by sending a DELETE HTTP call.
 *
 * @throws Exception If there is a problem.
 *///from  ww  w. j  av a 2  s  .  c o  m
@Test
public void testSubmitJobMethodKill() throws Exception {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
    final List<String> commandArgs = Lists.newArrayList("-c", "'sleep 60'");

    final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
    final Set<String> clusterTags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
    final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
    clusterCriteriaList.add(clusterCriteria);

    final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
    final JobRequest jobRequest = new JobRequest.Builder(JOB_NAME, JOB_USER, JOB_VERSION, clusterCriteriaList,
            commandCriteria).withCommandArgs(commandArgs).withDisableLogArchival(true).build();

    final String jobId = this.getIdFromLocation(RestAssured.given(this.getRequestSpecification())
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest)).when().port(this.port)
            .post(JOBS_API).then().statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
            .header(HttpHeaders.LOCATION, Matchers.notNullValue()).extract().header(HttpHeaders.LOCATION));

    this.waitForRunning(jobId);

    // Make sure we can get output for a running job
    RestAssured.given(this.getRequestSpecification()).accept(MediaType.APPLICATION_JSON_VALUE).when()
            .port(this.port).get(JOBS_API + "/{id}/output/{filePath}", jobId, "").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.equalToIgnoringCase(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .body("parent", Matchers.isEmptyOrNullString()).body("directories[0].name", Matchers.is("genie/"))
            .body("files[0].name", Matchers.is("run")).body("files[1].name", Matchers.is("stderr"))
            .body("files[2].name", Matchers.is("stdout"));

    RestAssured.given(this.getRequestSpecification()).when().port(this.port)
            .get(JOBS_API + "/{id}/output/{filePath}", jobId, "stdout").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.containsString(ContentType.TEXT.toString()));

    // Let it run for a couple of seconds
    Thread.sleep(2000);

    // Send a kill request to the job.
    final RestDocumentationFilter killResultFilter = RestAssuredRestDocumentation
            .document("{class-name}/killJob/", Snippets.ID_PATH_PARAM);

    RestAssured.given(this.getRequestSpecification()).filter(killResultFilter).when().port(this.port)
            .delete(JOBS_API + "/{id}", jobId).then().statusCode(Matchers.is(HttpStatus.ACCEPTED.value()));

    this.waitForDone(jobId);

    RestAssured.given(this.getRequestSpecification()).when().port(this.port).get(JOBS_API + "/{id}", jobId)
            .then().statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.is(MediaTypes.HAL_JSON_UTF8_VALUE)).body(ID_PATH, Matchers.is(jobId))
            .body(STATUS_PATH, Matchers.is(JobStatus.KILLED.toString()))
            .body(STATUS_MESSAGE_PATH, Matchers.is(JobStatusMessages.JOB_KILLED_BY_USER));

    // Kill the job again to make sure it doesn't cause a problem.
    RestAssured.given(this.getRequestSpecification()).filter(killResultFilter).when().port(this.port)
            .delete(JOBS_API + "/{id}", jobId).then().statusCode(Matchers.is(HttpStatus.ACCEPTED.value()));
}