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:com.openkm.servlet.admin.DatabaseQueryServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/* w w w. j  a  v  a  2s. c o  m*/
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            boolean showSql = false;
            String vtable = "";
            String type = "";
            String qs = "";
            byte[] data = null;

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("showSql")) {
                        showSql = true;
                    } else if (item.getFieldName().equals("vtables")) {
                        vtable = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, showSql, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    sc.setAttribute("vtable", vtable);
                    executeMetadata(session, qs, false, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("showSql", showSql);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DbQueryGlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        } else {
            // Edit table cell value
            String action = request.getParameter("action");
            String vtable = request.getParameter("vtable");
            String column = request.getParameter("column");
            String value = request.getParameter("value");
            String id = request.getParameter("id");

            if (action.equals("edit")) {
                int idx = column.indexOf('(');

                if (idx > 0) {
                    column = column.substring(idx + 1, idx + 6);
                }

                String hql = "update DatabaseMetadataValue dmv set dmv." + column + "='" + value
                        + "' where dmv.table='" + vtable + "' and dmv.id=" + id;
                log.info("HQL: {}", hql);
                session = HibernateUtil.getSessionFactory().openSession();
                int rows = session.createQuery(hql).executeUpdate();
                log.info("Rows affected: {}", rows);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:org.opennms.web.controller.event.EventController.java

private ModelAndView createListModelAndView(HttpServletRequest request, List<Filter> filterList,
        AcknowledgeType ackType) {//from w w  w.  ja va 2s .c  o  m
    final EventQueryParms parms = createEventQueryParms(request, filterList, ackType);
    final EventCriteria queryCriteria = new EventCriteria(parms);
    final Event[] events = m_webEventRepository.getMatchingEvents(queryCriteria);

    final ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("events", events);
    modelAndView.addObject("parms", new NormalizedQueryParameters(parms));
    modelAndView.addObject("callback", getFilterCallback());
    modelAndView.addObject("favorites",
            favoriteService.getFavorites(request.getRemoteUser(), OnmsFilterFavorite.Page.EVENT).toArray());

    if (m_showEventCount) {
        EventCriteria countCriteria = new EventCriteria(filterList, ackType);
        modelAndView.addObject("eventCount", m_webEventRepository.countMatchingEvents(countCriteria));
    } else {
        modelAndView.addObject("eventCount", Integer.valueOf(-1));
    }
    return modelAndView;
}

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

/**
 * Execute report//from   w  w  w.j  a va2s.c om
 */
private void execute(HttpServletRequest request, HttpServletResponse response)
        throws IOException, DatabaseException, EvalError {
    log.debug("execute({}, {})", new Object[] { request, response });
    int ctId = WebUtils.getInt(request, "ct_id");
    CronTab ct = CronTabDAO.findByPk(ctId);

    if (CronTab.BSH.equals(ct.getFileMime())) {
        Cron.RunnerBsh runner = new Cron.RunnerBsh(ct.getId(), ct.getName(), ct.getMail(),
                new String(SecureStore.b64Decode(ct.getFileContent())));
        runner.run();
    } else if (CronTab.JAR.equals(ct.getFileMime())) {
        Cron.RunnerJar runner = new Cron.RunnerJar(ct.getId(), ct.getName(), ct.getMail(),
                SecureStore.b64Decode(ct.getFileContent()));
        runner.run();
    }

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_CRONTAB_EXECUTE", Integer.toString(ctId), null,
            ct.toString());
    log.debug("execute: void");
}

From source file:gov.nih.nci.ncicb.cadsr.common.security.LogoutServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //unlock all forms locked by this session
    HttpSession session = request.getSession();
    String logTjsp = getServletConfig().getInitParameter("LogthroughJSP");
    if (logTjsp != null && !logTjsp.equals(""))
        LOGTHROUGH_JSP = logTjsp;//from  w w w . j  av a 2s  .  c o m

    String lojsp = getServletConfig().getInitParameter("LogoutJSP");
    if (lojsp != null && !lojsp.equals(""))
        LOGOUT_JSP = lojsp;
    String authjsp = getServletConfig().getInitParameter("ErrorJSP");
    if (authjsp != null && !authjsp.equals(""))
        AUTHORIZATION_ERROR_JSP = authjsp;

    if (!request.getContextPath().contains("CDEBrowser")) {
        getApplicationServiceLocator(session.getServletContext()).findLockingService()
                .unlockFormByUser(request.getRemoteUser());
    }
    synchronized (SessionUtils.sessionObjectCache) {
        log.error("LogoutServlet.doPost at start:" + TimeUtils.getEasternTime());
        String error = request.getParameter("authorizationError");
        String forwardUrl;
        //// GF29128 Begin. D.An, 20130729. 
        String un = (String) session.getAttribute("myUsername");
        ;
        ////   if (un == null)
        ////      un = "viewer";
        System.out.println("logoutServlet: " + session.getAttribute("myUsername"));
        if (error == null) {
            if (un.equals("viewer"))
                forwardUrl = LOGTHROUGH_JSP;
            //// GF29128  end.      
            else
                forwardUrl = LOGOUT_JSP;
        } else {
            forwardUrl = AUTHORIZATION_ERROR_JSP;
        }

        if ((session != null) && isLoggedIn(request)) {
            for (int i = 0; i < logoutKeys.length; i++) {
                session.removeAttribute(logoutKeys[i]);
            }

            //remove formbuilder specific objects
            //TODO has to be moved to an action
            Collection keys = (Collection) session.getAttribute(FormBuilderConstants.CLEAR_SESSION_KEYS);
            if (keys != null) {
                Iterator it = keys.iterator();
                while (it.hasNext()) {
                    session.removeAttribute((String) it.next());
                }
            }
            HashMap allMap = new HashMap();
            allMap.put(CaDSRConstants.GLOBAL_SESSION_KEYS, copyAllsessionKeys(session));
            allMap.put(CaDSRConstants.GLOBAL_SESSION_MAP, copyAllsessionObjects(session));
            SessionUtils.addToSessionCache(session.getId(), allMap);
            forwardUrl = forwardUrl + "?" + CaDSRConstants.PREVIOUS_SESSION_ID + "=" + session.getId();
            session.invalidate();
        }

        RequestDispatcher dispacher = request.getRequestDispatcher(forwardUrl);
        dispacher.forward(request, response);
        log.error("LogoutServlet.doPost at end:" + TimeUtils.getEasternTime());
    }
}

From source file:org.kuali.mobility.academics.controllers.AcademicsAuthControllerImpl.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/mySections", method = RequestMethod.GET)
public String getMySections(HttpServletRequest request, Model uiModel,
        @RequestParam(required = false) final String termId,
        @RequestParam(required = false) final String careerId) {
    HttpSession session = request.getSession();
    if (termId.equalsIgnoreCase((String) session.getAttribute(AcademicsConstants.TERM_ID))
            && careerId.equalsIgnoreCase((String) session.getAttribute(AcademicsConstants.CAREER_ID))) {
        Term term = (Term) session.getAttribute("currentTerm");
        uiModel.addAttribute("title", term.getShortDescription());
    } else {// w  w  w  . java 2 s  .c o m
        List<? extends Section> sections = getService().getClassSchedule(request, termId, careerId);
        if (sections.isEmpty()) {
            LOG.debug("No sections found for user [" + request.getRemoteUser() + "]");
        } else {
            Term term = (Term) CollectionUtils.find((List<Term>) session.getAttribute(AcademicsConstants.TERM),
                    new TermPredicate(termId));
            if (term != null) {
                session.setAttribute("currentTerm", term);
                session.setAttribute("currentCareer", term.getCareers().get(0));
                uiModel.addAttribute("title", term.getShortDescription());
            } else {
                uiModel.addAttribute("title", "My Schedule");
            }
            uiModel.addAttribute("detailsections", sections);
            session.setAttribute(AcademicsConstants.SECTIONS, sections);
            session.setAttribute(AcademicsConstants.TERM_ID, termId);
            session.setAttribute(AcademicsConstants.CAREER_ID, careerId);
        }
    }
    uiModel.addAttribute("catalogDescription", null);
    uiModel.addAttribute("toolContext", "myAcademics");
    //uiModel.addAttribute(AcademicsConstants.BACKBUTTON_URL, request.getContextPath() + "/myAcademics/");
    return "academics/sections";
}

From source file:org.archive.wayback.core.WaybackRequest.java

/**
 * extract REFERER, remote IP and authorization information from the
 * HttpServletRequest/*  w  ww .  ja  va 2  s  . c o  m*/
 * 
 * @param httpRequest
 */
private void extractHttpRequestInfo(HttpServletRequest httpRequest) {
    // attempt to get the HTTP referer if present..
    put(WaybackConstants.REQUEST_REFERER_URL, emptyIfNull(httpRequest.getHeader("REFERER")));
    put(WaybackConstants.REQUEST_REMOTE_ADDRESS, emptyIfNull(httpRequest.getRemoteAddr()));
    put(WaybackConstants.REQUEST_WAYBACK_HOSTNAME, emptyIfNull(httpRequest.getLocalName()));
    put(WaybackConstants.REQUEST_WAYBACK_PORT, String.valueOf(httpRequest.getLocalPort()));
    put(WaybackConstants.REQUEST_WAYBACK_CONTEXT, emptyIfNull(httpRequest.getContextPath()));
    put(WaybackConstants.REQUEST_AUTH_TYPE, emptyIfNull(httpRequest.getAuthType()));
    put(WaybackConstants.REQUEST_REMOTE_USER, emptyIfNull(httpRequest.getRemoteUser()));
    put(WaybackConstants.REQUEST_LOCALE_LANG, getUserLocale(httpRequest));

    Cookie[] cookies = httpRequest.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            put(cookie.getName(), cookie.getValue());
        }
    }
}

