Example usage for org.springframework.http HttpHeaders ACCEPT

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

Introduction

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

Prototype

String ACCEPT

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

Click Source Link

Document

The HTTP Accept header field name.

Usage

From source file:com.netflix.genie.web.resources.handlers.GenieResourceHttpRequestHandler.java

/**
 * {@inheritDoc}//from w w  w . j  av  a 2s.c  o  m
 */
@Override
public void handleRequest(@Nonnull final HttpServletRequest request,
        @Nonnull final HttpServletResponse response) throws ServletException, IOException {
    final Resource resource = this.getResource(request);
    if (resource == null || !resource.exists()) {
        response.sendError(HttpStatus.NOT_FOUND.value());
        return;
    }

    final File file = resource.getFile();
    if (file.isDirectory()) {
        final Object rootDirAttribute = request.getAttribute(GENIE_JOB_IS_ROOT_DIRECTORY);
        final boolean isRootDirectory;
        if (rootDirAttribute != null) {
            isRootDirectory = (Boolean) rootDirAttribute;
        } else {
            isRootDirectory = true;
        }
        final String accept = request.getHeader(HttpHeaders.ACCEPT);
        final String requestUrl;
        if (request.getHeader(JobConstants.GENIE_FORWARDED_FROM_HEADER) != null) {
            requestUrl = request.getHeader(JobConstants.GENIE_FORWARDED_FROM_HEADER);
        } else {
            requestUrl = request.getRequestURL().toString();
        }

        try {
            if (accept != null && accept.contains(MediaType.TEXT_HTML_VALUE)) {
                response.setContentType(MediaType.TEXT_HTML_VALUE);
                response.getOutputStream()
                        .write(this.directoryWriter.toHtml(file, requestUrl, !isRootDirectory).getBytes(UTF_8));
            } else {
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.getOutputStream()
                        .write(this.directoryWriter.toJson(file, requestUrl, !isRootDirectory).getBytes(UTF_8));
            }
        } catch (final Exception e) {
            throw new ServletException(e);
        }
    } else {
        super.handleRequest(request, response);
    }
}

From source file:com.netflix.genie.web.services.impl.JobDirectoryServerServiceImpl.java

