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:com.haulmont.cuba.core.controllers.FileDownloadController.java

protected UserSession getSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UUID sessionId;/*from  ww w . j a v  a 2  s.co  m*/
    try {
        sessionId = UUID.fromString(request.getParameter("s"));
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    UserSession session = userSessions.getAndRefresh(sessionId);
    if (session == null)
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return session;
}

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

@Override
public void get(@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  ww .  j  a  v  a  2  s.  c  o  m*/
        ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Boolean hasCommands = null;

        if (userId == null) {
            String apiKey = (String) headers.get(RestApi.API_KEY);
            ControllerRelay relay = ControllerRelay.getRelay(apiKey);

            if (relay == null) {
                throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        RestException.INTERNAL_ERROR, "Relay was lost");
            }
            for (PendingCommand cmd : PendingCommand.getCommandsToSend(relay, true)) {
                list.add(toJSON(cmd));
            }
            hasCommands = PendingCommand.hasCommands(relay);
        } else {
            User user = User.getUserByUserId(userId);

            if (user == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SUCH_USER,
                        "Invalid user access to location");
            }
            String locationId = req.getParameter("locationId");
            Collection<ControllerRelay> relays;

            if (locationId == null) {
                relays = new ArrayList<ControllerRelay>();
                for (Location location : user.getLocations()) {
                    relays.addAll(ControllerRelay.findRelaysInLocation(location));
                }
            } else {
                boolean mine = false;

                for (String lid : user.getLocationIds()) {
                    if (lid.equals(locationId)) {
                        mine = true;
                        break;
                    }
                }
                Location location = Location.getLocation(locationId);

                if (location == null || (!mine && !userId.equals(location.getOwnerId()))) {
                    throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PARAMETER,
                            "No such location: " + locationId);
                }
                relays = ControllerRelay.findRelaysInLocation(location);
            }
            for (ControllerRelay relay : relays) {
                for (PendingCommand cmd : PendingCommand.getCommands(relay)) {
                    list.add(toJSON(cmd));
                }
            }
        }
        if (hasCommands != null) {
            resp.setHeader("x-imaginary-has-commands", String.valueOf(hasCommands));
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().println((new JSONArray(list)).toString());
        resp.getWriter().flush();
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }
}

From source file:byps.test.servlet.BypsServlet.java

/**
 * Overrides the testAdapter function in order to modify the application
 * version.//from   w  w  w.j av  a  2 s .c  om
 */
@Override
protected void doTestAdapter(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (!config.isTestAdapterEnabled()) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    final String testAdapter = request.getParameter(HTestAdapter.KEY_PARAM);
    if (testAdapter == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (testAdapter.equals(HTestAdapter.SET_SERVER_APP_VERSION)) {
        String versionStr = request.getParameter(HTestAdapter.VERSION);
        MySession.appVersion = Integer.parseInt(versionStr);
        return;
    }

    super.doTestAdapter(request, response);
}

From source file:com.erudika.para.security.RestAuthFilter.java

private boolean userAuthRequestHandler(HttpServletRequest request, HttpServletResponse response) {
    Authentication userAuth = SecurityContextHolder.getContext().getAuthentication();
    User user = SecurityUtils.getAuthenticatedUser(userAuth);
    String reqUri = request.getRequestURI();
    String method = request.getMethod();
    if (user != null && user.getActive()) {
        App parentApp;/*from w  w  w.j  a va 2  s  .com*/
        if (userAuth instanceof JWTAuthentication) {
            parentApp = ((JWTAuthentication) userAuth).getApp();
        } else {
            parentApp = Para.getDAO().read(App.id(user.getAppid()));
        }
        if (parentApp != null) {
            String resource = RestUtils.extractResourceName(request);
            if (!parentApp.isAllowedTo(user.getId(), resource, request.getMethod())) {
                RestUtils
                        .returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN,
                                Utils.formatMessage(
                                        "You don't have permission to access this resource. "
                                                + "[user: {0}, resource: {1} {2}]",
                                        user.getId(), method, reqUri));
                return false;
            }
        } else {
            RestUtils.returnStatusResponse(response, HttpServletResponse.SC_NOT_FOUND, "App not found.");
            return false;
        }
    } else {
        RestUtils.returnStatusResponse(response, HttpServletResponse.SC_UNAUTHORIZED, Utils
                .formatMessage("You don't have permission to access this resource. [{0} {1}]", method, reqUri));
        return false;
    }
    return true;
}

