Example usage for org.springframework.http MediaType MULTIPART_FORM_DATA_VALUE

List of usage examples for org.springframework.http MediaType MULTIPART_FORM_DATA_VALUE

Introduction

In this page you can find the example usage for org.springframework.http MediaType MULTIPART_FORM_DATA_VALUE.

Prototype

String MULTIPART_FORM_DATA_VALUE

To view the source code for org.springframework.http MediaType MULTIPART_FORM_DATA_VALUE.

Click Source Link

Document

A String equivalent of MediaType#MULTIPART_FORM_DATA .

Usage

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.  j  av 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.traffitruck.web.HtmlController.java

@RequestMapping(value = "/newTruck", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ModelAndView newTruck(@RequestParam("licensePlateNumber") String licensePlateNumber,
        @RequestParam("truckPhoto") byte[] truckPhoto,
        @RequestParam("vehicleLicensePhoto") byte[] vehicleLicensePhoto,
        @RequestParam("driverLicensePhoto") byte[] driverLicensePhoto) throws IOException {

    Truck truck = new Truck();
    truck.setLicensePlateNumber(licensePlateNumber);
    truck.setVehicleLicensePhoto(new Binary(vehicleLicensePhoto));
    truck.setDriverLicensePhoto(new Binary(driverLicensePhoto));
    truck.setTruckPhoto(new Binary(truckPhoto));
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    truck.setUsername(username);//  ww w  .j av a  2 s.co m
    truck.setCreationDate(new Date());
    truck.setRegistrationStatus(TruckRegistrationStatus.REGISTERED);
    try {
        dao.storeTruck(truck);
    } catch (DuplicateException e) {
        Map<String, Object> model = new HashMap<>();
        model.put("error", "dup");
        return new ModelAndView("new_truck", model);
    }
    return new ModelAndView("redirect:/myTrucks");
}

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

/**
 * Submit a new job with attachments.// ww  w.ja  v  a2s .  c o  m
 *
 * @param jobRequest         The job request information
 * @param attachments        The attachments for the job
 * @param clientHost         client host sending the request
 * @param userAgent          The user agent string
 * @param httpServletRequest The http servlet request
 * @return The submitted job
 * @throws GenieException For any error
 */
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseStatus(HttpStatus.ACCEPTED)
public ResponseEntity<Void> submitJob(@Valid @RequestPart("request") final JobRequest jobRequest,
        @RequestPart("attachment") final MultipartFile[] attachments,
        @RequestHeader(value = FORWARDED_FOR_HEADER, required = false) final String clientHost,
        @RequestHeader(value = HttpHeaders.USER_AGENT, required = false) final String userAgent,
        final HttpServletRequest httpServletRequest) throws GenieException {
    log.info("[submitJob] Called multipart method to submit job: {}", jobRequest);
    this.submitJobWithAttachmentsRate.increment();
    return this.handleSubmitJob(jobRequest, attachments, clientHost, userAgent, httpServletRequest);
}

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
        );/*  ww  w.  ja  v  a 2s.c o 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.photon.phresco.service.rest.api.AdminService.java

@ApiOperation(value = "Get customer icon by given customerid")
@ApiErrors(value = { @ApiError(code = 204, reason = "Icon not found") })
@RequestMapping(value = REST_API_ICON, produces = MediaType.MULTIPART_FORM_DATA_VALUE, method = RequestMethod.GET)
public @ResponseBody byte[] getIcon(HttpServletResponse response,
        @ApiParam(value = "The Id of the customer to get icon", name = REST_QUERY_CUSTOMERID) @QueryParam(REST_QUERY_CUSTOMERID) String customerId,
        @ApiParam(value = "The context of the customer to get icon", name = "Context") @QueryParam("context") String context,
        @ApiParam(value = "Request for favicon", name = "favIcon") @QueryParam("favIcon") String favIcon,
        @ApiParam(value = "Request for loginIcon", name = "loginIcon") @QueryParam("loginIcon") String loginIcon)
        throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entered into AdminService.getIcon(String id)");
    }/*from  w  ww. j  a va  2s .  c o  m*/
    boolean isFavIcon = Boolean.valueOf(favIcon);
    boolean isLogIcon = Boolean.valueOf(loginIcon);
    byte[] byteArray = null;
    InputStream iconStream = null;
    CustomerDAO customerDAO = null;
    List<Customer> customers = new ArrayList<Customer>();

    customers = findCustomersFromDB();
    if (StringUtils.isNotEmpty(context)) {
        customerDAO = DbService.getMongoOperation().findOne(CUSTOMERS_COLLECTION_NAME,
                new Query(Criteria.where("context").is(context)), CustomerDAO.class);
    } else if (StringUtils.isNotEmpty(customerId)) {
        customerDAO = DbService.getMongoOperation().findOne(CUSTOMERS_COLLECTION_NAME,
                new Query(Criteria.whereId().is(customerId)), CustomerDAO.class);
    } else if (customers.size() == 2) {
        for (Customer customer : customers) {
            if (!customer.getName().equals("Photon")) {
                customerDAO = DbService.getMongoOperation().findOne(CUSTOMERS_COLLECTION_NAME,
                        new Query(Criteria.whereId().is(customer.getId())), CustomerDAO.class);
            }
        }
    }
    Converter<CustomerDAO, Customer> converter = (Converter<CustomerDAO, Customer>) ConvertersFactory
            .getConverter(CustomerDAO.class);
    for (Customer customer : customers) {
        if (StringUtils.isNotEmpty(context) && !customer.getContext().equalsIgnoreCase(context)) {
            response.setStatus(204);
        }
    }
    if (customerDAO == null) {
        return byteArray;
    }
    Customer customer = converter.convertDAOToObject(customerDAO, DbService.getMongoOperation());
    String repourl = customer.getRepoInfo().getGroupRepoURL();
    String artifactId = filterString(customer.getName());
    if (isFavIcon) {
        artifactId = artifactId + "favIcon";
    } else if (isLogIcon) {
        artifactId = artifactId + "icon";
    }
    String contentURL = ServerUtil.createContentURL("customers", artifactId, "1.0", "png");
    try {
        URL url = new URL(repourl + "/" + contentURL);
        iconStream = url.openStream();
    } catch (MalformedURLException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        iconStream = null;
    }
    if (iconStream == null) {
        byte[] icon = getIcon(response, "photon", "photon", favIcon, loginIcon);
        if (icon != null) {
            return icon;
        } else {
            response.setStatus(204);
            return null;
        }
    }
    try {
        byteArray = IOUtils.toByteArray(iconStream);
    } catch (IOException e) {
    }
    response.setStatus(200);
    return byteArray;
}