private void handleRequest(final URI baseUri, final String relativePath, final HttpServletRequest request,
        final HttpServletResponse response, final JobDirectoryManifest manifest, final URI jobDirectoryRoot)
        throws IOException, ServletException {
    log.debug("Handle request, baseUri: '{}', relpath: '{}', jobRootUri: '{}'", baseUri, relativePath,
            jobDirectoryRoot);//from www.j a  va2  s  .c om
    final JobDirectoryManifest.ManifestEntry entry;
    final Optional<JobDirectoryManifest.ManifestEntry> entryOptional = manifest.getEntry(relativePath);
    if (entryOptional.isPresent()) {
        entry = entryOptional.get();
    } else {
        log.error("No such entry in job manifest: {}", relativePath);
        response.sendError(HttpStatus.NOT_FOUND.value(), "Not found: " + relativePath);
        return;
    }

    if (entry.isDirectory()) {
        // For now maintain the V3 structure
        // TODO: Once we determine what we want for V4 use v3/v4 flags or some way to differentiate
        // TODO: there's no unit test covering this section
        final DefaultDirectoryWriter.Directory directory = new DefaultDirectoryWriter.Directory();
        final List<DefaultDirectoryWriter.Entry> files = Lists.newArrayList();
        final List<DefaultDirectoryWriter.Entry> directories = Lists.newArrayList();
        try {
            entry.getParent().ifPresent(parentPath -> {
                final JobDirectoryManifest.ManifestEntry parentEntry = manifest.getEntry(parentPath)
                        .orElseThrow(IllegalArgumentException::new);
                directory.setParent(createEntry(parentEntry, baseUri));
            });

            for (final String childPath : entry.getChildren()) {
                final JobDirectoryManifest.ManifestEntry childEntry = manifest.getEntry(childPath)
                        .orElseThrow(IllegalArgumentException::new);

                if (childEntry.isDirectory()) {
                    directories.add(this.createEntry(childEntry, baseUri));
                } else {
                    files.add(this.createEntry(childEntry, baseUri));
                }
            }
        } catch (final IllegalArgumentException iae) {
            log.error("Encountered unexpected problem traversing the manifest for directory entry {}", entry,
                    iae);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return;
        }

        directories.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));
        files.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));

        directory.setDirectories(directories);
        directory.setFiles(files);

        final String accept = request.getHeader(HttpHeaders.ACCEPT);
        if (accept != null && accept.contains(MediaType.TEXT_HTML_VALUE)) {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            response.getOutputStream().write(DefaultDirectoryWriter.directoryToHTML(entry.getName(), directory)
                    .getBytes(StandardCharsets.UTF_8));
        } else {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            GenieObjectMapper.getMapper().writeValue(response.getOutputStream(), directory);
        }
    } else {
        final URI location = jobDirectoryRoot.resolve(entry.getPath());
        log.debug("Get resource: {}", location);
        final Resource jobResource = this.resourceLoader.getResource(location.toString());
        // Every file really should have a media type but if not use text/plain
        final String mediaType = entry.getMimeType().orElse(MediaType.TEXT_PLAIN_VALUE);
        final ResourceHttpRequestHandler handler = this.genieResourceHandlerFactory.get(mediaType, jobResource);
        handler.handleRequest(request, response);
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody.toSingleValueMap(), headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), String.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    int cookiesAdded = 0;
    headers = getAppBasicAuthHttpHeaders();
    for (String cookie : cookies) {
        if (cookie.startsWith("X-Uaa-Csrf=") || cookie.startsWith("JSESSIONID=")) {
            headers.add("Cookie", cookie);
            cookiesAdded++;/*from   w ww  . j av  a  2 s.c o m*/
        }
    }
    assertEquals(2, cookiesAdded);

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true")
                .queryParam(DEFAULT_CSRF_COOKIE_NAME,
                        IntegrationTestUtils.extractCookieCsrf(authorizeResponse.getBody()))
                .build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), String.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token").build().toUriString();

    MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>();
    tokenParams.add("response_type", "token");
    tokenParams.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE);
    tokenParams.add("code", newCode);
    tokenParams.add("redirect_uri", appUrl);
    headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(tokenParams, headers,
            HttpMethod.POST, new URI(tokenUrl));
    ResponseEntity<Map> tokenResponse = template.exchange(requestEntity, Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();

    BasicCookieStore cookieStore = new BasicCookieStore();
    ResponseEntity<String> loginResponse = template.exchange(baseUrl + "/login", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, loginResponse);
    String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody());
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, csrf);

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), String.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertThat(cookies, hasItem(startsWith("JSESSIONID")));
    assertThat(cookies, hasItem(startsWith("X-Uaa-Csrf")));
    if (IdentityZoneHolder.get().getConfig().isAccountChooserEnabled()) {
        assertThat(cookies, hasItem(startsWith("Saved-Account-")));
    }
    assertThat(cookies, hasItem(startsWith("Current-User")));
    cookieStore.clear();
    setCookiesFromResponse(cookieStore, loginResponse);
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> profilePage = restOperations.exchange(baseUrl + "/profile", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, profilePage);
    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(profilePage.getBody()));
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.login.LoginInfoEndpoint.java

@RequestMapping(value = { "/login" }, headers = "Accept=text/html, */*")
public String loginForHtml(Model model, Principal principal, HttpServletRequest request,
        @RequestHeader(value = "Accept", required = false) List<MediaType> headers)
        throws HttpMediaTypeNotAcceptableException {
    boolean match = headers == null
            || headers.stream().anyMatch(mediaType -> mediaType.isCompatibleWith(MediaType.TEXT_HTML));
    if (!match) {
        throw new HttpMediaTypeNotAcceptableException(request.getHeader(HttpHeaders.ACCEPT));
    }/* w  w w.  j a  va2 s.  c  o  m*/

    Cookie[] cookies = request.getCookies();
    List<SavedAccountOptionModel> savedAccounts = getSavedAccounts(cookies, SavedAccountOptionModel.class);
    savedAccounts.forEach(account -> {
        Color color = ColorHash.getColor(account.getUserId());
        account.assignColors(color);
    });

    model.addAttribute("savedAccounts", savedAccounts);

    return login(model, principal, Collections.singletonList(PASSCODE), false, request);
}