From source file:edu.mayo.cts2.framework.plugin.service.lexevs.bulk.codesystemversion.controller.CodeSystemVersionBulkDownloadController.java

/**
 * Download./*from   ww w  .  j  a va 2 s .c om*/
 *
 * @param response the response
 * @param codingschemes the codingschemes
 * @param fields the fields
 * @param separator the separator
 * @throws LBException the lB exception
 */
@RequestMapping(value = "/exporter/codingscheme")
public void download(HttpServletResponse response,
        @RequestParam(value = "meddratoken", defaultValue = "") String meddraToken,
        @RequestParam(value = "codingschemes", defaultValue = "") String codingschemes,
        @RequestParam(value = "fields", defaultValue = "") String fields,
        @RequestParam(value = "separator", defaultValue = DEFAULT_SEPARATOR) char separator,
        @RequestParam(value = "filename", defaultValue = DEFAULT_FILE_NAME) String filename)
        throws LBException {

    if (StringUtils.isBlank(codingschemes)) {
        throw new UserInputException("'codingschemes' parameter is required.");
    }

    boolean isValidMeddraToken = false;
    if (StringUtils.isNotBlank(meddraToken)) {
        boolean validates = this.mssoUserValidator.isValid(meddraToken);
        if (!validates) {
            try {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid MedDRA token.");
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            isValidMeddraToken = true;
        }
    }

    List<String> fieldsList;
    if (StringUtils.isBlank(fields)) {
        fieldsList = DEFAULT_FIELDS;
    } else {
        fieldsList = Arrays.asList(StringUtils.split(fields, ','));
    }

    this.setHeaders(response, filename);

    Set<CodingSchemeReference> references = new HashSet<CodingSchemeReference>();

    for (String codingScheme : StringUtils.split(codingschemes, ',')) {
        if (codingScheme.equals(CodeSystemVersionBulkDownloader.ALL_CODINGSCHEMES)) {
            continue;
        }
        String[] parts = StringUtils.split(codingScheme, ':');

        CodingSchemeReference reference = new CodingSchemeReference();
        reference.setCodingScheme(parts[0]);

        if (parts.length == 2) {
            reference.setVersionOrTag(Constructors.createCodingSchemeVersionOrTagFromVersion(parts[1]));
        }

        references.add(reference);
    }

    Set<CodingSchemeReference> exclusions = new HashSet<CodingSchemeReference>();
    exclusions.addAll(this.nciMetaExclusions);
    if (!isValidMeddraToken) {
        exclusions.addAll(this.meddraExclusions);
    }

    try {
        this.codeSystemVersionBulkDownloader.download(response.getOutputStream(), references, exclusions,
                fieldsList, separator);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    try {
        response.flushBuffer();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * /*from   w  w  w . ja  v  a 2 s.  c om*/
 * @param n # of strings.
 * @return the latest n strings of the dasish database log file.
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/logDatabase/{n}")
@Transactional(readOnly = true)
public String getDasishBackendLog(@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.logDatabaseLocation", n);
    } else {
        this.DEVELOPER_RIGHTS_EXPECTED();
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        return "Coucou.";
    }
}

From source file:org.wwarn.cms.authentication.LoginCas.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
    // Extract username
    String username = req.getParameter("u");
    if (username == null || username.length() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
    }/* w ww . ja  va 2  s  .c o  m*/
    // Extract CAS ticket
    String ticket = req.getParameter("t");
    if (ticket == null) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Ticket not specified");
    }

    try {
        // Add ticket to model for javascript and template access
        Map<String, Object> model = new HashMap<String, Object>(7, 1.0f);

        // Validate our proxy CAS ticket
        Cas20ProxyTicketValidator tv = new Cas20ProxyTicketValidator(CAS_WEBAPP_URL);
        tv.setAcceptAnyProxy(true);
        String legacyServerServiceUrl = ALFRESCO_WEBAPP_URL;
        Assertion assertion = tv.validate(ticket, legacyServerServiceUrl);
        String cas_username = assertion.getPrincipal().getName();

        // Compare usernames
        if (!username.equals(assertion.getPrincipal().getName())) {
            throw new TicketValidationException("usernames does not match: " + username + "/" + cas_username);
        }

        // Authenticate our user
        authenticationComponent.setCurrentUser(username);

        // Create a new alfresco ticket
        String alfticket = authenticationService.getCurrentTicket();
        model.put("ticket", alfticket);

        return model;
    } catch (AuthenticationException e) {
        throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Login failed");
    } catch (TicketValidationException ex) {
        ex.printStackTrace();
    } finally {
        authenticationService.clearCurrentSecurityContext();
    }

    return null;
}

From source file:nl.b3p.viewer.stripes.ProxyActionBean.java

private Resolution proxyArcIMS() throws Exception {

    HttpServletRequest request = getContext().getRequest();

    if (!"POST".equals(request.getMethod())) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }/*w  ww .ja  v  a2 s . co  m*/

    Map params = new HashMap(getContext().getRequest().getParameterMap());
    // Only allow these parameters in proxy request
    params.keySet().retainAll(Arrays.asList("ClientVersion", "Encode", "Form", "ServiceName"));
    URL theUrl = new URL(url);
    // Must not allow file / jar etc protocols, only HTTP:
    String path = theUrl.getPath();
    for (Map.Entry<String, String[]> param : (Set<Map.Entry<String, String[]>>) params.entrySet()) {
        if (path.length() == theUrl.getPath().length()) {
            path += "?";
        } else {
            path += "&";
        }
        path += URLEncoder.encode(param.getKey(), "UTF-8") + "="
                + URLEncoder.encode(param.getValue()[0], "UTF-8");
    }
    theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path);

    // TODO logging for inspecting malicious proxy use

    ByteArrayOutputStream post = new ByteArrayOutputStream();
    IOUtils.copy(request.getInputStream(), post);

    // This check makes some assumptions on how browsers serialize XML
    // created by OpenLayers' ArcXML.js write() function (whitespace etc.),
    // but all major browsers pass this check
    if (!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }

    final HttpURLConnection connection = (HttpURLConnection) theUrl.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());

    connection.connect();
    try {
        IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream());
    } finally {
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
    }

    return new StreamingResolution(connection.getContentType()) {
        @Override
        protected void stream(HttpServletResponse response) throws IOException {
            try {
                IOUtils.copy(connection.getInputStream(), response.getOutputStream());
            } finally {
                connection.disconnect();
            }

        }
    };
}

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

