Example usage for javax.servlet.http HttpServletRequest getServletPath

List of usage examples for javax.servlet.http HttpServletRequest getServletPath

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServletPath.

Prototype

public String getServletPath();

Source Link

Document

Returns the part of this request's URL that calls the servlet.

Usage

From source file:net.maritimecloud.identityregistry.controllers.RoleController.java

/**
 * Updates a Role/*from  w  w  w.ja  va 2  s.c o m*/
 *
 * @return a reply...
 * @throws McBasicRestException
 */
@RequestMapping(value = "/api/org/{orgMrn}/role/{roleId}", method = RequestMethod.PUT)
@ResponseBody
@PreAuthorize("(hasRole('ORG_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn) and #input.roleName != 'ROLE_SITE_ADMIN') or hasRole('SITE_ADMIN')")
public ResponseEntity<?> updateRole(HttpServletRequest request, @PathVariable String orgMrn,
        @PathVariable Long roleId, @Valid @RequestBody Role input, BindingResult bindingResult)
        throws McBasicRestException {
    ValidateUtil.hasErrors(bindingResult, request);
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        Role role = this.roleService.getById(roleId);
        if (role == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ROLE_NOT_FOUND,
                    request.getServletPath());
        }
        if (role.getIdOrganization().compareTo(org.getId()) != 0) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.URL_DATA_MISMATCH,
                    request.getServletPath());
        }
        input.copyTo(role);
        this.roleService.save(role);
        return new ResponseEntity<>(HttpStatus.OK);
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:com.google.nigori.server.NigoriServlet.java

/**
 * Handle initial request from client and dispatch to appropriate handler or return error message.
 *///from   w w  w  .j  av  a2 s  .  c o  m
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        addCorsHeaders(resp);
        // Subset of path managed by this servlet; e.g. if URI is "/nigori/get" and servlet path
        // is "/nigori, then we want to retrieve "get" as the request type
        int startIndex = req.getServletPath().length() + 1;
        String requestURI = req.getRequestURI();
        if (requestURI.length() <= startIndex) {
            ServletException s = new ServletException(HttpServletResponse.SC_BAD_REQUEST,
                    "No request type specified.\n" + supportedTypes + "\n");
            log.fine(s.toString());
            s.writeHttpResponse(resp);
            return;
        }
        String requestType = requestURI.substring(startIndex);
        String requestMimetype = req.getContentType();
        RequestHandlerType handlerType = new RequestHandlerType(requestMimetype, requestType);

        RequestHandler handler = handlers.get(handlerType);
        if (handler == null) {
            throw new ServletException(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "Unsupported request pair: " + handlerType + "\n" + supportedTypes + "\n");
        }
        try {
            handler.handle(req, resp);
        } catch (NotFoundException e) {
            ServletException s = new ServletException(HttpServletResponse.SC_NOT_FOUND,
                    e.getLocalizedMessage());
            log.fine(s.toString());
            s.writeHttpResponse(resp);
        } catch (UnauthorisedException e) {
            ServletException s = new ServletException(HttpServletResponse.SC_UNAUTHORIZED,
                    "Authorisation failed: " + e.getLocalizedMessage());
            log.warning(s.toString());
            s.writeHttpResponse(resp);
        } catch (IOException ioe) {
            throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal error sending data to client");
        } catch (MessageLibrary.JsonConversionException jce) {
            throw new ServletException(HttpServletResponse.SC_BAD_REQUEST,
                    "JSON format error: " + jce.getMessage());
        } catch (RuntimeException re) {
            log.severe(re.toString());
            throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, re.toString());
        }

    } catch (ServletException e) {
        log.severe(e.toString());
        e.writeHttpResponse(resp);
    }
}

From source file:edu.usc.lunchnlearn.elasticsearch.interceptor.BreadCrumbInterceptor.java

private Crumb createIndexCrumb(Crumb firstCrumb, HttpServletRequest request) {
    Crumb indexCrumb = new Crumb();
    StringBuffer sb = new StringBuffer();

    if (request.getScheme().equals("http") && request.getHeader("x-forwarded-proto") != null) {
        sb.append("https://");
    } else {/* www .j  ava  2 s. c  o m*/
        sb.append(request.getScheme()).append("://");
    }

    sb.append(request.getServerName());

    if (request.getServerPort() != 80 && request.getServerPort() != 443) {
        sb.append(":").append(request.getServerPort());
    }

    sb.append(request.getContextPath());
    sb.append(request.getServletPath());
    sb.append("/index.html");

    indexCrumb.setUrl(sb.toString());
    indexCrumb.setDisplayText("Index");
    indexCrumb.setX(firstCrumb.getX() - 100L);

    return indexCrumb;
}