From source file:org.cloudfoundry.identity.uaa.web.LimitedModeUaaFilter.java

protected boolean acceptsJson(HttpServletRequest request) {
    List<MediaType> mediaTypes = MediaType.parseMediaTypes(request.getHeader(HttpHeaders.ACCEPT));
    return mediaTypes.stream().anyMatch(m -> m.isCompatibleWith(MediaType.APPLICATION_JSON));
}

From source file:org.fao.geonet.api.GlobalExceptionController.java

public List<MediaType> resolveMediaTypes(NativeWebRequest request) {

    String header = request.getHeader(HttpHeaders.ACCEPT);
    if (!StringUtils.hasText(header)) {
        return Collections.emptyList();
    }/*  w  w  w . java  2s  .co m*/
    try {
        List<MediaType> mediaTypes = MediaType.parseMediaTypes(header);
        MediaType.sortBySpecificityAndQuality(mediaTypes);
        return mediaTypes;
    } catch (InvalidMediaTypeException ex) {
        return Collections.emptyList();
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

@RequestMapping(value = { "/api/records/{metadataUuid}/formatters/{formatterId}",
        "/api/" + API.VERSION_0_1
                + "/records/{metadataUuid}/formatters/{formatterId}" }, method = RequestMethod.GET, produces = {
                        MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_XHTML_XML_VALUE, "application/pdf",
                        MediaType.ALL_VALUE
        // TODO: PDF
})
@ApiOperation(value = "Get a formatted metadata record", nickname = "getRecordFormattedBy")
@ResponseBody// www .  j  a  v a2s.  c om
public void getRecordFormattedBy(
        @ApiParam(value = "Formatter type to use.") @RequestHeader(value = HttpHeaders.ACCEPT, defaultValue = MediaType.TEXT_HTML_VALUE) String acceptHeader,
        @PathVariable(value = "formatterId") final String formatterId,
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @RequestParam(value = "width", defaultValue = "_100") final FormatterWidth width,
        @RequestParam(value = "mdpath", required = false) final String mdPath,
        @RequestParam(value = "output", required = false) FormatType formatType,
        @ApiIgnore final NativeWebRequest request, final HttpServletRequest servletRequest) throws Exception {

    ApplicationContext applicationContext = ApplicationContextHolder.get();
    Locale locale = languageUtils.parseAcceptLanguage(servletRequest.getLocales());

    // TODO :
    // if text/html > xsl_view
    // if application/pdf > xsl_view and PDF output
    // if application/x-gn-<formatterId>+(xml|html|pdf|text)
    // Force PDF ouutput when URL parameter is set.
    // This is useful when making GET link to PDF which
    // can not use headers.
    if (MediaType.ALL_VALUE.equals(acceptHeader)) {
        acceptHeader = MediaType.TEXT_HTML_VALUE;
    }
    if (formatType == null) {
        formatType = FormatType.find(acceptHeader);
    }
    if (formatType == null) {
        formatType = FormatType.xml;
    }

    final String language = LanguageUtils.locale2gnCode(locale.getISO3Language());
    final ServiceContext context = createServiceContext(language, formatType,
            request.getNativeRequest(HttpServletRequest.class));
    AbstractMetadata metadata = ApiUtils.canViewRecord(metadataUuid, servletRequest);

    Boolean hideWithheld = true;
    //        final boolean hideWithheld = Boolean.TRUE.equals(hide_withheld) ||
    //            !context.getBean(AccessManager.class).canEdit(context, resolvedId);
    Key key = new Key(metadata.getId(), language, formatType, formatterId, hideWithheld, width);
    final boolean skipPopularityBool = false;

    ISODate changeDate = metadata.getDataInfo().getChangeDate();

    Validator validator;
    if (changeDate != null) {
        final long changeDateAsTime = changeDate.toDate().getTime();
        long roundedChangeDate = changeDateAsTime / 1000 * 1000;
        if (request.checkNotModified(language, roundedChangeDate)
                && context.getBean(CacheConfig.class).allowCaching(key)) {
            if (!skipPopularityBool) {
                context.getBean(DataManager.class).increasePopularity(context,
                        String.valueOf(metadata.getId()));
            }
            return;
        }
        validator = new ChangeDateValidator(changeDateAsTime);
    } else {
        validator = new NoCacheValidator();
    }
    final FormatMetadata formatMetadata = new FormatMetadata(context, key, request);

    byte[] bytes;
    if (hasNonStandardParameters(request)) {
        // the http headers can cause a formatter to output custom output due to the parameters.
        // because it is not known how the parameters may affect the output then we have two choices
        // 1. make a unique cache for each configuration of parameters
        // 2. don't cache anything that has extra parameters beyond the standard parameters used to
        //    create the key
        // #1 has a major flaw because an attacker could simply make new requests always changing the parameters
        // and completely swamp the cache.  So we go with #2.  The formatters are pretty fast so it is a fine solution
        bytes = formatMetadata.call().data;
    } else {
        bytes = context.getBean(FormatterCache.class).get(key, validator, formatMetadata, false);
    }
    if (bytes != null) {
        if (!skipPopularityBool) {
            context.getBean(DataManager.class).increasePopularity(context, String.valueOf(metadata.getId()));
        }
        writeOutResponse(context, metadataUuid, locale.getISO3Language(),
                request.getNativeResponse(HttpServletResponse.class), formatType, bytes);
    }
}

From source file:org.fao.geonet.api.records.MetadataApi.java

@ApiOperation(value = "Get a metadata record", notes = "Depending on the accept header the appropriate formatter is used. "
        + "When requesting a ZIP, a MEF version 2 file is returned. "
        + "When requesting HTML, the default formatter is used.", nickname = "getRecord")
@RequestMapping(value = "/{metadataUuid:.+}", method = RequestMethod.GET, consumes = {
        MediaType.ALL_VALUE }, produces = { MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_XHTML_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, "application/pdf",
                "application/zip", MEF_V1_ACCEPT_TYPE, MEF_V2_ACCEPT_TYPE, MediaType.ALL_VALUE })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Return the record."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW),
        @ApiResponse(code = 404, message = ApiParams.API_RESPONSE_RESOURCE_NOT_FOUND) })