@ApiOperation(value = "Get account data of a current user")
@RequestMapping(method = RequestMethod.GET, value = "/accountprofile/me")
public @ResponseBody AccountProfile findAccountProfile(HttpServletResponse response) throws IOException {
    Long user = userManager.getUserId();
    if (user == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }/*from w w  w.j a v a  2  s .  c  o  m*/
    return profileManager.getAccountProfileById(user.toString());
}

From source file:org.shredzone.cilla.view.GalleryView.java

/**
 * Shows a map of the location the picture was taken.
 */// w  w  w . j a  va2 s.  c om
@Framed
@View(pattern = "/show/gallery/${section.id}/map/${picture.id}.html", name = "gallery.map")
public String galleryMapView(@PathPart("section.id") GallerySection section,
        @PathPart("picture.id") Picture picture, HttpServletRequest req, HttpServletResponse resp)
        throws ViewException {
    if (!pageService.isVisible(section.getPage())) {
        throw new ErrorResponseException(HttpServletResponse.SC_FORBIDDEN);
    }

    if (!section.getPictures().contains(picture)) {
        // There is such a picture, but not in this gallery!
        throw new PageNotFoundException("No such picture in this gallery.");
    }

    if (redirectRestricted(section.getPage(), req, resp)) {
        return null;
    }

    req.setAttribute("page", section.getPage());
    req.setAttribute("section", section);
    req.setAttribute("picture", picture);

    return "section/gallery/map.jsp";
}