Example usage for org.springframework.http MediaType ALL_VALUE

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

Introduction

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

Prototype

String ALL_VALUE

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

Click Source Link

Document

A String equivalent of MediaType#ALL .

Usage

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

/**
 * Get the job output directory.//from w ww . j ava 2s .com
 *
 * @param id            The id of the job to get output for
 * @param forwardedFrom The host this request was forwarded from if present
 * @param request       the servlet request
 * @param response      the servlet response
 * @throws IOException      on redirect error
 * @throws ServletException when trying to handle the request
 * @throws GenieException   on any Genie internal error
 */
@RequestMapping(value = { "/{id}/output", "/{id}/output/",
        "/{id}/output/**" }, method = RequestMethod.GET, produces = MediaType.ALL_VALUE)
public void getJobOutput(@PathVariable("id") final String id,
        @RequestHeader(name = JobConstants.GENIE_FORWARDED_FROM_HEADER, required = false) final String forwardedFrom,
        final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException, GenieException {
    log.info("[getJobOutput] Called for job with id: {}", id);

    // if forwarded from isn't null it's already been forwarded to this node. Assume data is on this node.
    if (this.jobsProperties.getForwarding().isEnabled() && forwardedFrom == null) {
        // TODO: It's possible that could use the JobMonitorCoordinator to check this in memory
        //       However that could get into problems where the job finished or died
        //       and it would return false on check if the job with given id is running on that node
        final String jobHostname = this.jobSearchService.getJobHost(id);
        if (!this.hostName.equals(jobHostname)) {
            log.info("Job {} is not or was not run on this node. Forwarding to {}", id, jobHostname);
            final String forwardUrl = buildForwardURL(request, jobHostname);
            try {
                this.restTemplate.execute(forwardUrl, HttpMethod.GET,
                        forwardRequest -> copyRequestHeaders(request, forwardRequest),
                        new ResponseExtractor<Void>() {
                            @Override
                            public Void extractData(final ClientHttpResponse forwardResponse)
                                    throws IOException {
                                response.setStatus(HttpStatus.OK.value());
                                copyResponseHeaders(response, forwardResponse);
                                // Documentation I could find pointed to the HttpEntity reading the bytes off
                                // the stream so this should resolve memory problems if the file returned is large
                                ByteStreams.copy(forwardResponse.getBody(), response.getOutputStream());
                                return null;
                            }
                        });
            } catch (HttpStatusCodeException e) {
                log.error("Failed getting the remote job output from {}. Error: {}", forwardUrl,
                        e.getMessage());
                response.sendError(e.getStatusCode().value(), e.getStatusText());
            } catch (Exception e) {
                log.error("Failed getting the remote job output from {}. Error: {}", forwardUrl,
                        e.getMessage());
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            }

            //No need to search on this node
            return;
        }
    }

    log.info("Job {} is running or was run on this node. Fetching requested resource...", id);
    final String path = ControllerUtils.getRemainingPath(request);
    if (StringUtils.isNotBlank(path)) {
        request.setAttribute(GenieResourceHttpRequestHandler.GENIE_JOB_IS_ROOT_DIRECTORY, false);
    } else {
        request.setAttribute(GenieResourceHttpRequestHandler.GENIE_JOB_IS_ROOT_DIRECTORY, true);
    }
    log.debug("PATH = {}", path);
    request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, id + "/" + path);

    this.resourceHttpRequestHandler.handleRequest(request, response);
}

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 ww . j a va2s .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));
}

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

/**
 * Test the response content types to ensure UTF-8.
 *
 * @throws Exception If there is a problem.
 *//*w  ww  .  j  av  a2 s . c o m*/
@Test
public void testResponseContentType() throws Exception {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
    final List<String> commandArgs = Lists.newArrayList("-c", "'echo hello'");

    final JobRequest jobRequest = new JobRequest.Builder(JOB_NAME, JOB_USER, JOB_VERSION,
            Lists.newArrayList(new ClusterCriteria(Sets.newHashSet("localhost"))), Sets.newHashSet("bash"))
                    .withCommandArgs(commandArgs).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.waitForDone(jobId);

    RestAssured.given(this.getRequestSpecification()).when().port(this.port)
            .get(JOBS_API + "/" + jobId + "/output/genie/logs/env.log").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
            .contentType(Matchers.containsString("UTF-8"));

    RestAssured.given(this.getRequestSpecification()).when().port(this.port)
            .get(JOBS_API + "/" + jobId + "/output/genie/logs/genie.log").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
            .contentType(Matchers.containsString("UTF-8"));

    RestAssured.given(this.getRequestSpecification()).when().port(this.port)
            .get(JOBS_API + "/" + jobId + "/output/genie/genie.done").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
            .contentType(Matchers.containsString("UTF-8"));

    RestAssured.given(this.getRequestSpecification()).accept(MediaType.ALL_VALUE).when().port(this.port)
            .get(JOBS_API + "/" + jobId + "/output/stdout").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
            .contentType(Matchers.containsString("UTF-8"));

    RestAssured.given(this.getRequestSpecification()).accept(MediaType.ALL_VALUE).when().port(this.port)
            .get(JOBS_API + "/" + jobId + "/output/stderr").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
            .contentType(Matchers.containsString("UTF-8"));

    // Verify the file is served as UTF-8 even if it's not
    RestAssured.given(this.getRequestSpecification()).accept(MediaType.ALL_VALUE).when().port(this.port)
            .get(JOBS_API + "/" + jobId + "/output/genie/command/" + CMD1_ID + "/config/" + GB18030_TXT).then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
            .contentType(Matchers.containsString("UTF-8"));
}

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

