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

/**
 * /*from w  ww  .  ja v  a2s. c o  m*/
 * @return An {@link AnnotationInfoList}-element containing the list of {@link AnnotationInfo} elements of ALL the annotations,
 * with the latest (youngest) annotation on the top.
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("annotations")
@Transactional(readOnly = true)
public JAXBElement<AnnotationInfoList> getAllAnnotations() throws IOException {
    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return new ObjectFactory().createAnnotationInfoList(new AnnotationInfoList());
    }
    String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
    if (typeOfAccount.equals(admin) || typeOfAccount.equals(developer)) {
        final AnnotationInfoList annotationInfoList = dbDispatcher.getAllAnnotationInfos();
        return new ObjectFactory().createAnnotationInfoList(annotationInfoList);
    } else {
        this.DEVELOPER_RIGHTS_EXPECTED();
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        return new ObjectFactory().createAnnotationInfoList(new AnnotationInfoList());
    }
}

From source file:com.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void post(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {//from  w w w  .  j ava 2s . c o m
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());

        if (!object.has("pairingCode") || object.isNull("pairingCode")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        String code = object.getString("pairingCode");

        if (code.equalsIgnoreCase("null")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        Location location = Location.findForPairing(code);

        if (location == null) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PAIRING_CODE,
                    "Invalid pairing code; pairing did not occur");
        }
        String relayName;

        if (object.has("name") && !object.isNull("name")) {
            relayName = object.getString("name");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA,
                    "Missing relay name from JSON");
        }
        ControllerRelay relay = location.pair(code, relayName);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.PAIRING_FAILURE,
                    "Pairing failed due to an invalid pairing code or expired pairing code");
        }
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("apiKeyId", relay.getControllerRelayId());
        json.put("apiKeySecret", Configuration.decrypt(location.getLocationId(), relay.getApiKeySecret()));
        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.getWriter().println((new JSONObject(json)).toString());
        resp.getWriter().flush();
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}

From source file:info.magnolia.cms.security.SecurityFilter.java

/**
 * Checks access from Listener / Authenticator / AccessLock.
 * @param req HttpServletRequest as received by the service method
 * @param res HttpServletResponse as received by the service method
 * @return boolean <code>true</code> if access to the resource is allowed
 * @throws IOException can be thrown when the servlet is unable to write to the response stream
 *///from w w w .  j  a  v  a  2 s  .  c  o  m
protected boolean isAllowed(HttpServletRequest req, HttpServletResponse res) throws IOException {
    if (Lock.isSystemLocked()) {
        res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return false;
    } else if (Authenticator.isAuthenticated(req)) {
        return true;
    } else if (SecureURI.isUnsecure(Path.getURI(req)))
        return true;
    else if (SecureURI.isProtected(Path.getURI(req))) {
        return authenticate(req, res);
    } else if (!Listener.isAllowed(req)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }
    return true;
}

From source file:com.liusoft.dlog4j.upload.SecurityFCKUploadServlet.java

/**
 * ?//  w  w w.  ja  v  a2s.com
 */
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    //??????(??)
    SessionUserObject loginUser = UserLoginManager.getLoginUser(req, res, true);
    if (loginUser != null) {
        super.doPost(req, res);//post??
        Integer errno = (Integer) req.getAttribute("errno");
        if (errno != null && errno.intValue() == 0) {
            //?
            FckUploadFileBean fbean = new FckUploadFileBean();
            try {
                Long fileSize = (Long) req.getAttribute("file.size");
                Integer fileType = (Integer) req.getAttribute("file.type");
                String savePath = (String) req.getAttribute("file.path");
                String uriPath = (String) req.getAttribute("file.uri");
                if (fileSize != null)
                    fbean.setFileSize(fileSize.intValue());
                if (fileType != null)
                    fbean.setFileType(fileType.intValue());
                fbean.setSavePath(savePath);
                fbean.setUri(uriPath);
                HttpSession ssn = req.getSession(true);
                //SESSION_ID??Cookie
                RequestUtils.setCookie(req, res, Globals.SESSION_ID_KEY_IN_COOKIE, ssn.getId(), -1);
                fbean.setSessionId(ssn.getId());
                fbean.setUser(new UserBean(loginUser.getId()));
                fbean.setUploadTime(new Date());
                FCKUploadFileDAO.createUploadFileItem(fbean);
            } catch (Exception e) {
                log.error("Writting upload file info failed.", e);
            }
        }
        return;
    }
    res.sendError(HttpServletResponse.SC_FORBIDDEN);
}

From source file:elw.web.ControllerElw.java

public HashMap<String, Object> noAuth(HttpServletRequest req, HttpServletResponse resp, boolean page,
        final String message) throws IOException {
    if (page) {/*  w  ww . ja  va  2  s  .  c  o  m*/
        Message.addWarn(req, message);
        ControllerAuth.storeSuccessRedirect(req);
        resp.sendRedirect(elwServerConfig.getBaseUrl() + "auth.html");
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, message);
    }

    return null;
}

From source file:net.bhira.sample.api.controller.EmployeeController.java

/**
 * Fetch all the employees for the given company ID. It will return a light weight version of
 * {@link net.bhira.sample.model.Employee} model without the address and contactInfo objects.
 * //from   w  w w.j  av a  2  s.  c om
 * @param companyId
 *            the ID for {@link net.bhira.sample.model.Company}.
 * @param response
 *            the http response to which the results will be written.
 * @return an array of {@link net.bhira.sample.model.Employee} instances as JSON.
 */
@RequestMapping(value = "/employee/company/{companyId}", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getEmployeesByCompany(@PathVariable long companyId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET employee/company/{}", companyId);
                List<Employee> list = employeeService.loadByCompany(companyId);
                int count = (list == null) ? 0 : list.size();
                LOG.debug("GET employee/company/{} count = {}", companyId, count);
                body = JsonUtil.createGson().toJson(list);
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading employee/company/{}. {}", companyId, body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:net.bhira.sample.api.controller.DepartmentController.java

/**
 * Fetch all the departments for the given company ID. It will return a light weight version of
 * {@link net.bhira.sample.model.Department} model without the address and contactInfo objects.
 * /*from  www.j a va  2 s  . c  o  m*/
 * @param companyId
 *            the ID for {@link net.bhira.sample.model.Company}.
 * @param response
 *            the http response to which the results will be written.
 * @return an array of {@link net.bhira.sample.model.Department} instances as JSON.
 */
@RequestMapping(value = "/department/company/{companyId}", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getDepartmentsByCompany(@PathVariable long companyId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET department/company/{}", companyId);
                List<Department> list = departmentService.loadByCompany(companyId);
                int count = (list == null) ? 0 : list.size();
                LOG.debug("GET department/company/{} count = {}", companyId, count);
                body = JsonUtil.createGson().toJson(list);
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading department/company/{}. {}", companyId, body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:com.oneops.cms.ws.rest.CmDjMergeController.java

@ExceptionHandler(CmsSecurityException.class)
public void handleCmsSecurityException(CmsSecurityException e, HttpServletResponse response)
        throws IOException {
    sendError(response, HttpServletResponse.SC_FORBIDDEN, e);
}

From source file:it.smartcommunitylab.aac.controller.BasicProfileController.java

@ApiOperation(value = "Get basic profile of a current user")
@RequestMapping(method = RequestMethod.GET, value = "/basicprofile/me")
public @ResponseBody BasicProfile findProfile(HttpServletResponse response) throws IOException {
    Long user = userManager.getUserId();
    if (user == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }//from  ww w  . j a v a 2s  .  com
    return profileManager.getBasicProfileById(user.toString());
}