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.AnnotationResource.java

/**
 * /*from w  w  w. j  a va2  s . co m*/
 * @param annotation an {@link Annotation} object.
 * @return the {@link ResponseBody} element that contains the xml element representing 
 * the fresh annotation (with its freshly generated by the back-end external UUID), and the list
 * of action-elements representing the actions the client should care for,
 * e.g. add a cached representation for a certain target.
 * @throws IOException if sending an error fails.
 */
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
@Path("")
public JAXBElement<ResponseBody> createAnnotation(Annotation annotation) throws IOException {

    Map params = new HashMap();
    params.put("annotation", annotation);
    try {
        ResponseBody result = (ResponseBody) (new RequestWrappers(this)).wrapRequestResource(params,
                new AddAnnotation());
        if (result != null) {
            return (new ObjectFactory()).createResponseBody(result);
        } else {
            return (new ObjectFactory()).createResponseBody(new ResponseBody());
        }
    } catch (NotInDataBaseException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return (new ObjectFactory()).createResponseBody(new ResponseBody());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return (new ObjectFactory()).createResponseBody(new ResponseBody());
    }
}

From source file:com.ark.website.filter.CORSFilter.java

/**
 * Handles a CORS request that violates specification.
 * /*from  w  w  w  . j  a  v  a  2 s. c  o  m*/
 * @param request
 *            The {@link HttpServletRequest} object.
 * @param response
 *            The {@link HttpServletResponse} object.
 * @param filterChain
 *            The {@link FilterChain} object.
 * @throws IOException
 * @throws ServletException
 */
public void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) {
    String origin = request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN);
    String method = request.getMethod();
    String accessControlRequestHeaders = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);

    String message = "Invalid CORS request; Origin=" + origin + ";Method=" + method;
    if (accessControlRequestHeaders != null) {
        message = message + ";Access-Control-Request-Headers=" + accessControlRequestHeaders;
    }
    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    response.resetBuffer();

    log(message);
}

From source file:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerTest.java

@Test
public void shouldThrowRuntimeExWhenWsdlUrlNotOk200() throws Exception {

    final ServiceId serviceId = ServiceId.create(DEFAULT_CLIENT, GET_WSDL);
    final ServiceId requestingWsdlForService = ServiceId.create(DEFAULT_CLIENT, "someServiceWithWsdl122");

    MetadataServiceHandlerImpl handlerToTest = new MetadataServiceHandlerImpl();

    WsdlRequestData wsdlRequestData = new WsdlRequestData();
    wsdlRequestData.setServiceCode(requestingWsdlForService.getServiceCode());

    InputStream soapContentInputStream = new TestSoapBuilder().withClient(DEFAULT_CLIENT).withService(serviceId)
            .withModifiedBody(soapBody -> marshaller.marshal(wsdlRequestData, soapBody)).buildAsInputStream();

    when(mockProxyMessage.getSoapContent()).thenReturn(soapContentInputStream);

    setUpDatabase(requestingWsdlForService);

    mockServer.stubFor(WireMock.any(urlPathEqualTo(EXPECTED_WSDL_QUERY_PATH))
            .willReturn(aResponse().withStatus(HttpServletResponse.SC_FORBIDDEN)));
    mockServer.start();//www.  j av  a 2  s.  c  om

    handlerToTest.canHandle(serviceId, mockProxyMessage);

    thrown.expect(RuntimeException.class);
    thrown.expectMessage(containsString("Received HTTP error: 403 - Forbidden"));

    // execution, should throw..

    handlerToTest.startHandling(mockRequest, mockProxyMessage, httpClientMock, mock(OpMonitoringData.class));
}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