From source file:com.photon.phresco.service.rest.api.AdminService.java

/**
 * Creates the list of customers//from  w w w .j a  v a  2  s  .  c o m
 * @param customer
 * @return 
 * @throws IOException 
 */
@ApiOperation(value = " Creates a new customer ")
@ApiErrors(value = { @ApiError(code = 500, reason = "Failed to create") })
@RequestMapping(value = REST_API_CUSTOMERS, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE,
        MediaType.APPLICATION_JSON_VALUE,
        "multipart/mixed" }, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public @ResponseBody void createCustomer(MultipartHttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "customer", required = false) byte[] customerData) throws IOException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entered into AdminService.createCustomer(List<Customer> customer)");
    }
    Customer customer = new Gson().fromJson(new String(customerData), Customer.class);
    saveCustomer(response, request, customer);
}

From source file:com.photon.phresco.service.rest.api.AdminService.java

/**
 * Updates the list of customers/*  w  w w  . j a va  2  s .co  m*/
 * @param customers
 * @return
 * @throws IOException 
 */
@ApiOperation(value = " Creates a new customer ")
@ApiErrors(value = { @ApiError(code = 500, reason = "Failed to update") })
@RequestMapping(value = REST_API_CUSTOMERS, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE,
        MediaType.APPLICATION_JSON_VALUE,
        "multipart/mixed" }, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.PUT)
public @ResponseBody void updateCustomer(HttpServletResponse response,
        MultipartHttpServletRequest multipartHttpServletRequest,
        @RequestParam(value = "customer", required = false) byte[] customerData) throws IOException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entered into AdminService.updateCustomer(List<Customer> customers)");
    }
    Customer customer = new Gson().fromJson(new String(customerData), Customer.class);
    saveCustomer(response, multipartHttpServletRequest, customer);
}

