List of usage examples for org.springframework.http HttpHeaders CONTENT_TYPE
String CONTENT_TYPE
To view the source code for org.springframework.http HttpHeaders CONTENT_TYPE.
Click Source Link
From source file:io.syndesis.runtime.action.DynamicActionDefinitionITCase.java
@Test public void shouldOfferDynamicActionPropertySuggestions() { final HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); final ResponseEntity<ActionDefinition> firstResponse = http(HttpMethod.POST, "/api/v1/connections/" + connectionId + "/actions/" + CREATE_OR_UPDATE_ACTION_ID, null, ActionDefinition.class, tokenRule.validToken(), headers, HttpStatus.OK); final ActionDefinition firstEnrichment = new ActionDefinition.Builder()// .inputDataShape(new DataShape.Builder().kind("json-schema").build()) .outputDataShape(new DataShape.Builder().kind("java") .type("org.apache.camel.component.salesforce.api.dto.CreateSObjectResult").build()) .withActionDefinitionStep("Select Salesforce object", "Select Salesforce object type to create", b -> b.putProperty("sObjectName", suggestedSalesforceObjectNames)) .withActionDefinitionStep("Select Identifier property", "Select Salesforce property that will hold the uniquely identifying value of this object", b -> b.putProperty("sObjectIdName", _DEFAULT_SALESFORCE_IDENTIFIER)) .build();/* w w w . j a v a2 s. co m*/ assertThat(firstResponse.getBody()).isEqualTo(firstEnrichment); final ResponseEntity<ActionDefinition> secondResponse = http(HttpMethod.POST, "/api/v1/connections/" + connectionId + "/actions/" + CREATE_OR_UPDATE_ACTION_ID, Collections.singletonMap("sObjectName", "Contact"), ActionDefinition.class, tokenRule.validToken(), headers, HttpStatus.OK); final ActionDefinition secondEnrichment = new ActionDefinition.Builder()// .outputDataShape(new DataShape.Builder().kind("java") .type("org.apache.camel.component.salesforce.api.dto.CreateSObjectResult").build()) .withActionDefinitionStep("Select Salesforce object", "Select Salesforce object type to create", b -> b.putProperty("sObjectName", contactSalesforceObjectName)) .withActionDefinitionStep("Select Identifier property", "Select Salesforce property that will hold the uniquely identifying value of this object", b -> b.putProperty("sObjectIdName", suggestedSalesforceIdNames)) .build(); final ActionDefinition secondResponseBody = secondResponse.getBody(); assertThat(secondResponseBody).isEqualToIgnoringGivenFields(secondEnrichment, "inputDataShape"); assertThat(secondResponseBody.getInputDataShape()).hasValueSatisfying(input -> { assertThat(input.getKind()).isEqualTo("json-schema"); assertThat(input.getType()).isEqualTo("Contact"); assertThat(input.getSpecification()).isNotEmpty(); }); }
From source file:access.deploy.Deployer.java
/** * Deploys a GeoTIFF resource to GeoServer. This will create a new GeoServer data store and layer. This will upload * the file directly to GeoServer using the GeoServer REST API. * /*from www .j a v a 2 s. c o m*/ * @param dataResource * The DataResource to deploy. * @return The Deployment * @throws InvalidInputException * @throws IOException * @throws AmazonClientException */ private Deployment deployRaster(DataResource dataResource) throws GeoServerException, IOException, InvalidInputException { // Get the File Bytes of the Raster to be uploaded byte[] fileBytes = accessUtilities.getBytesForDataResource(dataResource); // Create the Request that will upload the File authHeaders.add(HttpHeaders.CONTENT_TYPE, "image/tiff"); HttpEntity<byte[]> request = new HttpEntity<>(fileBytes, authHeaders.get()); // Send the Request String url = String.format("%s/rest/workspaces/piazza/coveragestores/%s/file.geotiff", accessUtilities.getGeoServerBaseUrl(), dataResource.getDataId()); try { pzLogger.log(String.format("Creating new Raster Deployment to %s", url), Severity.INFORMATIONAL, new AuditElement(ACCESS, "deployGeoServerRasterLayer", dataResource.getDataId())); restTemplate.exchange(url, HttpMethod.PUT, request, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { if (exception.getStatusCode() == HttpStatus.METHOD_NOT_ALLOWED) { // If 405 NOT ALLOWED is encountered, then the layer may already exist on the GeoServer. Check if it // exists already. If it does, then use this layer for the Deployment. if (!doesGeoServerLayerExist(dataResource.getDataId())) { // If it doesn't exist, throw an error. Something went wrong. String error = String.format( "GeoServer would not allow for layer creation, despite an existing layer not being present: url: %s, statusCode: %s, exceptionBody: %s", url, exception.getStatusCode().toString(), exception.getResponseBodyAsString()); pzLogger.log(error, Severity.ERROR); LOGGER.error(error, exception); throw new GeoServerException(error); } } else if ((exception.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) && (exception.getResponseBodyAsString().contains("Error persisting"))) { // If a 500 is received, then it's possible that GeoServer is processing this layer already via a // simultaneous POST, and there is a collision. Add this information to the response. // TODO: In the future, we should persist a lookup table where only one Data ID is persisted at a time // to GeoServer, to avoid this collision. String error = String.format( "Creating Layer on GeoServer at URL %s returned HTTP Status %s with Body: %s. This may be the result of GeoServer processing this Data Id simultaneously by another request. Please try again.", url, exception.getStatusCode().toString(), exception.getResponseBodyAsString()); pzLogger.log(error, Severity.ERROR, new AuditElement(ACCESS, "failedToDeployRaster", dataResource.getDataId())); LOGGER.error(error, exception); throw new GeoServerException(error); } else { // For any other errors, report back this error to the user and fail the job. String error = String.format( "Creating Layer on GeoServer at URL %s returned HTTP Status %s with Body: %s", url, exception.getStatusCode().toString(), exception.getResponseBodyAsString()); pzLogger.log(error, Severity.ERROR, new AuditElement(ACCESS, "failedToDeployRaster", dataResource.getDataId())); LOGGER.error(error, exception); throw new GeoServerException(error); } } // Create a Deployment for this Resource String deploymentId = uuidFactory.getUUID(); String capabilitiesUrl = String.format("%s%s", accessUtilities.getGeoServerBaseUrl(), CAPABILITIES_URL); String deploymentLayerName = dataResource.getDataId(); return new Deployment(deploymentId, dataResource.getDataId(), accessUtilities.getGeoServerBaseUrl(), null, deploymentLayerName, capabilitiesUrl); }
From source file:com.github.zhanhb.ckfinder.download.PathPartial.java
/** * Copy the contents of the specified input stream to the specified output * stream, and ensure that both streams are closed before returning (even in * the face of an exception)./*from w ww .j ava 2s. c o m*/ * * @param path The cache entry for the source resource * @param ostream The output stream to write to * @param ranges Enumeration of the ranges the client wanted to retrieve * @param contentType Content type of the resource * @param buffer buffer to copy the resource * @exception IOException if an input/output error occurs */ private void copy(Path path, ServletOutputStream ostream, Range[] ranges, String contentType, byte[] buffer) throws IOException { IOException exception = null; for (Range currentRange : ranges) { try (InputStream stream = Files.newInputStream(path)) { // Writing MIME header. ostream.println(); ostream.println("--" + MIME_SEPARATION); if (contentType != null) { ostream.println(HttpHeaders.CONTENT_TYPE + ": " + contentType); } ostream.println(HttpHeaders.CONTENT_RANGE + ": " + currentRange); ostream.println(); // Printing content copyRange(stream, ostream, currentRange, buffer); } catch (IOException ex) { exception = ex; } } ostream.println(); ostream.print("--" + MIME_SEPARATION + "--"); if (exception != null) { throw exception; } }
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 www. jav a 2 s . com 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.netflix.genie.web.controllers.JobRestControllerUnitTests.java
/** * Make sure directory forwarding happens when all conditions are met. * * @throws IOException on error/* w w w . j a v a2 s . c om*/ * @throws ServletException on error * @throws GenieException on error */ @Test public void canHandleForwardJobOutputRequestWithSuccess() throws IOException, ServletException, GenieException { this.jobsProperties.getForwarding().setEnabled(true); final String jobId = UUID.randomUUID().toString(); final String forwardedFrom = null; final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response); final String jobHostName = UUID.randomUUID().toString(); Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName); //Mock parts of the http request final String http = "http"; Mockito.when(request.getScheme()).thenReturn(http); final int port = 8080; Mockito.when(request.getServerPort()).thenReturn(port); final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString(); Mockito.when(request.getRequestURI()).thenReturn(requestURI); final Set<String> headerNames = Sets.newHashSet(HttpHeaders.ACCEPT); Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerNames)); Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON_VALUE); final String requestUrl = UUID.randomUUID().toString(); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl)); //Mock parts of forward response final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class); final StatusLine statusLine = Mockito.mock(StatusLine.class); Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine); final int successCode = 200; Mockito.when(statusLine.getStatusCode()).thenReturn(successCode); final Header contentTypeHeader = Mockito.mock(Header.class); Mockito.when(contentTypeHeader.getName()).thenReturn(HttpHeaders.CONTENT_TYPE); Mockito.when(contentTypeHeader.getValue()).thenReturn(MediaType.TEXT_PLAIN_VALUE); Mockito.when(forwardResponse.getAllHeaders()).thenReturn(new Header[] { contentTypeHeader }); final String text = UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString(); final ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes(UTF_8)); final HttpEntity entity = Mockito.mock(HttpEntity.class); Mockito.when(entity.getContent()).thenReturn(bis); Mockito.when(forwardResponse.getEntity()).thenReturn(entity); final ByteArrayServletOutputStream bos = new ByteArrayServletOutputStream(); Mockito.when(response.getOutputStream()).thenReturn(bos); final ClientHttpRequestFactory factory = Mockito.mock(ClientHttpRequestFactory.class); final ClientHttpRequest clientHttpRequest = Mockito.mock(ClientHttpRequest.class); Mockito.when(clientHttpRequest.execute()) .thenReturn(new MockClientHttpResponse(text.getBytes(UTF_8), HttpStatus.OK)); Mockito.when(clientHttpRequest.getHeaders()).thenReturn(new HttpHeaders()); Mockito.when(factory.createRequest(Mockito.any(), Mockito.any())).thenReturn(clientHttpRequest); final RestTemplate template = new RestTemplate(factory); final Registry registry = Mockito.mock(Registry.class); final Counter counter = Mockito.mock(Counter.class); Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter); final JobRestController jobController = new JobRestController(Mockito.mock(JobCoordinatorService.class), this.jobSearchService, Mockito.mock(AttachmentService.class), Mockito.mock(ApplicationResourceAssembler.class), Mockito.mock(ClusterResourceAssembler.class), Mockito.mock(CommandResourceAssembler.class), Mockito.mock(JobResourceAssembler.class), Mockito.mock(JobRequestResourceAssembler.class), Mockito.mock(JobExecutionResourceAssembler.class), Mockito.mock(JobSearchResultResourceAssembler.class), this.hostname, template, this.genieResourceHttpRequestHandler, this.jobsProperties, registry); jobController.getJobOutput(jobId, forwardedFrom, request, response); Assert.assertThat(new String(bos.toByteArray(), UTF_8), Matchers.is(text)); Mockito.verify(request, Mockito.times(1)).getHeader(HttpHeaders.ACCEPT); Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId)); Mockito.verify(response, Mockito.never()).sendError(Mockito.anyInt()); Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response); }
From source file:eu.freme.broker.eservices.Pipelines.java
private ResponseEntity<String> createOKJSONResponse(final String contents) { MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, RDFConstants.RDFSerialization.JSON.contentType()); return new ResponseEntity<>(contents, headers, HttpStatus.OK); }
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 );/*from w w w . ja v a 2s . co m*/ 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
private void checkJobOutput(final int documentationId, final String id) throws Exception { // Check getting a directory as json final RestDocumentationFilter jsonResultFilter = RestAssuredRestDocumentation.document( "{class-name}/" + documentationId + "/getJobOutput/json/", Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath") .description("The path to the directory to get").optional()), // Path parameters HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT) .description(MediaType.APPLICATION_JSON_VALUE).optional()), // Request header HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE) .description(MediaType.APPLICATION_JSON_VALUE)), // Response Headers Snippets.OUTPUT_DIRECTORY_FIELDS); RestAssured.given(this.getRequestSpecification()).filter(jsonResultFilter) .accept(MediaType.APPLICATION_JSON_VALUE).when().port(this.port) .get(JOBS_API + "/{id}/output/{filePath}", id, "").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("config1")).body("files[1].name", Matchers.is("dep1")) .body("files[2].name", Matchers.is("jobsetupfile")).body("files[3].name", Matchers.is("run")) .body("files[4].name", Matchers.is("stderr")).body("files[5].name", Matchers.is("stdout")); // Check getting a directory as HTML final RestDocumentationFilter htmlResultFilter = RestAssuredRestDocumentation.document( "{class-name}/" + documentationId + "/getJobOutput/html/", Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath") .description("The path to the directory to get").optional()), // Path parameters HeaderDocumentation.requestHeaders( HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT).description(MediaType.TEXT_HTML)), // Request header HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE) .description(MediaType.TEXT_HTML)) // Response Headers );/*from w w w. j ava 2s. c o m*/ RestAssured.given(this.getRequestSpecification()).filter(htmlResultFilter).accept(MediaType.TEXT_HTML_VALUE) .when().port(this.port).get(JOBS_API + "/{id}/output/{filePath}", id, "").then() .statusCode(Matchers.is(HttpStatus.OK.value())) .contentType(Matchers.containsString(MediaType.TEXT_HTML_VALUE)); // Check getting a file final RestDocumentationFilter fileResultFilter = RestAssuredRestDocumentation.document( "{class-name}/" + documentationId + "/getJobOutput/file/", Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath") .description("The path to the file to get").optional()), // Path parameters HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT) .description(MediaType.ALL_VALUE).optional()), // Request header HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE) .description("The content type of the file being returned").optional()) // Response Headers ); // check that the generated run file is correct final String runShFileName = SystemUtils.IS_OS_LINUX ? "linux-runsh.txt" : "non-linux-runsh.txt"; final String runShFile = this.resourceLoader.getResource(BASE_DIR + runShFileName).getFile() .getAbsolutePath(); final String runFileContents = new String(Files.readAllBytes(Paths.get(runShFile)), StandardCharsets.UTF_8); final String jobWorkingDir = this.jobDirResource.getFile().getCanonicalPath() + FILE_DELIMITER + id; final String expectedRunScriptContent = this.getExpectedRunContents(runFileContents, jobWorkingDir, id); RestAssured.given(this.getRequestSpecification()).filter(fileResultFilter).when().port(this.port) .get(JOBS_API + "/{id}/output/{filePath}", id, "run").then() .statusCode(Matchers.is(HttpStatus.OK.value())).body(Matchers.is(expectedRunScriptContent)); }