/**
 * Publish message to Backplane./*ww  w .j a va  2s .c  o m*/
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/message", method = { RequestMethod.POST })
public @ResponseBody Map<String, Object> postMessages(HttpServletRequest request, HttpServletResponse response,
        @RequestBody Map<String, Map<String, Object>> messagePostBody,
        @RequestParam(value = OAUTH2_ACCESS_TOKEN_PARAM_NAME, required = false) String access_token,
        @RequestHeader(value = "Authorization", required = false) String authorizationHeader)
        throws SimpleDBException, BackplaneServerException {

    ServletUtil.checkSecure(request);

    final TimerContext context = v2PostTimer.time();

    try {
        Token token = Token.fromRequest(daoFactory, request, access_token, authorizationHeader);
        if (token.getType().isRefresh() || !token.getType().isPrivileged()) {
            throw new TokenException("Invalid token type: " + token.getType(),
                    HttpServletResponse.SC_FORBIDDEN);
        }

        BackplaneMessage message = parsePostedMessage(messagePostBody, token);
        daoFactory.getBackplaneMessageDAO().persist(message);

        aniLogNewMessage(request, message, token);

        response.setStatus(HttpServletResponse.SC_CREATED);
        return null;

    } catch (TokenException te) {
        return handleTokenException(te, response);
    } catch (InvalidRequestException ire) {
        throw ire;
    } catch (Exception e) {
        throw new BackplaneServerException("Error processing post request: " + e.getMessage(), e);
    } finally {
        context.stop();
    }
}

From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java

private void sendSaveProjectResult() {
    try {/*from   w  ww.  j a v  a2  s .  c  o m*/
        currentProject = objectMapper.readValue(request.getParameter("project"), Project.class);
        String publicId = request.getParameter("publicId");
        String type = request.getParameter("projectType");
        MySqlConnector.getInstance().saveProject(sessionInfo.getUserInfo(), publicId, currentProject, type);
        writeResponse("", HttpServletResponse.SC_OK);
    } catch (IOException e) {
        writeResponse("Can't parse file", HttpServletResponse.SC_BAD_REQUEST);
    } catch (NullPointerException e) {
        writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST);
    } catch (DatabaseOperationException e) {
        writeResponse(e.getMessage(), HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

@RequestMapping(value = "/api/service.{type}", method = RequestMethod.GET)
public void serviceByGet(@PathVariable(value = "type") String type, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "service") String serviceName, @RequestParam(value = "method") String methodName,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!connect(sessionId, response))
        return;/*from   www  . j  a va2s .co m*/

    if (!restServicePermissions.isPermitted(serviceName, methodName)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    try {
        Map<String, String[]> parameterMap = request.getParameterMap();
        List<String> paramValuesString = new ArrayList<>();
        List<Class> paramTypes = new ArrayList<>();

        int idx = 0;
        while (true) {
            String[] _values = parameterMap.get("param" + idx);
            if (_values == null)
                break;
            if (_values.length > 1) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Multiple values for param" + idx);
                return;
            }
            paramValuesString.add(_values[0]);

            String[] _types = parameterMap.get("param" + idx + "_type");
            if (_types != null) {
                if (_types.length > 1) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Multiple values for param" + idx + "_type");
                    return;
                }
                paramTypes.add(idx, ClassUtils.forName(_types[0], null));
            } else if (!paramTypes.isEmpty()) {
                //types should be defined for all parameters or for none of them
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Parameter type for param" + idx + " is not defined");
                return;
            }
            idx++;
        }

        Converter converter = conversionFactory.getConverter(type);
        ServiceRequest serviceRequest = new ServiceRequest(serviceName, methodName, converter);
        serviceRequest.setParamTypes(paramTypes);
        serviceRequest.setParamValuesString(paramValuesString);

        Object result = serviceRequest.invokeMethod();

        String converted = converter.processServiceMethodResult(result, serviceRequest.getMethodReturnType());
        writeResponse(response, converted, converter.getMimeType());
    } catch (Throwable e) {
        sendError(request, response, e);
    } finally {
        authentication.end();
    }
}

From source file:com.sun.faban.harness.webclient.CLIServlet.java

