Example usage for javax.servlet.http HttpServletRequest getRemoteUser

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

Introduction

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

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:org.eclipse.orion.server.git.servlets.AbstractGitHandler.java

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path)
        throws ServletException {
    Repository db = null;//w w  w  . j  ava 2  s . c  o m
    try {
        IPath p = new Path(path);
        String gitSegment = null;
        if (p.segment(1).equals("file")) { //$NON-NLS-1$
            gitSegment = GitUtils.decode(p.segment(0));
            p = p.removeFirstSegments(1);
        }
        IPath filePath = p;
        if (!AuthorizationService.checkRights(request.getRemoteUser(), "/" + filePath.toString(),
                request.getMethod())) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return true;
        }
        IPath gitSearchPath = filePath.hasTrailingSeparator() ? filePath : filePath.removeLastSegments(1);
        Set<Entry<IPath, File>> gitDirsFound = GitUtils.getGitDirs(gitSearchPath, Traverse.GO_UP).entrySet();
        Entry<IPath, File> firstGitDir = gitDirsFound.iterator().next();
        File gitDir = firstGitDir.getValue();
        if (gitDir == null) {
            String msg = NLS.bind("Could not find repository for {0}", filePath);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        String relativePath = GitUtils.getRelativePath(filePath, firstGitDir.getKey());
        db = FileRepositoryBuilder.create(gitDir);
        RequestInfo requestInfo = new RequestInfo(request, response, db, gitSegment, relativePath, filePath);
        switch (getMethod(request)) {
        case GET:
            return handleGet(requestInfo);
        case POST:
            return handlePost(requestInfo);
        case PUT:
            return handlePut(requestInfo);
        case DELETE:
            return handleDelete(requestInfo);
        case OPTIONS:
        case HEAD:
        default:
            return false;
        }
    } catch (IOException e) {
        String msg = NLS.bind("Failed to process a git request for {0}", path);
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    } catch (CoreException e) {
        String msg = NLS.bind("Failed to process a git request for {0}", path);
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    } finally {
        if (db != null)
            db.close();
    }
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@ModelAttribute
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
protected User showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // If not an administrator, make sure user is not trying to add or edit another user
    if (!request.isUserInRole(Constants.ADMIN_ROLE) && !isFormSubmission(request)) {
        if (isAdd(request) || request.getParameter("id") != null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '"
                    + request.getParameter("id") + "'");

            throw new AccessDeniedException("You do not have permission to modify other users.");
        }//ww w. j  a v  a2  s . c  o m
    }

    if (!isFormSubmission(request)) {
        String userId = request.getParameter("id");

        // if user logged in with remember me, display a warning that they can't change passwords
        log.debug("checking for remember me login...");

        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() != null) {
            Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                request.getSession().setAttribute("cookieLogin", "true");

                // add warning message
                saveMessage(request, getText("userProfile.cookieLogin", request.getLocale()));
            }
        }

        User user;
        if (userId == null && !isAdd(request)) {
            user = getUserManager().getUserByUsername(request.getRemoteUser());
        } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) {
            user = getUserManager().getUser(userId);
        } else {
            user = new User();
            user.addRole(new Role(Constants.USER_ROLE));
        }

        user.setConfirmPassword(user.getPassword());

        return user;
    } else {
        // populate user object from database, so all fields don't need to be hidden fields in form
        return getUserManager().getUser(request.getParameter("id"));
    }
}

From source file:com.qualogy.qafe.web.upload.DatagridUploadServlet.java

@SuppressWarnings("unchecked")
private void writeUploadInfo(HttpServletRequest request) {
    writeLog("Document Upload!");

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        Object name = headerNames.nextElement();
        if (name != null) {
            writeLog("Header - " + name + " : " + request.getHeader((String) name));
        }//w  w w  .  j a v  a 2 s .  com
    }

    writeLog("ServletRemoteAddr: " + request.getRemoteAddr());
    writeLog("Remote Host: " + request.getRemoteHost());
    writeLog("Remote User: " + request.getRemoteUser());
    writeLog("Protocol: " + request.getProtocol());
    writeLog("Server Name: " + request.getServerName());
    writeLog("Server Port: " + request.getServerPort());
    writeLog("Request URL: " + request.getRequestURL());

}