public String getRecord(
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @ApiParam(value = "Accept header should indicate which is the appropriate format "
                + "to return. It could be text/html, application/xml, application/zip, ..."
                + "If no appropriate Accept header found, the XML format is returned.", required = true) @RequestHeader(value = HttpHeaders.ACCEPT, defaultValue = MediaType.APPLICATION_XML_VALUE, required = false) String acceptHeader,
        HttpServletResponse response, HttpServletRequest request) throws Exception {
    try {/*from www  .ja  va  2  s  .  co  m*/
        ApiUtils.canViewRecord(metadataUuid, request);
    } catch (SecurityException e) {
        Log.debug(API.LOG_MODULE_NAME, e.getMessage(), e);
        throw new NotAllowedException(ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW);
    }
    List<String> accept = Arrays.asList(acceptHeader.split(","));

    String defaultFormatter = "xsl-view";
    if (accept.contains(MediaType.TEXT_HTML_VALUE) || accept.contains(MediaType.APPLICATION_XHTML_XML_VALUE)
            || accept.contains("application/pdf")) {
        return "forward:" + (metadataUuid + "/formatters/" + defaultFormatter);
    } else if (accept.contains(MediaType.APPLICATION_XML_VALUE)
            || accept.contains(MediaType.APPLICATION_JSON_VALUE)) {
        return "forward:" + (metadataUuid + "/formatters/xml");
    } else if (accept.contains("application/zip") || accept.contains(MEF_V1_ACCEPT_TYPE)
            || accept.contains(MEF_V2_ACCEPT_TYPE)) {
        return "forward:" + (metadataUuid + "/formatters/zip");
    } else {
        // FIXME this else is never reached because any of the accepted medias match one of the previous if conditions.
        response.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XHTML_XML_VALUE);
        //response.sendRedirect(metadataUuid + "/formatters/" + defaultFormatter);
        return "forward:" + (metadataUuid + "/formatters/" + defaultFormatter);
    }
}

