Example usage for org.springframework.http MediaType APPLICATION_XML_VALUE

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

Introduction

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

Prototype

String APPLICATION_XML_VALUE

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

Click Source Link

Document

A String equivalent of MediaType#APPLICATION_XML .

Usage

From source file:de.hybris.platform.ycommercewebservices.v2.controller.UsersController.java

/**
 * Updates existing customer's credit card payment details by it's ID. Only attributes given in request body will be
 * changed.// ww w  .  j  ava 2s .com
 * 
 * @param paymentDetails
 *           payment details object
 * @bodyparams 
 *             accountHolderName,cardNumber,cardType,issueNumber,startMonth,expiryMonth,startYear,expiryYear,subscriptionId
 *             ,defaultPaymentInfo,saved,billingAddress(firstName,lastName,titleCode,line1,line2,town,postalCode,
 *             region(isocode),country(isocode),defaultAddress)
 * @throws RequestParameterException
 * @throws WebserviceValidationException
 */
@Secured({ "ROLE_CUSTOMERGROUP", "ROLE_TRUSTED_CLIENT", "ROLE_CUSTOMERMANAGERGROUP" })
@RequestMapping(value = "/{userId}/paymentdetails/{paymentDetailsId}", method = RequestMethod.PATCH, consumes = {
        MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseStatus(HttpStatus.OK)
public void updatePaymentInfo(@PathVariable final String paymentDetailsId,
        @RequestBody final PaymentDetailsWsDTO paymentDetails) throws RequestParameterException {
    final CCPaymentInfoData paymentInfoData;
    try {
        paymentInfoData = userFacade.getCCPaymentInfoForCode(paymentDetailsId);
    } catch (final PK.PKException ex) {
        throw new RequestParameterException("Payment details [" + paymentDetailsId + "] not found.",
                RequestParameterException.UNKNOWN_IDENTIFIER, "paymentDetailsId", ex);
    }

    final boolean isAlreadyDefaultPaymentInfo = paymentInfoData.isDefaultPaymentInfo();

    dataMapper.map(paymentDetails, paymentInfoData,
            "accountHolderName,cardNumber,cardType,issueNumber,startMonth,expiryMonth,startYear,expiryYear,subscriptionId,defaultPaymentInfo,saved,billingAddress(firstName,lastName,titleCode,line1,line2,town,postalCode,region(isocode),country(isocode),defaultAddress)",
            false);
    validate(paymentInfoData, "paymentDetails", ccPaymentInfoValidator);

    userFacade.updateCCPaymentInfo(paymentInfoData);
    if (paymentInfoData.isSaved() && !isAlreadyDefaultPaymentInfo && paymentInfoData.isDefaultPaymentInfo()) {
        userFacade.setDefaultPaymentInfo(paymentInfoData);
    }

}

From source file:de.hybris.platform.ycommercewebservices.v2.controller.UsersController.java

/**
 * Updates existing customer's credit card payment info by payment info ID. Attributes not given in request will be
 * reset (set as null or default)./*  ww  w  . ja v a  2 s. com*/
 * 
 * @param paymentDetails
 *           payment details object
 * @bodyparams 
 *             accountHolderName,cardNumber,cardType,issueNumber,startMonth,expiryMonth,startYear,expiryYear,subscriptionId
 *             ,defaultPaymentInfo,saved,billingAddress(firstName,lastName,titleCode,line1,line2,town,postalCode,
 *             region(isocode),country(isocode),defaultAddress)
 * @throws RequestParameterException
 */
@Secured({ "ROLE_CUSTOMERGROUP", "ROLE_TRUSTED_CLIENT", "ROLE_CUSTOMERMANAGERGROUP" })
@RequestMapping(value = "/{userId}/paymentdetails/{paymentDetailsId}", method = RequestMethod.PUT, consumes = {
        MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseStatus(HttpStatus.OK)
public void putPaymentInfo(@PathVariable final String paymentDetailsId,
        @RequestBody final PaymentDetailsWsDTO paymentDetails) throws RequestParameterException {
    final CCPaymentInfoData paymentInfoData;
    try {
        paymentInfoData = userFacade.getCCPaymentInfoForCode(paymentDetailsId);
    } catch (final PK.PKException ex) {
        throw new RequestParameterException("Payment details [" + paymentDetailsId + "] not found.",
                RequestParameterException.UNKNOWN_IDENTIFIER, "paymentDetailsId", ex);
    }

    final boolean isAlreadyDefaultPaymentInfo = paymentInfoData.isDefaultPaymentInfo();

    validate(paymentDetails, "paymentDetails", paymentDetailsDTOValidator);
    dataMapper.map(paymentDetails, paymentInfoData,
            "accountHolderName,cardNumber,cardType,issueNumber,startMonth,expiryMonth,startYear,expiryYear,subscriptionId,defaultPaymentInfo,saved,billingAddress(firstName,lastName,titleCode,line1,line2,town,postalCode,region(isocode),country(isocode),defaultAddress)",
            true);

    userFacade.updateCCPaymentInfo(paymentInfoData);
    if (paymentInfoData.isSaved() && !isAlreadyDefaultPaymentInfo && paymentInfoData.isDefaultPaymentInfo()) {
        userFacade.setDefaultPaymentInfo(paymentInfoData);
    }
}

From source file:eionet.webq.converter.MultipartFileToUserFileConverterTest.java

private MultipartFile createMultipartFile(byte[] content) {
    return createMultipartFile(MediaType.APPLICATION_XML_VALUE, content);
}

From source file:eionet.webq.web.controller.FileDownloadController.java

/**
 * Convert the user XML file into JSON format and then back to XML format to be able to evaluate the conversion. The method is
 * called when request header Accept content type is text/xml.
 *
 * @param fileId   user file id./*from  w  w  w  .  j  a  va2 s  .  c o  m*/
 * @param request  http request to write file
 * @param response http response to write file
 * @throws FileNotAvailableException user file is not available for given id
 */
@RequestMapping(value = "/converted_user_file", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
@Transactional
public void downloadUserFileJsonToXml(@RequestParam int fileId, HttpServletRequest request,
        HttpServletResponse response) throws FileNotAvailableException {

    UserFile file = userFileHelper.downloadUserFile(fileId, request);

    byte[] xml = jsonXMLConverter.convertJsonToXml(jsonXMLConverter.convertXmlToJson(file.getContent()));

    writeXmlFileToResponse("json.xml", xml, response);
}

From source file:eionet.webq.web.controller.FileDownloadController.java

/**
 * Writes project file to response.//w  ww . j  a  va2s .co m
 *
 * @param name        file name
 * @param projectFile project file object
 * @param response    http response
 * @param disposition inline or attachment
 */
private void writeProjectFileToResponse(String name, ProjectFile projectFile, HttpServletResponse response,
        String disposition, String format) {

    ConfigurableMimeFileTypeMap mimeTypesMap = new ConfigurableMimeFileTypeMap();
    String contentType = mimeTypesMap.getContentType(name);

    // check if default
    if (mimeTypesMap.getContentType("").equals(contentType)) {
        if (name.endsWith(".xhtml")) {
            contentType = MediaType.APPLICATION_XHTML_XML_VALUE;
        } else if (name.endsWith(".js")) {
            contentType = "application/javascript";
        } else if (name.endsWith(".json")) {
            contentType = MediaType.APPLICATION_JSON_VALUE;
        } else {
            contentType = MediaType.APPLICATION_XML_VALUE;
        }
        // TODO check if there are more missing mime types
    }

    byte[] fileContent = projectFile.getFileContent();

    if ("json".equals(format)) {
        fileContent = jsonXMLConverter.convertXmlToJson(projectFile.getFileContent());
        contentType = MediaType.APPLICATION_JSON_VALUE;
        disposition = "inline";
    }

    if (contentType.startsWith("text") || contentType.startsWith("application")) {
        contentType += ";charset=UTF-8";
    }
    response.setContentType(contentType);
    setContentDisposition(response, disposition + ";filename=" + name);
    if (projectFile.getUpdated() != null) {
        response.setDateHeader("Last-Modified", projectFile.getUpdated().getTime());
    } else if (projectFile.getCreated() != null) {
        response.setDateHeader("Last-Modified", projectFile.getCreated().getTime());
    }
    writeToResponse(response, fileContent);
}

From source file:eu.europa.ec.markt.dss.web.controller.SignatureController.java

@RequestMapping(method = RequestMethod.GET, value = "/policy.xml", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody//from w ww. j  ava 2  s.co  m
public String getDefaultPolicyFile() throws IOException {
    InputStream inputStream;
    final String prefDefaultPolicyUrl = preferencesDao.get(PreferenceKey.DEFAULT_POLICY_URL).getValue();
    if (StringUtils.isNotEmpty(prefDefaultPolicyUrl)) {
        inputStream = new URL(prefDefaultPolicyUrl).openStream();
    } else {
        inputStream = getClass()
                .getResourceAsStream(ValidationResourceManager.defaultPolicyConstraintsLocation);
    }
    return IOUtils.toString(inputStream);
}

From source file:org.apache.servicecomb.demo.springmvc.server.CodeFirstSpringmvc.java

@RequestMapping(path = "/appXml", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
public JAXBPerson appXml(@RequestBody JAXBPerson person) {
    return person;
}

From source file:org.cruk.genologics.api.GenologicsAPIPaginatedBatchTest.java

private HttpResponse createMultipageFetchResponse(File responseFile) {
    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE);
    response.setEntity(new HttpEntityForMultipageFetch(responseFile));
    return response;
}

From source file:org.fao.geonet.api.records.editing.MetadataEditingApi.java

@ApiOperation(value = "Edit a record", notes = "Return HTML form for editing.", nickname = "editor")
@RequestMapping(value = "/{metadataUuid}/editor", method = RequestMethod.GET, consumes = {
        MediaType.ALL_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE })
@PreAuthorize("hasRole('Editor')")
@ResponseStatus(HttpStatus.OK)//  www.  j a  v  a 2 s  .c  o  m
@ApiResponses(value = { @ApiResponse(code = 200, message = "The editor form."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_EDIT) })
@ResponseBody
public Element startEditing(
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @ApiParam(value = "Tab") @RequestParam(defaultValue = "simple") String currTab,
        @RequestParam(defaultValue = "false") boolean withAttributes,
        @ApiIgnore @ApiParam(hidden = true) HttpSession session,
        @ApiIgnore @ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams,
        HttpServletRequest request) throws Exception {
    AbstractMetadata metadata = ApiUtils.canEditRecord(metadataUuid, request);

    boolean showValidationErrors = false;
    boolean starteditingsession = true;

    ServiceContext context = ApiUtils.createServiceContext(request);
    ApplicationContext applicationContext = ApplicationContextHolder.get();
    if (starteditingsession) {
        DataManager dm = applicationContext.getBean(DataManager.class);
        dm.startEditingSession(context, String.valueOf(metadata.getId()));
    }

    Element elMd = new AjaxEditUtils(context).getMetadataEmbedded(context, String.valueOf(metadata.getId()),
            true, showValidationErrors);
    return buildEditorForm(currTab, session, allRequestParams, request, metadata.getId(), elMd,
            metadata.getDataInfo().getSchemaId(), showValidationErrors, context, applicationContext, false,
            false);
}

From source file:org.fao.geonet.api.records.editing.MetadataEditingApi.java

@ApiOperation(value = "Save edits", notes = "Save the HTML form content.", nickname = "saveEdits")
@RequestMapping(value = "/{metadataUuid}/editor", method = RequestMethod.POST, consumes = {
        MediaType.ALL_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE })
@PreAuthorize("hasRole('Editor')")
@ResponseStatus(HttpStatus.OK)/*from w  ww. ja  v a2 s .c  o m*/
@ApiResponses(value = { @ApiResponse(code = 200, message = "The editor form."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_EDIT) })
@ResponseBody
public Element saveEdits(
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @ApiParam(value = "Tab") @RequestParam(defaultValue = "simple") String tab,
        @RequestParam(defaultValue = "false") boolean withAttributes,
        @RequestParam(defaultValue = "false") boolean withValidationErrors,
        @RequestParam(defaultValue = "false") boolean minor,
        @ApiParam(value = "Save current edits.") @RequestParam(defaultValue = "false") boolean commit,
        @ApiParam(value = "Save and terminate session.") @RequestParam(defaultValue = "false") boolean terminate,
        @ApiParam(value = "Record as XML. TODO: rename xml") @RequestParam(defaultValue = "") String data,
        @ApiIgnore @ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams,
        HttpServletRequest request, @ApiIgnore @ApiParam(hidden = true) HttpSession httpSession)
        throws Exception {
    AbstractMetadata metadata = ApiUtils.canEditRecord(metadataUuid, request);
    ServiceContext context = ApiUtils.createServiceContext(request);
    AjaxEditUtils ajaxEditUtils = new AjaxEditUtils(context);
    //        ajaxEditUtils.preprocessUpdate(allRequestParams, context);

    ApplicationContext applicationContext = ApplicationContextHolder.get();
    DataManager dataMan = applicationContext.getBean(DataManager.class);
    UserSession session = ApiUtils.getUserSession(httpSession);
    IMetadataValidator validator = applicationContext.getBean(IMetadataValidator.class);
    String id = String.valueOf(metadata.getId());
    String isTemplate = allRequestParams.get(Params.TEMPLATE);
    //        boolean finished = config.getValue(Params.FINISHED, "no").equals("yes");
    //        boolean forget = config.getValue(Params.FORGET, "no").equals("yes");
    //        boolean commit = config.getValue(Params.START_EDITING_SESSION, "no").equals("yes");

    // TODO: Use map only to avoid this conversion
    Element params = new Element("request");
    Map<String, String> forwardedParams = new HashMap<>();
    for (Map.Entry<String, String> e : allRequestParams.entrySet()) {
        params.addContent(new Element(e.getKey()).setText(e.getValue()));
        if (!e.getKey().startsWith("_")) {
            forwardedParams.put(e.getKey(), e.getValue());
        }
    }

    int iLocalId = Integer.parseInt(id);
    dataMan.setTemplateExt(iLocalId, MetadataType.lookup(isTemplate));

    //--- use StatusActionsFactory and StatusActions class to possibly
    //--- change status as a result of this edit (use onEdit method)
    StatusActionsFactory saf = context.getBean(StatusActionsFactory.class);
    StatusActions sa = saf.createStatusActions(context);
    sa.onEdit(iLocalId, minor);
    Element beforeMetadata = dataMan.getMetadata(context, String.valueOf(metadata.getId()), false, false,
            false);

    if (StringUtils.isNotEmpty(data)) {
        Element md = Xml.loadString(data, false);
        String changeDate = null;
        boolean updateDateStamp = !minor;
        boolean ufo = true;
        boolean index = true;
        dataMan.updateMetadata(context, id, md, withValidationErrors, ufo, index, context.getLanguage(),
                changeDate, updateDateStamp);

        XMLOutputter outp = new XMLOutputter();
        String xmlBefore = outp.outputString(beforeMetadata);
        String xmlAfter = outp.outputString(md);
        new RecordUpdatedEvent(Long.parseLong(id), session.getUserIdAsInt(), xmlBefore, xmlAfter)
                .publish(applicationContext);
    } else {
        ajaxEditUtils.updateContent(params, false, true);

        Element afterMetadata = dataMan.getMetadata(context, String.valueOf(metadata.getId()), false, false,
                false);
        XMLOutputter outp = new XMLOutputter();
        String xmlBefore = outp.outputString(beforeMetadata);
        String xmlAfter = outp.outputString(afterMetadata);
        new RecordUpdatedEvent(Long.parseLong(id), session.getUserIdAsInt(), xmlBefore, xmlAfter)
                .publish(applicationContext);
    }

    //-----------------------------------------------------------------------
    //--- update element and return status
    //        Element elResp = new Element(Jeeves.Elem.RESPONSE);
    //        elResp.addContent(new Element(Geonet.Elem.ID).setText(id));
    //        elResp.addContent(new Element(Geonet.Elem.SHOWVALIDATIONERRORS)
    //            .setText(String.valueOf(withValidationErrors)));
    ////        boolean justCreated = Util.getParam(params, Params.JUST_CREATED, null) != null;
    ////        if (justCreated) {
    ////            elResp.addContent(new Element(Geonet.Elem.JUSTCREATED).setText("true"));
    ////        }
    //        elResp.addContent(new Element(Params.MINOREDIT).setText(String.valueOf(minor)));

    //--- if finished then remove the XML from the session
    if ((commit) && (!terminate)) {
        return null;
    }
    if (terminate) {
        SettingManager sm = context.getBean(SettingManager.class);

        boolean forceValidationOnMdSave = sm.getValueAsBool("metadata/workflow/forceValidationOnMdSave");

        boolean reindex = false;

        // Save validation if the forceValidationOnMdSave is enabled
        if (forceValidationOnMdSave) {
            validator.doValidate(metadata, context.getLanguage());
            reindex = true;
        }

        boolean automaticUnpublishInvalidMd = sm
                .getValueAsBool("metadata/workflow/automaticUnpublishInvalidMd");
        boolean isUnpublished = false;

        // Unpublish the metadata automatically if the setting automaticUnpublishInvalidMd is enabled and
        // the metadata becomes invalid
        if (automaticUnpublishInvalidMd) {
            final OperationAllowedRepository operationAllowedRepo = context
                    .getBean(OperationAllowedRepository.class);

            boolean isPublic = (operationAllowedRepo.count(where(hasMetadataId(id))
                    .and(hasOperation(ReservedOperation.view)).and(hasGroupId(ReservedGroup.all.getId()))) > 0);

            if (isPublic) {
                final MetadataValidationRepository metadataValidationRepository = context
                        .getBean(MetadataValidationRepository.class);

                boolean isInvalid = (metadataValidationRepository.count(
                        MetadataValidationSpecs.isInvalidAndRequiredForMetadata(Integer.parseInt(id))) > 0);

                if (isInvalid) {
                    isUnpublished = true;
                    operationAllowedRepo
                            .deleteAll(where(hasMetadataId(id)).and(hasGroupId(ReservedGroup.all.getId())));
                }

                reindex = true;
            }

        }

        if (reindex) {
            dataMan.indexMetadata(id, true, null);
        }

        ajaxEditUtils.removeMetadataEmbedded(session, id);
        dataMan.endEditingSession(id, session);
        if (isUnpublished) {
            throw new IllegalStateException(String.format(
                    "Record saved but as it was invalid at the end of "
                            + "the editing session. The public record '%s' was unpublished.",
                    metadata.getUuid()));
        } else {
            return null;
        }
    }

    //        if (!finished && !forget && commit) {
    //            dataMan.startEditingSession(context, id);
    //        }
    Element elMd = new AjaxEditUtils(context).getMetadataEmbedded(context, String.valueOf(id), true,
            withValidationErrors);
    return buildEditorForm(tab, httpSession, forwardedParams, request, metadata.getId(), elMd,
            metadata.getDataInfo().getSchemaId(), withValidationErrors, context, applicationContext, false,
            false);
}