From source file:com.pkrete.locationservice.admin.controller.mvc.EditUserController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute("userInfo") UserInfo userInfo, BindingResult result) throws Exception {
    validator.validate(userInfo, result);

    if (result.hasErrors()) {
        ModelMap model = new ModelMap();
        this.setReferenceData(request, model);
        return new ModelAndView("edit_user", model);
    }// w  w w.java 2  s. co  m
    String userId = request.getParameter("select_user");

    userInfo.getUser().setUpdater(getUser(request).getUsername());
    // Updates only User
    if (!usersService.update(userInfo.getUser())) {
        throw new Exception("Updating user failed.");
    }
    // Updates only UserInfor
    if (!usersService.update(userInfo)) {
        throw new Exception("Updating user info failed.");
    }

    HttpSession session = request.getSession();
    session.removeAttribute("user");
    session.setAttribute("user", usersService.getUser(request.getRemoteUser()));

    return new ModelAndView("redirect:userowner.htm?select_user=" + userId);
}

From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java

/**
 * Prepare for choose or select role//from   w ww.  j a  v  a 2s.  c o  m
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
protected void setRolSession(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        ContactLogic contactLogic = new ContactLogic();

        Contact contact = contactLogic.findByUser(request.getRemoteUser());

        if (contact != null) {

            if (request.getSession().getAttribute("plugins") == null) {

                PluginLogic pluginLogic = new PluginLogic();
                request.getSession().setAttribute("plugins", pluginLogic.getPlugins(contact));
            }

            EmployeeLogic employeeLogic = new EmployeeLogic();
            List<Employee> employees = employeeLogic.consEmployeesByUser(contact);

            if (employees.isEmpty()) { // Any user match
                request.setAttribute("error",
                        getResourceBundle(request).getString("msg.error.without_permission"));
                request.setAttribute("notLogin", true);

                HttpSession session = request.getSession();
                if (session != null) {
                    session.invalidate();
                }

                setForward(true);
                forward("/login.jsp", request, response);
            } else if (employees.size() == 1) { // One user match
                Employee user = employeeLogic.consEmployee(employees.get(0).getIdEmployee());
                request.getSession().setAttribute("user", user);
                request.getSession().setAttribute("rolPrincipal", user.getResourceprofiles().getIdProfile());
            } else if (employees.size() > 1) { // More than one user found
                PerformingOrgLogic performingOrgLogic = new PerformingOrgLogic();

                List<Performingorg> orgs = performingOrgLogic.consByContact(contact);

                Employee user = new Employee();
                user.setContact(contact);
                request.getSession().setAttribute("user", user);

                request.setAttribute("employees", employees);
                request.setAttribute("organizactions", orgs);

                // Configurations
                ConfigurationLogic configurationLogic = new ConfigurationLogic();
                request.setAttribute("configurations",
                        configurationLogic.findByTypes(user, Configurations.TYPE_CHOOSE_ROLE));

                setForward(true);
                forward("/select_rol.jsp", request, response);
            }
        } else { // Contact not exists
            request.setAttribute("error", getResourceBundle(request).getString("msg.error_login.message"));
            setForward(true);
            forward("/index.jsp", request, response);
        }
    } catch (Exception e) {
        ExceptionUtil.evalueException(request, getResourceBundle(request), LOGGER, e);
        setForward(true);
        forward("/index.jsp", request, response);
    }
}

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

private boolean handlePut(HttpServletRequest request, HttpServletResponse response, String pathString)
        throws GitAPIException, CoreException, IOException, JSONException, ServletException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    if (path.segment(0).equals("file") && path.segmentCount() > 1) { //$NON-NLS-1$

        // make sure a clone is addressed
        ProjectInfo webProject = GitUtils.projectFromPath(path);
        if (isAccessAllowed(request.getRemoteUser(), webProject)) {
            Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.CURRENT);
            if (gitDirs.isEmpty()) {
                String msg = NLS.bind("Request path is not a git repository: {0}", path);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }/*from  ww  w.java 2  s .  c  o m*/
            File gitDir = gitDirs.values().iterator().next();

            // make sure required fields are set
            JSONObject toCheckout = OrionServlet.readJSONRequest(request);
            JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH);
            String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME, null);
            String tag = toCheckout.optString(GitConstants.KEY_TAG_NAME, null);
            boolean removeUntracked = toCheckout.optBoolean(GitConstants.KEY_REMOVE_UNTRACKED, false);
            if ((paths == null || paths.length() == 0) && branch == null && tag == null) {
                String msg = NLS.bind("Either '{0}' or '{1}' or '{2}' should be provided, got: {3}",
                        new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_BRANCH_NAME,
                                GitConstants.KEY_TAG_NAME, toCheckout });
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }

            Git git = new Git(FileRepositoryBuilder.create(gitDir));
            if (paths != null) {
                Set<String> toRemove = new HashSet<String>();
                CheckoutCommand checkout = git.checkout();
                for (int i = 0; i < paths.length(); i++) {
                    String p = paths.getString(i);
                    if (removeUntracked && !isInIndex(git.getRepository(), p))
                        toRemove.add(p);
                    checkout.addPath(p);
                }
                checkout.call();
                for (String p : toRemove) {
                    File f = new File(git.getRepository().getWorkTree(), p);
                    f.delete();
                }
                return true;
            } else if (tag != null && branch != null) {
                CheckoutCommand co = git.checkout();
                try {
                    co.setName(branch).setStartPoint(tag).setCreateBranch(true).call();
                    return true;
                } catch (RefNotFoundException e) {
                    String msg = NLS.bind("Tag not found: {0}", tag);
                    return statusHandler.handleRequest(request, response,
                            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
                } catch (GitAPIException e) {
                    if (org.eclipse.jgit.api.CheckoutResult.Status.CONFLICTS
                            .equals(co.getResult().getStatus())) {
                        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                                HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
                    }
                    // TODO: handle other exceptions
                }
            } else if (branch != null) {

                if (!isLocalBranch(git, branch)) {
                    String msg = NLS.bind("{0} is not a branch.", branch);
                    return statusHandler.handleRequest(request, response,
                            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
                }

                CheckoutCommand co = git.checkout();
                try {
                    co.setName(Constants.R_HEADS + branch).call();
                    return true;
                } catch (CheckoutConflictException e) {
                    return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                            HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
                } catch (RefNotFoundException e) {
                    String msg = NLS.bind("Branch name not found: {0}", branch);
                    return statusHandler.handleRequest(request, response,
                            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
                } // TODO: handle other exceptions
            }
        } else {
            String msg = NLS.bind("Nothing found for the given ID: {0}", path);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
        }
    }
    String msg = NLS.bind("Invalid checkout request {0}", pathString);
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}

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

/**
 * Execute report//from  ww w .j  a va  2 s .  c  o  m
 */
private void execute(HttpServletRequest request, HttpServletResponse response)
        throws IOException, DatabaseException, EvalError {
    log.debug("execute({}, {})", new Object[] { request, response });
    int ctId = WebUtils.getInt(request, "ct_id");
    CronTab ct = CronTabDAO.findByPk(ctId);

    if (MimeTypeConfig.MIME_BSH.equals(ct.getFileMime())) {
        Cron.RunnerBsh runner = new Cron.RunnerBsh(ct.getId(), ct.getName(), ct.getMail(),
                new String(SecureStore.b64Decode(ct.getFileContent())));
        runner.run();
    } else if (MimeTypeConfig.MIME_JAR.equals(ct.getFileMime())) {
        Cron.RunnerJar runner = new Cron.RunnerJar(ct.getId(), ct.getName(), ct.getMail(),
                SecureStore.b64Decode(ct.getFileContent()));
        runner.run();
    }

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_CRONTAB_EXECUTE", Integer.toString(ctId), null,
            ct.toString());
    log.debug("execute: void");
}