From source file:com.ikon.servlet.admin.MimeTypeServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    Session dbSession = null;//from w w w  .j a  v a  2 s. c o m
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            MimeType mt = new MimeType();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("mt_id")) {
                        mt.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("mt_name")) {
                        mt.setName(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_extensions")) {
                        String[] extensions = item.getString("UTF-8").split(" ");
                        for (int i = 0; i < extensions.length; i++) {
                            mt.getExtensions().add(extensions[i].toLowerCase());
                        }
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                long id = MimeTypeDAO.create(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                MimeTypeDAO.update(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null,
                        mt.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                MimeTypeDAO.delete(mt.getId());
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importMimeTypes(userId, request, response, data, dbSession);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:OpenProdocServ.Oper.java

/**
 * //w w  w .  java  2 s . c  o  m
 * @param Req
 * @param out
 * @throws Exception
 */
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception {
    String Order = Req.getParameter(DriverRemote.ORDER);
    String Param = Req.getParameter(DriverRemote.PARAM);
    if (PDLog.isDebug()) {
        PDLog.Debug("From:" + Req.getRemoteHost() + "/" + Req.getRemoteHost() + ":" + Req.getRemoteUser());
        PDLog.Debug("Order:" + Order);
        PDLog.Debug("Param:" + Param);
    }
    DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document XMLObjects = DB.parse(new ByteArrayInputStream(Param.getBytes("UTF-8")));
    if (Order.equals(DriverGeneric.S_LOGIN)) {
        NodeList OPDObjectList = XMLObjects.getElementsByTagName("U");
        Node OPDObject = OPDObjectList.item(0);
        String User = OPDObject.getTextContent();
        OPDObjectList = XMLObjects.getElementsByTagName("C");
        OPDObject = OPDObjectList.item(0);
        String Pass = OPDObject.getTextContent();
        DriverGeneric D = ProdocFW.getSession("PD", User, Pass);
        Req.getSession().setAttribute("PRODOC_SESS", D);
        Answer(Req, out, true, null, null);
        return;
    } else if (Order.equals(DriverGeneric.S_UNLOCK)) {
        getSessOPD(Req).UnLock();
        Req.getSession().setAttribute("PRODOC_SESS", null);
        Answer(Req, out, true, null, null);
        return;
    }
    DriverGeneric D = getSessOPD(Req);
    String Results = D.RemoteOrder(Order, XMLObjects);
    Answer(Req, out, Results);
    XMLObjects = null;
    DB.reset();
}

From source file:com.openkm.servlet.admin.MimeTypeServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    Session dbSession = null;/*from  w  w  w .j av  a 2  s  .c om*/
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            MimeType mt = new MimeType();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("mt_id")) {
                        mt.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("mt_name")) {
                        mt.setName(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_description")) {
                        mt.setDescription(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_search")) {
                        mt.setSearch(true);
                    } else if (item.getFieldName().equals("mt_extensions")) {
                        String[] extensions = item.getString("UTF-8").split(" ");

                        for (int i = 0; i < extensions.length; i++) {
                            mt.getExtensions().add(extensions[i].toLowerCase());
                        }
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                long id = MimeTypeDAO.create(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                MimeTypeDAO.update(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null,
                        mt.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                MimeTypeDAO.delete(mt.getId());
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importMimeTypes(userId, request, response, data, dbSession);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:com.sun.socialsite.web.filters.CustomizedPageFragmentCachingFilter.java

@Override
protected String calculateKey(final HttpServletRequest req) {
    String uri = null;//from   w w  w.  j a v  a2 s.c om
    String query = null;

    if (req.getAttribute("javax.servlet.include.request_uri") != null) {
        uri = (String) (req.getAttribute("javax.servlet.include.request_uri"));
        query = (String) (req.getAttribute("javax.servlet.include.query_string"));
    } else {
        uri = req.getRequestURI();
        query = req.getQueryString();
    }

    // TODO: something better than this anonymous/loggedin workaround
    StringBuilder sb = new StringBuilder();
    sb.append((req.getRemoteUser() != null) ? "LOGGED_IN" : "ANONYMOUS");
    sb.append("|");
    sb.append(req.getMethod());
    sb.append("|");
    sb.append(uri);
    if (query != null) {
        sb.append("?").append(query);
    }

    String key = sb.toString();
    log.trace("key=" + key);

    return key;
}

From source file:de.fhg.fokus.openride.services.rating.RatingService.java

@POST
@Produces("text/json")
public Response postRating(@Context HttpServletRequest con, @PathParam("username") String username,
        String json) {//from www. jav a2s.co m
    System.out.println("postRating start");

    if (json != null) {
        System.out.println("json: " + json);
        // to use this method client must send json content!

        if (!username.equals(con.getRemoteUser())) {
            /*
             * Ratings my be posted by other users, too
             *
            return Response.status(Response.Status.FORBIDDEN).build();
             */
        }

        CustomerEntity c = customerControllerBean.getCustomerByNickname(username);

        // build a List of Objects that shall be available in the JSON context.
        ArrayList list = new ArrayList();
        list.add(new GivenRatingRequest());

        XStream x = Utils.getJasonXStreamer(list);

        GivenRatingRequest r = (GivenRatingRequest) x.fromXML(json);

        // Check whether rating value is valid
        if (r.getGivenRating() >= -1 && r.getGivenRating() <= 1) {

            // Do not accept negative ratings without a comment
            if (r.getGivenRating() == -1 && r.getGivenRatingComment().equals("")) {
                // return "bad request" status msg
                return Response.status(Response.Status.BAD_REQUEST).build();
            }
            // Save this rating

            boolean rated = false;
            // Was the customer who submits this rating driver or rider?
            if (riderUndertakesRideControllerBean.getRideByRiderRouteId(r.getRiderRouteId()).getCustId()
                    .equals(c)) {
                // Customer was the rider -> rates driver -> GivenRating
                riderUndertakesRideControllerBean.setGivenRating(r.getRiderRouteId(), r.getGivenRating(),
                        r.getGivenRatingComment());
                rated = true;
            }
            if (riderUndertakesRideControllerBean.getRideByRiderRouteId(r.getRiderRouteId()).getRideId()
                    .getCustId().equals(c)) {
                // Customer was the driver -> rates rider  -> ReceivedRating
                riderUndertakesRideControllerBean.setReceivedRating(r.getRiderRouteId(), r.getGivenRating(),
                        r.getGivenRatingComment());
                rated = true;
            }
            if (!rated) {
                // this Customer was neither rider or driver!... operation not allowed.
                return Response.status(Response.Status.BAD_REQUEST).build();
            }

        } else {
            // return "bad request" status msg
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

        return Response.ok().build();

    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}

From source file:com.openkm.servlet.admin.PropertyGroupsServlet.java

/**
 * Edit property groups/*from   w  w  w .j a v  a2  s  .c  o  m*/
 */
private void edit(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("edit({}, {})", new Object[] { request, response });

    if (WebUtils.getBoolean(request, "persist")) {
        String definition = request.getParameter("definition");
        FileUtils.writeStringToFile(new File(Config.PROPERTY_GROUPS_XML), definition, "UTF-8");

        // Activity log
        UserActivity.log(request.getRemoteUser(), "ADMIN_PROPERTY_GROUP_EDIT", null, null, null);
    } else {
        String xml = FileUtils.readFileToString(new File(Config.PROPERTY_GROUPS_XML), "UTF-8");
        ServletContext sc = getServletContext();
        sc.setAttribute("persist", true);
        sc.setAttribute("action", "edit");
        sc.setAttribute("definition", xml.replace("&", "&amp;"));
        sc.getRequestDispatcher("/admin/property_groups_edit.jsp").forward(request, response);
    }

    log.debug("edit: void");
}

From source file:de.fhg.fokus.openride.services.profile.ProfileService.java

@GET
@Path("preferences/")
@Produces("text/json")
public Response getPreferences(@Context HttpServletRequest con, @PathParam("username") String username) {

    System.out.println("getPreferences start");

    // check if remote user == {username} in path param
    if (!username.equals(con.getRemoteUser())) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }//from w  ww .j a v  a2 s . c  o m

    CustomerEntity c = customerControllerBean.getCustomerByNickname(username);

    // build a List of Objects that shall be available in the JSON context.
    ArrayList list = new ArrayList();
    list.add(new PreferencesResponse());

    XStream x = Utils.getJasonXStreamer(list);

    Character gender = c.getCustDriverprefGender();
    if (gender == null) {
        gender = "-".charAt(0);
    }
    Character issmoker = c.getCustDriverprefIssmoker();
    if (issmoker == null) {
        issmoker = "-".charAt(0);
    }

    PreferencesResponse profile = new PreferencesResponse(issmoker, gender);

    return Response.ok(x.toXML(profile)).build();

}