From source file:com.photon.phresco.service.rest.api.ComponentService.java

/**
 * Creates the list of technologies//from www  .ja va  2  s .co  m
 * @param technologies
 * @throws IOException 
 * @throws PhrescoException 
 */
@ApiOperation(value = " Creates technology ")
@ApiErrors(value = { @ApiError(code = 500, reason = "Unable to create technology") })
@RequestMapping(value = REST_API_TECHNOLOGIES, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE,
        MediaType.APPLICATION_JSON_VALUE,
        "multipart/mixed" }, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public @ResponseBody void createTechnologies(MultipartHttpServletRequest request, HttpServletResponse response,
        @RequestParam("technology") byte[] techJson) throws PhrescoException, IOException {
    if (isDebugEnabled) {
        LOGGER.debug("ComponentService.createTechnologies");
        LOGGER.debug("ComponentService.createTechnologies", "remoteAddress=" + request.getRemoteAddr(),
                "endpoint=" + request.getRequestURI(), "user=" + request.getParameter("userId"));
    }
    createOrUpdateTechnology(request, techJson);
}

From source file:com.photon.phresco.service.rest.api.ComponentService.java

/**
 * Updates the list of technologies//from  w w  w  .ja  va 2s  . c o  m
 * @param technologies
 * @return
  * @throws PhrescoException 
 * @throws IOException 
 */
@ApiOperation(value = " Updates technology ")
@ApiErrors(value = { @ApiError(code = 500, reason = "Unable to update technology") })
@RequestMapping(value = REST_API_TECHNOLOGIES, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE,
        MediaType.APPLICATION_JSON_VALUE,
        "multipart/mixed" }, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.PUT)
public void updateTechnologies(MultipartHttpServletRequest request, HttpServletResponse response,
        @RequestParam("technology") byte[] techJson) throws PhrescoException, IOException {
    if (isDebugEnabled) {
        LOGGER.debug("ComponentService.updateTechnologies : Entry");
        LOGGER.debug("ComponentService.createTechnologies", "remoteAddress=" + request.getRemoteAddr(),
                "endpoint=" + request.getRequestURI(), "user=" + request.getParameter("userId"));
    }
    createOrUpdateTechnology(request, techJson);
}

From source file:com.photon.phresco.service.rest.api.ComponentService.java

/**
 * Creates the list of modules//w w w. j  ava  2s.  co m
 * @param modules
 * @return 
 * @return 
 * @throws PhrescoException 
 * @throws IOException 
 */
@ApiOperation(value = " Creates new features ")
@ApiErrors(value = { @ApiError(code = 500, reason = "Feature creation failed") })
@RequestMapping(value = REST_API_MODULES, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE,
        MediaType.APPLICATION_JSON_VALUE,
        "multipart/mixed" }, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public @ResponseBody ArtifactGroup createModules(HttpServletResponse response,
        MultipartHttpServletRequest request,
        @RequestPart(value = "feature", required = false) ByteArrayResource moduleFile,
        @RequestPart(value = "icon", required = false) ByteArrayResource iconFile,
        @RequestParam("moduleGroup") byte[] artifactGroupData) throws PhrescoException, IOException {
    if (isDebugEnabled) {
        LOGGER.debug("ComponentService.createModules : Entry");
        LOGGER.debug("ComponentService.findModules", "remoteAddress=" + request.getRemoteAddr(),
                "endpoint=" + request.getRequestURI(), "user=" + request.getParameter("userId"));
    }
    String string = new String(artifactGroupData);
    ArtifactGroup artifactGroup = new Gson().fromJson(string, ArtifactGroup.class);
    if (moduleFile != null) {
        boolean saveArtifactFile = saveArtifactFile(artifactGroup, moduleFile.getByteArray());
        if (!saveArtifactFile) {
            throw new PhrescoException("Unable to create artifact");
        }
    }
    if (iconFile != null) {
        //artifactGroup.setPackaging(ICON_EXT);
        boolean saveArtifactIcon = saveArtifactIcon(artifactGroup, iconFile.getByteArray(), ICON_EXT);
        if (!saveArtifactIcon) {
            throw new PhrescoException("Unable to create artifact");
        }
    }
    saveModuleGroup(artifactGroup);
    return artifactGroup;
}