From source file:fr.univrouen.poste.web.ExceptionController.java

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {/*w w  w  .ja  v  a2s .c om*/

    if (ex instanceof AccessDeniedException) {
        return this.deniedHandler(request, response);
    }

    String ip = request.getRemoteAddr();
    if (ex instanceof MultipartException) {
        log.warn("MultipartException with this client " + ip
                + ". We can assume that the client has canceled his request (because of a double-click / double-submit of the form for example).",
                ex);
    } else {
        log.error("Uncaught exception  with this client " + ip, ex);
    }

    // hack for logging uploads failed 
    if (request.getServletPath().matches("/postecandidatures/[0-9]*/addFile")) {
        String posteCandidatureId = request.getServletPath().replaceAll("/postecandidatures/([0-9]*)/addFile",
                "$1");
        PosteCandidature posteCandidature = PosteCandidature
                .findPosteCandidature(Long.valueOf(posteCandidatureId));
        logService.logActionFile(LogService.UPLOAD_FAILED_ACTION, posteCandidature, null, request, new Date());
    }

    //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    ModelAndView modelAndview = new ModelAndView("uncaughtException");
    modelAndview.addObject("exception", ex);
    return modelAndview;
}

From source file:com.spring.tutorial.controllers.DefaultController.java

@RequestMapping(value = "/my-drive/dropbox/downloads/**", method = RequestMethod.GET)
public String getDropboxFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException, DbxException {

    config = new DbxRequestConfig("JavaTutorial/1.0", Locale.getDefault().toString());
    DbxClient client = new DbxClient(config, (String) request.getSession().getAttribute("dropbox_token"));

    String path = request.getServletPath()
            .substring(request.getServletPath().indexOf("/my-drive/dropbox/downloads/") + 27);
    ServletOutputStream outputStream = response.getOutputStream();
    try {/*  www  . ja  v  a2s .  c  o m*/

        DbxEntry.File downloadedFile = client.getFile(path, null, outputStream);
        String mimeType = "application/octet-stream";
        response.setContentType(mimeType);
        response.setContentLength((int) downloadedFile.numBytes);
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadedFile.name);
    } finally {
        outputStream.close();
    }
    return "";
}

From source file:net.maritimecloud.identityregistry.controllers.LogoController.java

/**
 * Creates or updates a logo for an organization
 * @param request so we can get the servlet path
 * @param orgMrn the resource/*from w  ww  . ja  v a  2s  .  c o  m*/
 * @param logo the logo bytes
 * @throws McBasicRestException
 */
@RequestMapping(value = "/api/org/{orgMrn}/logo", method = RequestMethod.PUT)
@ResponseBody
@PreAuthorize("hasRole('ORG_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<?> createLogoPut(HttpServletRequest request, @PathVariable String orgMrn,
        @RequestBody byte[] logo) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        try {
            ByteArrayInputStream inputLogo = new ByteArrayInputStream(logo);
            this.updateLogo(org, inputLogo);
            organizationService.save(org);
        } catch (IOException e) {
            e.printStackTrace();
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.INVALID_IMAGE,
                    request.getServletPath());
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:net.oneandone.jasmin.main.Servlet.java

private void doGetUnchecked(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String path;//from   w w w.  j a  v a2 s.  co m

    path = request.getPathInfo();
    if (path == null) {
        response.sendRedirect(request.getContextPath() + request.getServletPath() + "/");
        return;
    }
    lazyInit(request);
    LOG.debug("get " + path);
    if (path.startsWith("/get/")) {
        get(request, response, path.substring(5));
        return;
    }
    if (path.equals("/admin/")) {
        main(response);
        return;
    }
    if (path.equals("/admin/repository")) {
        repository(request, response);
        return;
    }
    if (path.equals("/admin/hashCache")) {
        hashCache(response);
        return;
    }
    if (path.equals("/admin/contentCache")) {
        contentCache(response);
        return;
    }
    if (path.startsWith(MODULE_PREFIX)) {
        module(request, response, path.substring(MODULE_PREFIX.length()));
        return;
    }
    if (path.equals("/admin/reload")) {
        reload(response);
        return;
    }
    if (path.equals("/admin/check")) {
        fileCheck(response);
        return;
    }
    notFound(request, response);
}

From source file:org.mashupmedia.controller.remote.RemoteLibraryController.java

@RequestMapping(value = "/album-art/{uniqueName}/{imageTypeValue}/{songId}", method = { RequestMethod.GET,
        RequestMethod.HEAD })/*  w w  w.  j a v  a  2  s . com*/