From source file:org.fao.geonet.api.records.MetadataApi.java

@ApiOperation(value = "Get a metadata record as XML or JSON", notes = "", nickname = "getRecordAsXmlOrJSON")
@RequestMapping(value = { "/{metadataUuid}/formatters/xml",
        "/{metadataUuid}/formatters/json" }, method = RequestMethod.GET, produces = {
                MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Return the record."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW) })
public @ResponseBody Object getRecordAsXML(
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @ApiParam(value = "Add XSD schema location based on standard configuration "
                + "(see schema-ident.xml).", required = false) @RequestParam(required = false, defaultValue = "true") boolean addSchemaLocation,
        @ApiParam(value = "Increase record popularity", required = false) @RequestParam(required = false, defaultValue = "true") boolean increasePopularity,
        @ApiParam(value = "Add geonet:info details", required = false) @RequestParam(required = false, defaultValue = "false") boolean withInfo,
        @ApiParam(value = "Download as a file", required = false) @RequestParam(required = false, defaultValue = "false") boolean attachment,
        @RequestHeader(value = HttpHeaders.ACCEPT, defaultValue = MediaType.APPLICATION_XML_VALUE) String acceptHeader,
        HttpServletResponse response, HttpServletRequest request) throws Exception {
    ApplicationContext appContext = ApplicationContextHolder.get();
    DataManager dataManager = appContext.getBean(DataManager.class);
    AbstractMetadata metadata;/*w w  w. j av  a 2 s.c  o m*/
    try {
        metadata = ApiUtils.canViewRecord(metadataUuid, request);
    } catch (ResourceNotFoundException e) {
        Log.debug(API.LOG_MODULE_NAME, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        Log.debug(API.LOG_MODULE_NAME, e.getMessage(), e);
        throw new NotAllowedException(ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW);
    }
    ServiceContext context = ApiUtils.createServiceContext(request);
    try {
        Lib.resource.checkPrivilege(context, String.valueOf(metadata.getId()), ReservedOperation.view);
    } catch (Exception e) {
        // TODO: i18n
        // TODO: Report exception in JSON format
        Log.debug(API.LOG_MODULE_NAME, e.getMessage(), e);
        throw new NotAllowedException(ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW);

    }

    if (increasePopularity) {
        dataManager.increasePopularity(context, metadata.getId() + "");
    }

    boolean withValidationErrors = false, keepXlinkAttributes = false, forEditing = false;
    Element xml = withInfo
            ? dataManager.getMetadata(context, metadata.getId() + "", forEditing, withValidationErrors,
                    keepXlinkAttributes)
            : dataManager.getMetadataNoInfo(context, metadata.getId() + "");

    if (addSchemaLocation) {
        Attribute schemaLocAtt = _schemaManager.getSchemaLocation(metadata.getDataInfo().getSchemaId(),
                context);

        if (schemaLocAtt != null) {
            if (xml.getAttribute(schemaLocAtt.getName(), schemaLocAtt.getNamespace()) == null) {
                xml.setAttribute(schemaLocAtt);
                // make sure namespace declaration for schemalocation is present -
                // remove it first (does nothing if not there) then add it
                xml.removeNamespaceDeclaration(schemaLocAtt.getNamespace());
                xml.addNamespaceDeclaration(schemaLocAtt.getNamespace());
            }
        }
    }

    boolean isJson = acceptHeader.contains(MediaType.APPLICATION_JSON_VALUE);

    String mode = (attachment) ? "attachment" : "inline";
    response.setHeader("Content-Disposition",
            String.format(mode + "; filename=\"%s.%s\"", metadata.getUuid(), isJson ? "json" : "xml"));
    return isJson ? Xml.getJSON(xml) : xml;
    //return xml;
}

From source file:org.fao.geonet.api.records.MetadataApi.java

@ApiOperation(value = "Get a metadata record as ZIP", notes = "Metadata Exchange Format (MEF) is returned. MEF is a ZIP file containing "
        + "the metadata as XML and some others files depending on the version requested. "
        + "See http://geonetwork-opensource.org/manuals/trunk/eng/users/annexes/mef-format.html.", nickname = "getRecordAsZip")
@RequestMapping(value = "/{metadataUuid}/formatters/zip", method = RequestMethod.GET, consumes = {
        MediaType.ALL_VALUE }, produces = { "application/zip", MEF_V1_ACCEPT_TYPE, MEF_V2_ACCEPT_TYPE })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Return the record."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW) })
public @ResponseBody void getRecordAsZip(
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @ApiParam(value = "MEF file format.", required = false) @RequestParam(required = false, defaultValue = "FULL") MEFLib.Format format,
        @ApiParam(value = "With related records (parent and service).", required = false) @RequestParam(required = false, defaultValue = "true") boolean withRelated,
        @ApiParam(value = "Resolve XLinks in the records.", required = false) @RequestParam(required = false, defaultValue = "true") boolean withXLinksResolved,
        @ApiParam(value = "Preserve XLink URLs in the records.", required = false) @RequestParam(required = false, defaultValue = "false") boolean withXLinkAttribute,
        @RequestParam(required = false, defaultValue = "true") boolean addSchemaLocation,
        @RequestHeader(value = HttpHeaders.ACCEPT, defaultValue = "application/x-gn-mef-2-zip") String acceptHeader,
        HttpServletResponse response, HttpServletRequest request) throws Exception {
    ApplicationContext appContext = ApplicationContextHolder.get();
    GeonetworkDataDirectory dataDirectory = appContext.getBean(GeonetworkDataDirectory.class);

    AbstractMetadata metadata;/*from   www.  j a v a  2 s  .  c  o  m*/
    try {
        metadata = ApiUtils.canViewRecord(metadataUuid, request);
    } catch (SecurityException e) {
        Log.debug(API.LOG_MODULE_NAME, e.getMessage(), e);
        throw new NotAllowedException(ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW);
    }
    Path stylePath = dataDirectory.getWebappDir().resolve(Geonet.Path.SCHEMAS);
    Path file = null;
    ServiceContext context = ApiUtils.createServiceContext(request);
    MEFLib.Version version = MEFLib.Version.find(acceptHeader);
    if (version == MEFLib.Version.V1) {
        // This parameter is deprecated in v2.
        boolean skipUUID = false;
        file = MEFLib.doExport(context, metadataUuid, format.toString(), skipUUID, withXLinksResolved,
                withXLinkAttribute, addSchemaLocation);
    } else {
        Set<String> tmpUuid = new HashSet<String>();
        tmpUuid.add(metadataUuid);
        // MEF version 2 support multiple metadata record by file.
        if (withRelated) {
            // Adding children in MEF file

            // Creating request for services search
            Element childRequest = new Element("request");
            childRequest.addContent(new Element("parentUuid").setText(metadataUuid));
            childRequest.addContent(new Element("to").setText("1000"));

            // Get children to export - It could be better to use GetRelated service TODO
            Set<String> childs = MetadataUtils.getUuidsToExport(metadataUuid, request, childRequest);
            if (childs.size() != 0) {
                tmpUuid.addAll(childs);
            }

            // Creating request for services search
            Element servicesRequest = new Element(Jeeves.Elem.REQUEST);
            servicesRequest
                    .addContent(new Element(org.fao.geonet.constants.Params.OPERATES_ON).setText(metadataUuid));
            servicesRequest.addContent(new Element(org.fao.geonet.constants.Params.TYPE).setText("service"));

            // Get linked services for export
            Set<String> services = MetadataUtils.getUuidsToExport(metadataUuid, request, servicesRequest);
            if (services.size() != 0) {
                tmpUuid.addAll(services);
            }
        }
        Log.info(Geonet.MEF, "Building MEF2 file with " + tmpUuid.size() + " records.");

        file = MEFLib.doMEF2Export(context, tmpUuid, format.toString(), false, stylePath, withXLinksResolved,
                withXLinkAttribute, false, addSchemaLocation);
    }
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
            String.format("inline; filename=\"%s.zip\"", metadata.getUuid()));
    response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(Files.size(file)));
    response.setContentType(acceptHeader);
    FileUtils.copyFile(file.toFile(), response.getOutputStream());
}