Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

List of usage examples for javax.servlet.http HttpServletResponse SC_FORBIDDEN

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Prototype

int SC_FORBIDDEN

To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:eu.dasish.annotation.backend.rest.NotebookResource.java

/**
 * //from  w  ww.  ja v a  2 s .  c om
 * @param externalIdentifier the external UUID identifier of a notebook.
 * @return a {@link Notebook} element representing the notebook with "externalIdentifier"; built up on the whole information 
 * (the "notebook" table and the corresponding junction tables) for the notebook with "externalIdentifier".
 * @throws IOException if sending an error fails.
 */

@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{notebookid: " + BackendConstants.regExpIdentifier + "}/metadata")
@Transactional(readOnly = true)
public JAXBElement<Notebook> getNotebook(@PathParam("notebookid") String externalIdentifier)
        throws IOException {
    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return new ObjectFactory().createNotebook(new Notebook());
    }
    try {
        Number notebookID = dbDispatcher.getResourceInternalIdentifier(UUID.fromString(externalIdentifier),
                Resource.NOTEBOOK);
        if (dbDispatcher.hasAccess(notebookID, remotePrincipalID, Access.fromValue("read"))) {
            Notebook notebook = dbDispatcher.getNotebook(notebookID);
            return new ObjectFactory().createNotebook(notebook);
        } else {
            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
            return new ObjectFactory().createNotebook(new Notebook());
        }

    } catch (NotInDataBaseException e) {
        loggerServer.debug(e.toString());
        ;
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.toString());
        return new ObjectFactory().createNotebook(new Notebook());
    }
}

From source file:edu.ucsd.library.dams.api.FileStoreServlet.java