public ModelAndView handleAlbumArt(HttpServletRequest request, @PathVariable String uniqueName,
        @PathVariable String imageTypeValue, @PathVariable Long songId, Model model) throws IOException {
    Library remoteLibrary = getRemoteLibrary(uniqueName, request, true);
    if (remoteLibrary == null) {
        logger.info("Unable to load album art, unknown host: " + request.getRemoteHost());
        return null;
    }

    logInAsSystemuser(request);

    ImageType imageType = ImageHelper.getImageType(imageTypeValue);
    StringBuilder servletPathBuilder = new StringBuilder(request.getServletPath());
    servletPathBuilder.append("/music/album-art");
    servletPathBuilder.append("/" + imageType.toString().toLowerCase());
    MediaItem mediaItem = mediaManager.getMediaItem(songId);
    if (mediaItem == null || !(mediaItem instanceof Song)) {
        return null;
    }
    Song song = (Song) mediaItem;
    Album album = song.getAlbum();
    long albumId = album.getId();

    servletPathBuilder.append("/" + albumId);
    return new ModelAndView("forward:" + servletPathBuilder.toString());
}

From source file:controllerClasses.StudyController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  ww.  jav  a  2  s.c  o m*/
 *
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("In StudyController");
    HttpSession session = null;
    //String action = request.getParameter("action");
    String userPath = request.getServletPath().substring(1, request.getServletPath().length());
    RequestDispatcher dispatcher = null;
    String reDirect = null;
    String studyCode = null;
    String choice = null;
    StudyDB studyDB = null;
    List<Study> studies = null;
    User user = null;

    try {
        HttpSession session2 = request.getSession();
        String email = (String) session2.getAttribute("email");
        session = request.getSession(false);
        if (session != null && session.getAttribute("theUser") != null) {
            user = (User) session.getAttribute("theUser");
            studyDB = new StudyDB();
            if (userPath.equals("participate")) {
                studyCode = request.getParameter("studyCode");
                String email1 = (String) session2.getAttribute("email");

                System.out.println("user email in study controller from session" + email1);
                if (studyCode != null && !studyCode.isEmpty()) {
                    System.out.println("studyCode in first block:  " + studyCode);
                    Study study = studyDB.getStudy(studyCode);
                    request.setAttribute("study", study);
                    reDirect = "question";
                } else {

                    List result = StudyDB.retrieveStudies1(email);
                    Study study = new Study();

                    String s = study.getName();
                    System.out.println("Controller study object" + s);

                    request.setAttribute("study", study);
                    request.setAttribute("result", result);
                    reDirect = "participate";
                }
            } else if (userPath.equals("answer")) {
                studyCode = request.getParameter("studyCode");
                choice = request.getParameter("choice");
                System.out.println("studyCode: " + studyCode);
                System.out.println("choice: " + choice);

                List result = StudyDB.answer(email, choice, studyCode);

                int i = UserDB.updateParticipations(email);
                user.setParticipation(i);
                int j = UserDB.updateCoins(email);
                user.setCoins(j);
                int k = UserDB.updateParticipants(email, studyCode);
                user.setParticipants(k);
                int participants = UserDB.getAttribute(email);
                int coins = UserDB.coins(email);
                int participation = UserDB.participation(email);

                user.setParticipants(participants);
                user.setCoins(coins);
                user.setParticipation(participation);

                request.setAttribute("user", user);

                /**
                List result = studyDB.getStudies();
                List<Study> sInStart = new ArrayList<Study>();
                for(Study study: studies){
                   if(study.getStatus().equalsIgnoreCase("start")){
                      sInStart.add(study);
                   }
                }
                System.out.println(sInStart.size());**/
                session.setAttribute("theUser", user);
                request.setAttribute("openStudies", result);
                request.setAttribute("result", result);

                reDirect = "participate";
            } else if (userPath.equals("myStudies")) {
                List result = studyDB.retrieveStudies(email);
                Study study = new Study();
                request.setAttribute("study", study);
                request.setAttribute("result", result);
                session.setAttribute("result", result);
                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            } else if (userPath.equals("edit")) {
                studyCode = request.getParameter("studyCode");
                String email3 = (String) session2.getAttribute("email");

                Study study = new Study();
                study = StudyDB.getStudy(studyCode);
                /**
                if(session.getAttribute("myStudies")!=null){
                studies = (List<Study>) session.getAttribute("myStudies");
                }else{
                studies = studyDB.getStudies(user.getEmail());
                }
                for(Study study: studies){
                if(study.getCode() == Integer.parseInt(studyCode)){
                request.setAttribute("study", studyDB.getStudy(Integer.parseInt(studyCode)));
                break;
                }
                }**/
                request.setAttribute("study", study);
                reDirect = "editstudy";
                /*Pending*/
            } else if (userPath.equals("update")) {
                studyCode = request.getParameter("studyCode");
                Study study = new Study();
                study.setCode(Integer.parseInt(request.getParameter("studyCode")));
                study.setName(request.getParameter("studyName"));
                study.setQuestion(request.getParameter("questionText"));
                study.setRequestedParticipants(Integer.parseInt(request.getParameter("participants")));
                study.setDescription(request.getParameter("description"));
                Part part = request.getPart("imageFile");
                String fileName = part.getSubmittedFileName();
                String file1 = "images/" + fileName;
                study.setImageURL(file1);

                System.out.println("IMAGE NAME" + file1);
                System.out.println("IMAGE NAME FROM STUDY OBJECT" + study.getImageURL());

                List result = StudyDB.updateStudy(study, email);
                /**
                if(session.getAttribute("myStudies")!=null){
                studies = (List<Study>) session.getAttribute("myStudies");
                }else{
                studies = studyDB.getStudies(user.getEmail());
                }
                for(Study study: studies){
                if(study.getCode() == Integer.parseInt(studyCode)){
                studies.remove(study);
                study.setCode(Integer.parseInt(request.getParameter("studyCode")));
                study.setName(request.getParameter("studyName"));
                study.setQuestion(request.getParameter("questionText"));
                study.setRequestedParticipants(Integer.parseInt(request.getParameter("participants")));
                study.setDescription(request.getParameter("description"));
                        
                studies.add(study);
                break;
                }
                }**/
                request.setAttribute("result", result);
                request.setAttribute("study", study);
                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            } else if (userPath.equals("add")) {

                Study study = new Study();
                study.setCode((int) Math.random());
                study.setName(request.getParameter("studyName"));
                study.setQuestion(request.getParameter("questionText"));
                study.setRequestedParticipants(Integer.parseInt(request.getParameter("participants")));

                study.setDescription(request.getParameter("description"));
                Part part = request.getPart("imageFile");
                String fileName = part.getSubmittedFileName();
                String file1 = "images/" + fileName;
                study.setImageURL(file1);
                /**
                studies = (List<Study>) session.getAttribute("myStudies");
                studies.add(study);**/
                List result1 = StudyDB.addStudy(study, email);

                List result = StudyDB.retrieveStudies(email);
                Study study1 = new Study();
                request.setAttribute("result", result);

                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            } else if (userPath.equals("start")) {
                studyCode = request.getParameter("studyCode");

                List result = StudyDB.startStudy(studyCode, email);
                Study study = new Study();
                session.setAttribute("result", result);
                study.setStatus("started");
                session.setAttribute("choice", "started");
                /**
                if(session.getAttribute("myStudies")!=null){
                studies = (List<Study>) session.getAttribute("myStudies");
                }
                for(Study study: studies){
                if(study.getCode() == Integer.parseInt(studyCode)){
                studies.remove(study);
                study.setStatus("start");
                studies.add(study);
                System.out.println("studyCode:  " + studyCode);
                System.out.println("New Status:  " + study.getStatus());
                break;
                }
                }**/
                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            } else if (userPath.equals("stop")) {
                studyCode = request.getParameter("studyCode");

                System.out.println("study code from DB" + studyCode);
                List result = StudyDB.stopStudy(studyCode, email);
                Study study = new Study();
                study.setStatus("stopped");
                session.setAttribute("result", result);

                System.out.println("studyCode:  " + studyCode);
                /**
                if(session.getAttribute("myStudies")!=null){
                studies = (List<Study>) session.getAttribute("myStudies");
                }
                for(Study study1: studies){
                if(study1.getCode() == Integer.parseInt(studyCode)){
                studies.remove(study);
                study1.setStatus(null);
                studies.add(study);
                System.out.println("studyCode:  " + studyCode);
                System.out.println("New Status:  " + study.getStatus());
                break;
                }
                }**/
                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            }
            dispatcher = getServletContext().getRequestDispatcher("/" + reDirect + ".jsp");
            dispatcher.forward(request, response);
        } else {
            dispatcher = getServletContext().getRequestDispatcher("/" + "login" + ".jsp");
            dispatcher.forward(request, response);
        }
    } catch (Exception e) {
        e.printStackTrace();
        dispatcher = getServletContext().getRequestDispatcher("/main.jsp");
        dispatcher.forward(request, response);
    }

}

From source file:net.maritimecloud.identityregistry.controllers.OrganizationController.java

/**
 * Returns new certificate for the user identified by the given ID
 *
 * @return a reply.../*from   w ww .ja v  a  2  s .c  om*/
 * @throws McBasicRestException
 */
@RequestMapping(value = "/api/org/{orgMrn}/certificate/issue-new", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@PreAuthorize("hasRole('ORG_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<PemCertificate> newOrgCert(HttpServletRequest request, @PathVariable String orgMrn)
        throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        PemCertificate ret = this.issueCertificate(org, org, "organization", request);
        return new ResponseEntity<>(ret, HttpStatus.OK);
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}