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:net.morphbank.mbsvc3.webservices.RestService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!isIPAllowed(request.getRemoteAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "This IP is not allowed. Current IP used:" + request.getRemoteAddr());
        return;//from   w  ww.ja  v  a2s.c  o m
    }
    PrintWriter out = response.getWriter();
    MorphbankConfig.SYSTEM_LOGGER.info("starting post from ip:" + request.getRemoteAddr());
    MorphbankConfig.ensureWorkingConnection();
    response.setContentType("text/xml");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + folderPath + " -->");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    //      response.setContentType("text/html");

    String parameter = request.getParameter("uploadxml");
    if (parameter != null) {
        ServletContext context = getServletContext();
        InputStream fis = context.getResourceAsStream(parameter);
        processRequest(fis, out, request.getParameter("fileName"));
    } else {
        try {
            // Process the uploaded items
            List<?> /* FileItem */ items = upload.parseRequest(request);
            Iterator<?> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    // processFormField(item);
                } else {
                    // processUploadedFile(item);
                    String paramName = item.getFieldName();
                    String fileName = item.getName();
                    InputStream stream = item.getInputStream();
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName);
                    processRequest(stream, out, fileName);
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing complete");
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.openrepose.filters.authz.RequestAuthorizationHandler.java

@Override
public FilterDirector handleRequest(HttpServletRequest request, ReadableHttpServletResponse response) {
    final FilterDirector myDirector = new FilterDirectorImpl();
    myDirector.setFilterAction(FilterAction.RETURN);
    myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    String message = "Failure in authorization component";

    final String tracingHeader = request.getHeader(CommonHttpHeader.TRACE_GUID.toString());
    final String authenticationToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString());

    try {/*from   w  w w.  ja v  a  2  s.com*/
        if (StringUtilities.isBlank(authenticationToken)) {
            // Reject if no token
            message = "Authentication token not found in X-Auth-Token header. Rejecting request.";
            LOG.debug(message);
            myDirector.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
        } else if (adminRoleMatchIgnoringCase(request.getHeaders(OpenStackServiceHeader.ROLES.toString()))
                || isEndpointAuthorizedForToken(authenticationToken, tracingHeader)) {
            myDirector.setFilterAction(FilterAction.PASS);
        } else {
            message = "User token: " + authenticationToken
                    + ": The user's service catalog does not contain an endpoint that matches "
                    + "the endpoint configured in openstack-authorization.cfg.xml: \""
                    + configuredEndpoint.getHref() + "\".  User not authorized to access service.";
            LOG.info(message);
            myDirector.setResponseStatusCode(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (AuthServiceOverLimitException ex) {
        LOG.error(message);
        LOG.trace("", ex);
        myDirector.setResponseStatusCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // (503)
        String retry = ex.getRetryAfter();
        if (retry == null) {
            Calendar retryCalendar = new GregorianCalendar();
            retryCalendar.add(Calendar.SECOND, 5);
            retry = new HttpDate(retryCalendar.getTime()).toRFC1123();
        }
        myDirector.responseHeaderManager().appendHeader(HttpHeaders.RETRY_AFTER, retry);
    } catch (AuthServiceException ex) {
        LOG.error(message);
        LOG.trace("", ex);
        if (ex.getCause() instanceof AkkaServiceClientException
                && ex.getCause().getCause() instanceof TimeoutException) {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        } else {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (Exception ex) {
        LOG.error(message);
        LOG.trace("", ex);
        myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (delegating != null && myDirector.getFilterAction() != FilterAction.PASS) {
        myDirector.setFilterAction(FilterAction.PASS);
        for (Map.Entry<String, List<String>> mapHeaders : JavaDelegationManagerProxy
                .buildDelegationHeaders(myDirector.getResponseStatusCode(), CLIENT_AUTHORIZATION, message,
                        delegating.getQuality())
                .entrySet()) {
            List<String> value = mapHeaders.getValue();
            myDirector.requestHeaderManager().appendHeader(mapHeaders.getKey(),
                    value.toArray(new String[value.size()]));
        }
    }
    return myDirector;
}

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

/**
 * //w w  w  .  ja v a 2s.  c  o  m
 * @param externalIdentifier the external UUID of a target.
 * @return a {@link ReferenceList} element representing the list of h-references of the targets that 
 * refer to the same link as the target with "externalIdentifier".
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{targetid: " + BackendConstants.regExpIdentifier + "}/versions")
@Transactional(readOnly = true)
public JAXBElement<ReferenceList> getSiblingTargets(@PathParam("targetid") String externalIdentifier)
        throws IOException {
    Map params = new HashMap();
    try {
        ReferenceList result = (ReferenceList) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetSiblingTargets(), Resource.TARGET, Access.READ, externalIdentifier);
        if (result != null) {
            return new ObjectFactory().createReferenceList(result);
        } else {
            return new ObjectFactory().createReferenceList(new ReferenceList());
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return new ObjectFactory().createReferenceList(new ReferenceList());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return new ObjectFactory().createReferenceList(new ReferenceList());
    }
}

From source file:org.ngrinder.script.controller.SvnDavController.java

/**
 * Request Handler.//w  ww  . j a  v  a 2 s. c o  m
 *
 * @param request  request
 * @param response response
 * @throws ServletException occurs when servlet has a problem.
 * @throws IOException      occurs when file system has a problem.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (LOGGER.isTraceEnabled()) {
        logRequest(request);
    }
    try {
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerFactory.createHandler(repositoryManager, request, response);
        handler.execute();
    } catch (DAVException de) {
        response.setContentType(XML_CONTENT_TYPE);
        handleError(de, response);
    } catch (SVNException svne) {
        StringWriter sw = new StringWriter();
        svne.printStackTrace(new PrintWriter(sw));

        /**
         * truncate status line if it is to long
         */
        String msg = sw.getBuffer().toString();
        if (msg.length() > 128) {
            msg = msg.substring(0, 128);
        }
        SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode();
        if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND
                || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
        } else {
            String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null,
                    svne.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType(XML_CONTENT_TYPE);
            response.getWriter().print(errorBody);
        }
    } catch (Throwable th) {
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        String msg = sw.getBuffer().toString();
        LOGGER.debug("Error in DavSVN Controller", th);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } finally {
        response.flushBuffer();
    }
}

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

/**
 * //from w w w  . java2  s. co m
 * @param request
 * @param response
 */
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public void authenticateRequest(HttpServletRequest request, 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) {
            response.setContentType("application/json");
            Map<String, Object> resultMap = new HashMap<String, Object>();

            resultMap.put("endPoint", appDO.getEndPoint());
            resultMap.put("pushIntervalMs", appDO.getDataPushingIntervalInMillsecs());
            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:aiai.ai.launchpad.server.ServerController.java

@GetMapping("/rest-anon/upload/{taskId}")
public UploadResult uploadResourceAnon(MultipartFile file, HttpServletResponse response,
        @PathVariable("taskId") Long taskId) throws IOException {
    log.debug("uploadResourceAnon(), globals.isSecureRestUrl: {}, taskId: {}", globals.isSecureRestUrl, taskId);
    if (globals.isSecureRestUrl) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }/*from w  w  w  .ja va  2  s .  c om*/
    return uploadResource(file, taskId);
}

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

/**
 * /*from  w  ww  .j  a  v a 2 s. c  o m*/
 * @param n # of strings
 * @return the last n strings of the dasish server logger (non-SQL-request logs).
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/logServer/{n}")
@Transactional(readOnly = true)
public String getDasishServerLog(@PathParam("n") int n) throws IOException {
    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return " ";
    }
    String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
    if (typeOfAccount.equals(admin) || typeOfAccount.equals(developer)) {
        return logFile("eu.dasish.annotation.backend.logServerLocation", n);
    } else {
        this.DEVELOPER_RIGHTS_EXPECTED();
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        return "Coucou.";
    }
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

@Override
public void doInvalidTokenAction(final HttpServletResponse httpResponse) throws IOException {
    LOGGER.error("Token Failed Validation");
    httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Token Failed Validation");
}

From source file:edu.vt.middleware.servlet.filter.ClientCertFilter.java

/**
 * Handle all requests sent to this filter.
 *
 * @param  request  <code>ServletRequest</code>
 * @param  response  <code>ServletResponse</code>
 * @param  chain  <code>FilterChain</code>
 *
 * @throws  ServletException  if an error occurs
 * @throws  IOException  if an error occurs
 *//*  w w w  .  ja  v a  2  s  .  c  o  m*/
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    boolean success = false;
    final X509Certificate[] certChain = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    if (LOG.isDebugEnabled()) {
        if (certChain != null && certChain[0] != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "Received the following client certificate: " + certChain[0].getSubjectDN().getName());
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Did not receive a client certificate");
            }
        }
    }

    if (certChain != null && certChain[0] != null) {
        final String issuer = certChain[0].getIssuerX500Principal().getName();
        final String subject = certChain[0].getSubjectX500Principal().getName();
        if (this.issuerDnPattern != null && this.subjectDnPattern != null) {
            if (this.issuerDnPattern.matcher(issuer).matches()
                    && this.subjectDnPattern.matcher(subject).matches()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(issuer + " matches " + this.issuerDnPattern.pattern() + " and " + subject
                            + " matches " + this.subjectDnPattern.pattern());
                }
                success = true;
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(issuer + " does not match " + this.issuerDnPattern.pattern() + " or " + subject
                            + " does not match " + this.subjectDnPattern.pattern());
                }
            }
        } else if (this.issuerDnPattern != null) {
            if (this.issuerDnPattern.matcher(issuer).matches()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(issuer + " matches " + this.issuerDnPattern.pattern());
                }
                success = true;
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(issuer + " does not match " + this.issuerDnPattern.pattern());
                }
            }
        } else if (this.subjectDnPattern != null) {
            if (this.subjectDnPattern.matcher(subject).matches()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(subject + " matches " + this.subjectDnPattern.pattern());
                }
                success = true;
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(subject + " does not match " + this.subjectDnPattern.pattern());
                }
            }
        } else {
            success = true;
        }
    } else if (!this.requireCert) {
        success = true;
    }

    if (!success) {
        if (response instanceof HttpServletResponse) {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Request blocked by filter");
            return;
        } else {
            throw new ServletException("Request blocked by filter");
        }
    }
    chain.doFilter(request, response);
}

From source file:com.haulmont.cuba.web.controllers.StaticContentController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path))
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");

    ServletContext context = req.getSession().getServletContext();

    final URL url;
    try {// w  w w  . j a v a  2  s. co m
        url = context.getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }
    if (url == null)
        return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");

    final String mimeType = getMimeType(path);

    final String realpath = context.getRealPath(path);
    if (realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile())
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        else {
            return createLookupResult(req, f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req),
                    url);
        }
    } else {
        try {
            // Try as a JAR Entry
            final ZipEntry ze = ((JarURLConnection) url.openConnection()).getJarEntry();
            if (ze != null) {
                if (ze.isDirectory())
                    return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                else
                    return createLookupResult(req, ze.getTime(), mimeType, (int) ze.getSize(),
                            acceptsDeflate(req), url);
            } else
                // Unexpected?
                return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), url);
        } catch (ClassCastException e) {
            // Unknown resource type
            return createLookupResult(req, -1, mimeType, -1, acceptsDeflate(req), url);
        } catch (IOException e) {
            return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }
}