/**
 * Process the actual request.//from  w  w  w .  j a  va  2s  .  co  m
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 *  (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException {
    // Validate the requested file -------------------------------------

    // Get requested file by path info.
    /* start ucsd changes */

    // get object and file ids from path
    String objid = null;
    String cmpid = null;
    String fileid = null;
    try {
        // /bb1234567x/1.tif
        // /bb1234567x/1/2.tif
        String[] path = request.getPathInfo().split("/");
        if (path.length == 3) {
            objid = path[1];
            fileid = path[2];
        } else if (path.length == 4) {
            objid = path[1];
            cmpid = path[2];
            fileid = path[3];
        }
    } catch (Exception e) {
        String errorMessage = "Error parsing request pathInfo: " + request.getPathInfo();
        log.error(errorMessage, e);
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage);
        return;
    }

    // make sure required parameters are populated
    if (objid == null || objid.trim().length() == 0 || fileid == null || fileid.trim().length() == 0) {
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Subject and file must be specified in the request URI");
        return;
    }
    String fullFilename = objid + (StringUtils.isNotBlank(cmpid) ? "-" + cmpid : "") + "-" + fileid;

    // first load the FileStore (no point if this doesn't work)
    FileStore fs = null;
    long fsTime = 0;
    try {
        long start = System.currentTimeMillis();
        fs = FileStoreUtil.getFileStore(props, fsDefault);
        fsTime = System.currentTimeMillis() - start;
    } catch (Exception ex) {
        response.setContentType("text/plain");
        response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Error initializing FileStore");
        ex.printStackTrace();
        return;
    }

    // check authorization attribute
    String restricted = null;
    String authorized = (String) request.getAttribute("edu.ucsd.library.dams.api.DAMSAPIServlet.authorized");
    if (authorized == null || !authorized.equals("true")) {
        log.warn("Illegal Access from IP " + request.getRemoteAddr() + " for file " + fullFilename);
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access without authorization.");
        return;
    } else {
        log.info("DAMS Access authorized for IP " + request.getRemoteAddr() + " for file " + fullFilename);
        restricted = (String) request.getAttribute("pas.restricted");
        //Disable browser caching for restricted objects.
        if (restricted != null && restricted.equals("1")) {
            String browser = request.getHeader("User-Agent");
            if (browser != null && browser.indexOf("MSIE") != -1) {
                response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            } else {
                response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            }
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");
        }
    }
    /* end ucsd changes */

    // load file metadata
    Map<String, String> meta = null;
    long metaTime = 0;
    try {
        long start = System.currentTimeMillis();
        meta = fs.meta(objid, cmpid, fileid);
        metaTime = System.currentTimeMillis() - start;
    } catch (Exception ex) {
        log.error("File " + fullFilename + " doesn't exist.", ex);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file
    String length = meta.get("Content-Length");
    String lastModStr = meta.get("Last-Modified");
    long lastModified = 0L;
    try {
        lastModified = df.parse(lastModStr).getTime();
    } catch (Exception ex) {
        // error parsing lastmod date... set to now
        lastModified = System.currentTimeMillis();
    }
    String eTag = meta.get("ETag");
    if (eTag == null) {
        eTag = fullFilename + "_" + length + "_" + lastModified;
    }

    // Validate request headers for caching -----------------------------

    // If-None-Match header should contain "*" or ETag. If so, return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified.
    // If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Prepare and initialize response ----------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fullFilename);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.  For all
    // content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    //If UCSD download
    boolean download = request.getParameter("download") != null;
    if (download) {
        disposition = "attachment";
        contentType = "application/x-download";
    }
    // Else if content type is text, then determine whether GZIP content
    // encoding is supported by the browser and expand content type with
    // the one and right character encoding.
    else if (contentType.startsWith("text")) {
        //String acceptEncoding = request.getHeader("Accept-Encoding");
        //acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by the browser, then set to inline, else
    // attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    String sFileName = request.getParameter("name");
    if (sFileName == null || (sFileName = sFileName.trim()).length() == 0)
        sFileName = fullFilename;

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + sFileName + "\"");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    /* begin ucsd changes */
    if (restricted == null || !restricted.equals("1")) {
        response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
    }
    /* end ucsd changes */

    // Send requested file to client ------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;
    long fileTime = 0;
    if (content) {
        try {
            long start = System.currentTimeMillis();
            // Open streams.
            input = fs.getInputStream(objid, cmpid, fileid);
            output = response.getOutputStream();
            response.setContentType(contentType);
            if (acceptsGzip) {
                // The browser accepts GZIP, so GZIP the content.
                response.setHeader("Content-Encoding", "gzip");
                output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
            } else {
                // Content length is not directly predictable in case of
                // GZIP. So only add it if there is no means of GZIP, else
                // browser will hang.
                response.setHeader("Content-Length", length);
            }

            // Copy full range.
            /* begin ucsd changes */
            FileStoreUtil.copy(input, output);
            fileTime = System.currentTimeMillis() - start;
            /* begin ucsd changes */
        } catch (Exception ex) {
            log.error("Error reading " + fullFilename, ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            /* begin ucsd changes */
            log.info("Time in miliseconds to retrival file " + fullFilename + "(" + length + " bytes)"
                    + ": Total " + (fsTime + metaTime + fileTime) + "[FileStore initiation: " + fsTime
                    + "; Metadata query: " + metaTime + "; File download: " + fileTime + "]");
            /* begin ucsd changes */
            // Gently close streams.
            close(output);
            close(input);
        }
    }
}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles get request with an id, this returns the serialized project
 * identified by the id. Partially implemented.
 * /*from w  w w . j  a  v a2s  .  c o  m*/
 * @param idpart
 * @param mimeType
 * @param modifiedSince
 * @param request
 * @throws BizPolicyException
 */
@RequestMapping(value = "/{idpart}", method = { RequestMethod.GET })
public void handleProjectGetRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse resp) throws IOException, BizPolicyException {

    Person user = getAuthenticatedUser();
    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {
        String id = util.buildRequestUrl(request);

        Project project = projectBizService.getProject(id, user);

        if (project == null) {
            resp.setStatus(HttpStatus.SC_NOT_FOUND);
        } else {
            if (authorizationService.canReadProject(user, project)) {
                Bop bop = new Bop();
                bop.addProject(project);
                resp.setContentType("text/xml");
                objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }
    }
}

From source file:com.github.thorqin.webapi.oauth2.OAuthServer.java

public static void responseGetResourceFailed(HttpServletResponse response, OAuthError error,
        String errorDescription, String errorUri) {
    String headContent = "Bearer ";
    headContent += "error=\"" + error.toString().toLowerCase() + "\"";
    if (errorDescription != null)
        headContent += "error_description=\"" + errorDescription + "\"";
    if (errorUri != null)
        headContent += "error_uri=\"" + errorUri + "\"";
    response.setHeader("WWW-Authenticate", headContent);

    switch (error) {
    case INVALID_REQUEST:
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        break;//from  w w w . j  a v  a 2  s  .  co  m
    case UNAUTHORIZED_CLIENT:
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        break;
    case ACCESS_DENIED:
    case UNSUPPORTED_RESPONSE_TYPE:
    case INVALID_SCOPE:
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        break;
    case SERVER_ERROR:
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        break;
    case TEMPORARILY_UNAVAILABLE:
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        break;
    }
}

From source file:com.lp.webapp.cc.CCOrderResponseServlet.java

private int getHttpStatusforEjbStatus(CreateOrderResult result) {
    if (Helper.isOneOf(result.getRc(),
            new int[] { CreateOrderResult.ERROR_EMPTY_ORDER, CreateOrderResult.ERROR_JAXB_EXCEPTION,
                    CreateOrderResult.ERROR_SAX_EXCEPTION, CreateOrderResult.ERROR_UNMARSHALLING })) {
        return HttpServletResponse.SC_BAD_REQUEST;
    }/*w w w.j  a  va  2s  . co  m*/

    if (result.getRc() == CreateOrderResult.ERROR_AUTHENTIFICATION) {
        return HttpServletResponse.SC_FORBIDDEN;
    }

    if (result.getRc() == CreateOrderResult.ERROR_CUSTOMER_NOT_FOUND) {
        return HttpServletResponse.SC_NOT_FOUND;
    }

    if (result.getRc() >= CreateOrderResult.ERROR_EJB_EXCEPTION) {
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    if (result.getRc() == BaseRequestResult.OKAY) {
        return HttpServletResponse.SC_CREATED;
    }

    return HttpServletResponse.SC_EXPECTATION_FAILED;
}

From source file:com.vmware.identity.samlservice.LogoutState.java

/**
 * Initial parsing of the request Includes signature check and validation
 *
 * @param tenant/*from w ww  .  j  a  va 2 s  .  c o  m*/
 * @param processor
 */
public void parseRequestForTenant(String tenant, ProcessingFilter<LogoutState> processor) {
    log.debug("parseRequestForTenant, tenant " + tenant);

    Validate.notNull(this.idmAccessor);
    Validate.notNull(this.request);

    // check for replays
    if (this.samlRequest != null) {
        if (this.requestCache.shouldDenyRequest(this.samlRequest)) {
            log.debug("Replay attack detected - DENYING logout request");
            this.validationResult = new ValidationResult(HttpServletResponse.SC_FORBIDDEN, "Forbidden", null);
            throw new IllegalStateException("Forbidden");
        } else {
            this.requestCache.storeRequest(this.samlRequest);
        }
    } else if (this.samlResponse != null) {
        if (this.requestCache.shouldDenyRequest(this.samlResponse)) {
            log.debug("Replay attack detected - DENYING logout response");
            this.validationResult = new ValidationResult(HttpServletResponse.SC_FORBIDDEN, "Forbidden", null);
            throw new IllegalStateException("Forbidden");
        } else {
            this.requestCache.storeRequest(this.samlResponse);
        }
    }

    try {
        processor.preProcess(this);
    } catch (SamlServiceException e) {
        this.validationResult = new ValidationResult(HttpServletResponse.SC_FORBIDDEN, "Forbidden", null);
        throw new IllegalStateException(e);
    }

    SamlService service = createSamlServiceForTenant(tenant, null); // relying
    // party
    // unknown
    // at
    // this
    // point
    // decode request
    try {
        setSamlObject(service.decodeSamlRequest(this.request));
        if (samlObject instanceof LogoutRequest) {
            setLogoutRequest((LogoutRequest) samlObject);
        } else if (samlObject instanceof LogoutResponse) {
            setLogoutResponse((LogoutResponse) samlObject);
        }
    } catch (MessageDecodingException e) {
        // fail the validation with specific error code and rethrow
        this.validationResult = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
        log.debug("Caught exception " + e.toString());
        throw new IllegalStateException(e);
    } catch (SecurityException e) {
        // fail the validation with specific error code and rethrow
        this.validationResult = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
        log.debug("Caught exception " + e.toString());
        throw new IllegalStateException(e);
    }
    // if signature was specified along with signing algorithm, verify
    // signature
    Issuer issuer = getIssuer();
    if (issuer == null || issuer.getValue() == null) {
        service = null;
    } else {
        this.setIssuerValue(issuer.getValue());
        service = createSamlServiceForTenant(tenant, this.getIssuerValue());
    }
    if (service == null) {
        // return 400 to the caller and throw
        this.validationResult = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest",
                "Issuer");
        throw new IllegalStateException("Issuer not recognized");
    }
    if (this.sigAlg != null && this.signature != null) {
        try {
            service.verifySignature(this.signedMessage, this.signature);
        } catch (IllegalStateException e) {
            // fail the validation with specific error code and rethrow
            this.validationResult = new ValidationResult(OasisNames.RESPONDER, OasisNames.REQUEST_DENIED);
            throw new IllegalStateException(e);
        }
    }

    this.validationResult = validator.validate(this);

    if (this.validationResult.isValid()) {
        // mark as parsed
        this.processingState = ProcessingState.PARSED;
    }
}

From source file:ejportal.webapp.action.UserAction.java

/**
 * Save user./*from   w w w .ja  v  a 2  s.  c o m*/
 * 
 * @return success if everything worked, otherwise input
 * @throws Exception
 *             when setting "access denied" fails on response
 */
public String save() throws Exception {

    final Integer originalVersion = this.user.getVersion();

    final boolean isNew = ("".equals(this.getRequest().getParameter("user.version")));
    // only attempt to change roles if user is admin
    // for other users, prepare() method will handle populating
    // TODO hartkodiert
    if (this.getRequest().isUserInRole("ROLE_ADMIN")) {
        // if (getRequest().isUserInRole(Constants.ADMIN_ROLE)) {
        this.user.getRoles().clear(); // APF-788: Removing roles from user
        // doesn't work
        final String[] userRoles = this.getRequest().getParameterValues("userRoles");

        for (int i = 0; (userRoles != null) && (i < userRoles.length); i++) {
            final String roleName = userRoles[i];
            this.user.addRole(this.roleManager.getRole(roleName));
        }
    }

    try {
        this.userManager.saveUser(this.user);
    } catch (final AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor
        // userManagerSecurity
        this.log.warn(ade.getMessage());
        this.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    } catch (final UserExistsException e) {
        final List<Object> args = new ArrayList<Object>();
        args.add(this.user.getUsername());
        args.add(this.user.getEmail());
        this.addActionError(this.getText("errors.existing.user", args));

        // reset the version # to what was passed in
        this.user.setVersion(originalVersion);
        // redisplay the unencrypted passwords
        this.user.setPassword(this.user.getConfirmPassword());
        return Action.INPUT;
    }

    if (!"list".equals(this.from)) {
        // add success messages
        this.saveMessage(this.getText("user.saved"));
        return "mainMenu";
    } else {
        // add success messages
        final List<Object> args = new ArrayList<Object>();
        args.add(this.user.getFullName());
        if (isNew) {
            this.saveMessage(this.getText("user.added", args));
            // Send an account information e-mail
            this.mailMessage.setSubject(this.getText("signup.email.subject"));
            try {
                this.sendUserMessage(this.user, this.getText("newuser.email.message", args),
                        RequestUtil.getAppURL(this.getRequest()));
            } catch (final MailException me) {
                this.addActionError(me.getCause().getLocalizedMessage());
            }
            return Action.SUCCESS;
        } else {
            this.saveMessage(this.getText("user.updated.byAdmin", args));
            return Action.INPUT;
        }
    }
}

From source file:org.logger.event.web.controller.EventController.java

/**
 * Read events from event detail/*w w  w  .j a va  2 s  . c  o m*/
 * 
 * @param request
 * @param apiKey
 * @param eventId
 * @param response
 */
@RequestMapping(value = "/tail", method = RequestMethod.GET)
public void readEventDetails(HttpServletRequest request,
        @RequestParam(value = "apiKey", required = true) String apiKey,
        @RequestParam(value = EVENT_ID, required = true) String eventId, HttpServletResponse response) {

    // add cross domain support
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers",
            "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
    response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST");

    String apiKeyToken = request.getParameter("apiKey");

    if (apiKeyToken != null && apiKeyToken.length() == 36) {
        AppDO appDO = eventService.verifyApiKey(apiKeyToken);
        if (appDO != null) {
            ColumnList<String> eventDetail = eventService.readEventDetail(eventId);
            if (eventDetail != null && !eventDetail.isEmpty()) {

                response.setContentType("application/json");
                Map<String, Object> resultMap = new HashMap<String, Object>();

                resultMap.put("eventJSON", eventDetail.getStringValue("fields", null));
                resultMap.put("startTime", eventDetail.getLongValue("start_time", null));
                resultMap.put("endTime", eventDetail.getLongValue("end_time", null));
                resultMap.put(EVENT_NAME, eventDetail.getStringValue("event_name", null));
                resultMap.put("apiKey", eventDetail.getStringValue("api_key", null));
                JSONObject resultJson = new JSONObject(resultMap);

                try {
                    response.getWriter().write(resultJson.toString());
                } catch (IOException e) {
                    logger.error("OOPS! Something went wrong", e);
                }

            }
            return;
        }
    }
    eventService.sendErrorResponse(request, response, HttpServletResponse.SC_FORBIDDEN, "Invalid API Key");
    return;

}

From source file:com.flexive.war.servlet.ExportServlet.java

/**
 * Export a content (one version)//from   www .  ja  v a  2s. c om
 *
 * @param request  request
 * @param response reponse
 * @param pk       primary key
 * @throws IOException on errors
 */
private void exportContent(HttpServletRequest request, HttpServletResponse response, String pk)
        throws IOException {
    String xml;
    try {
        ContentEngine co = EJBLookup.getContentEngine();
        final FxContent content = co.load(FxPK.fromString(pk));
        xml = co.exportContent(content);
        pk = content.getPk().toString(); //get exact version
    } catch (FxNoAccessException e) {
        LOG.warn("No access to export [" + pk + "]!");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    } catch (FxApplicationException e) {
        LOG.warn("Error exporting [" + pk + "]: " + e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=\"content_" + pk + ".xml\";");
    try {
        response.getOutputStream().write(xml.getBytes(Charsets.UTF_8));
    } finally {
        response.getOutputStream().close();
    }
}

From source file:info.magnolia.cms.servlets.EntryServlet.java

/**
 * Uses access manager to authorise this request.
 * @param req HttpServletRequest as received by the service method
 * @param res HttpServletResponse as received by the service method
 * @return boolean true if read access is granted
 * @throws IOException can be thrown when the servlet is unable to write to the response stream
 */// ww w. ja  v a  2 s .  co  m
protected boolean isAuthorized(HttpServletRequest req, HttpServletResponse res) throws IOException {
    if (MgnlContext.getAccessManager(ContentRepository.WEBSITE) != null) {
        String path = StringUtils.substringBefore(Path.getURI(req), "."); //$NON-NLS-1$
        if (!MgnlContext.getAccessManager(ContentRepository.WEBSITE).isGranted(path, Permission.READ)) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    }
    return true;
}