private void checkJobOutput(final int documentationId, final String id) throws Exception {
    // Check getting a directory as json
    final RestDocumentationResultHandler jsonResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/json/",
            Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()),
            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);
    this.mvc.perform(RestDocumentationRequestBuilders.get(JOBS_API + "/{id}/output/{filePath}", id, ""))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath("parent", Matchers.isEmptyOrNullString()))
            .andExpect(MockMvcResultMatchers.jsonPath("$.directories[0].name", Matchers.is("genie/")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[0].name", Matchers.is("dep1")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[1].name", Matchers.is("jobsetupfile")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[2].name", Matchers.is("run")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[3].name", Matchers.is("stderr")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[4].name", Matchers.is("stdout")))
            .andDo(jsonResultHandler);// w  w w . jav a2 s .c om

    // Check getting a directory as HTML
    final RestDocumentationResultHandler htmlResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/html/",
            Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()),
            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
    );
    this.mvc.perform(RestDocumentationRequestBuilders.get(JOBS_API + "/{id}/output/{filePath}", id, "")
            .accept(MediaType.TEXT_HTML)).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_HTML))
            .andDo(htmlResultHandler);

    // Check getting a file

    // Check getting a directory as HTML
    final RestDocumentationResultHandler fileResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/file/",
            Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()),
            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)), "UTF-8");

    final String jobWorkingDir = this.jobDirResource.getFile().getCanonicalPath() + FILE_DELIMITER + id;
    final String expectedRunScriptContent = this.getExpectedRunContents(runFileContents, jobWorkingDir, id);

    this.mvc.perform(RestDocumentationRequestBuilders.get(JOBS_API + "/{id}/output/{filePath}", id, "run"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().string(expectedRunScriptContent))
            .andDo(fileResultHandler);
}

From source file:de.appsolve.padelcampus.controller.ImagesController.java

@RequestMapping(value = "image/{sha256}", consumes = MediaType.ALL_VALUE, produces = {
        MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE, "image/svg+xml" })
public ResponseEntity<byte[]> showImage(@PathVariable("sha256") String sha256) {
    Image image = imageBaseDAO.findBySha256(sha256);
    if (image != null && image.getContent() != null) {
        byte[] byteArray = image.getContent();
        ResponseEntity.BodyBuilder builder = ResponseEntity.ok()
                .header(HttpHeaders.CACHE_CONTROL, String.format("public,max-age=%s,immutable", ONE_YEAR))
                .contentLength(byteArray.length).contentType(MediaType.IMAGE_PNG);

        if (!StringUtils.isEmpty(image.getContentType())) {
            try {
                MediaType mediaType = MediaType.parseMediaType(image.getContentType());
                builder.contentType(mediaType);
            } catch (InvalidMediaTypeException e) {
                LOG.warn(e.getMessage(), e);
            }//from   w w w. j a  v  a2 s . c  o  m
        }
        return builder.body(byteArray);
    }
    LOG.warn(String.format("Unable to display image %s", sha256));
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

From source file:de.codecentric.boot.admin.server.web.client.InstanceWebClientTest.java

@Test
public void should_add_default_logfile_accept_headers() {
    Instance instance = Instance.create(InstanceId.of("id"))
            .register(Registration.create("test", wireMock.url("/status")).build())
            .withEndpoints(Endpoints.single("logfile", wireMock.url("/log")));
    wireMock.stubFor(get("/log").willReturn(ok()));

    Mono<ClientResponse> exchange = instanceWebClient.instance(instance).get().uri("logfile").exchange();

    StepVerifier.create(exchange).expectNextCount(1).verifyComplete();
    wireMock.verify(1,// w ww .j  a  va  2  s .c o m
            getRequestedFor(urlEqualTo("/log")).withHeader(ACCEPT, containing(MediaType.TEXT_PLAIN_VALUE))
                    .withHeader(ACCEPT, containing(MediaType.ALL_VALUE)));
}

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)/*from  w ww .j a  va2s  .com*/
@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)/* www .j av a2  s  .co  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);
}