private void doSubmit(String[] reqC, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (reqC.length < 3) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Benchmark and profile not provided in request.");
        return;/*from  w w w  . j a  v a 2  s . c  o  m*/
    }
    // first is the bench name
    BenchmarkDescription desc = BenchmarkDescription.getDescription(reqC[1]);
    if (desc == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Benchmark " + reqC[1] + " not deployed.");
        return;
    }
    try {
        String user = null;
        String password = null;
        boolean hasPermission = true;

        ArrayList<String> runIdList = new ArrayList<String>();

        DiskFileUpload fu = new DiskFileUpload();
        // No maximum size
        fu.setSizeMax(-1);
        // maximum size that will be stored in memory
        fu.setSizeThreshold(8192);
        // the location for saving data larger than getSizeThreshold()
        fu.setRepositoryPath(Config.TMP_DIR);

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem item = (FileItem) i.next();
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                if ("sun".equals(fieldName)) {
                    user = item.getString();
                } else if ("sp".equals(fieldName)) {
                    password = item.getString();
                }
                continue;
            }
            if (reqC[2] == null) // No profile
                break;

            if (desc == null)
                break;

            if (!"configfile".equals(fieldName))
                continue;

            if (Config.SECURITY_ENABLED) {
                if (Config.CLI_SUBMITTER == null || Config.CLI_SUBMITTER.length() == 0
                        || !Config.CLI_SUBMITTER.equals(user)) {
                    hasPermission = false;
                    break;
                }
                if (Config.SUBMIT_PASSWORD == null || Config.SUBMIT_PASSWORD.length() == 0
                        || !Config.SUBMIT_PASSWORD.equals(password)) {
                    hasPermission = false;
                    break;
                }
            }

            String usrDir = Config.PROFILES_DIR + reqC[2];
            File dir = new File(usrDir);
            if (dir.exists()) {
                if (!dir.isDirectory()) {
                    logger.severe(usrDir + " should be a directory");
                    dir.delete();
                    logger.fine(dir + " deleted");
                } else
                    logger.fine("Saving parameter file to" + usrDir);
            } else {
                logger.fine("Creating new profile directory for " + reqC[2]);
                if (dir.mkdirs())
                    logger.fine("Created new profile directory " + usrDir);
                else
                    logger.severe("Failed to create profile " + "directory " + usrDir);
            }

            // Save the latest config file into the profile directory
            String dstFile = Config.PROFILES_DIR + reqC[2] + File.separator + desc.configFileName + "."
                    + desc.shortName;

            item.write(new File(dstFile));
            runIdList.add(RunQ.getHandle().addRun(user, reqC[2], desc));
        }

        response.setContentType("text/plain");
        Writer writer = response.getWriter();

        if (!hasPermission) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            writer.write("Permission denied!\n");
        }

        if (runIdList.size() == 0)
            writer.write("No runs submitted.\n");
        for (String newRunId : runIdList) {
            writer.write(newRunId);
        }

        writer.flush();
        writer.close();
    } catch (ServletException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new ServletException(e);
    }
}

From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java

private void sendSaveFileResult() {
    try {//from w  w w . ja v a  2  s  . c om
        ProjectFile file = objectMapper.readValue(request.getParameter("file"), ProjectFile.class);
        MySqlConnector.getInstance().saveFile(sessionInfo.getUserInfo(), file);
        writeResponse("ok", HttpServletResponse.SC_OK);
    } catch (IOException e) {
        writeResponse("Can't parse file", HttpServletResponse.SC_BAD_REQUEST);
    } catch (NullPointerException e) {
        writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST);
    } catch (DatabaseOperationException e) {
        writeResponse(e.getMessage(), HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:net.gplatform.sudoor.server.cors.CorsFilter.java

/**
 * Handles a CORS request that violates specification.
 * /*from www .  j ava2  s  .co m*/
 * @param request
 *            The {@link HttpServletRequest} object.
 * @param response
 *            The {@link HttpServletResponse} object.
 * @param filterChain
 *            The {@link FilterChain} object.
 */
private void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) {
    String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
    String method = request.getMethod();
    String accessControlRequestHeaders = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);

    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    response.resetBuffer();

    if (log.isDebugEnabled()) {
        // Debug so no need for i18n
        StringBuilder message = new StringBuilder("Invalid CORS request; Origin=");
        message.append(origin);
        message.append(";Method=");
        message.append(method);
        if (accessControlRequestHeaders != null) {
            message.append(";Access-Control-Request-Headers=");
            message.append(accessControlRequestHeaders);
        }
        log.debug(message.toString());
    }
}