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.appcelerator.transport.AjaxServiceTransportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ///*from   www  . jav  a  2s.c o m*/
    // make sure we check the integrity of the request before we continue
    //
    if (!validate(req, resp)) {
        LOG.warn("security validation failed for request=" + req + " from " + req.getRemoteAddr());
        return;
    }

    String type = req.getContentType();
    int idx = type.indexOf(';');

    if (idx > 0) {
        type = type.substring(0, idx);
    }

    try {
        // decode the incoming request
        ArrayList<Message> requests = new ArrayList<Message>(1);
        ArrayList<Message> responses = new ArrayList<Message>(1);

        ServiceMarshaller.getMarshaller(type).decode(req.getInputStream(), requests);

        if (requests.isEmpty()) {
            // no incoming messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        HttpSession session = req.getSession();
        InetAddress address = InetAddress.getByName(req.getRemoteAddr());
        //String instanceid = req.getParameter("instanceid");

        for (Message request : requests) {
            request.setUser(req.getUserPrincipal());
            request.setSession(session);
            request.setAddress(address);
            request.setServletRequest(req);

            //FIXME => refactor this out
            if (request.getType().equals(MessageType.APPCELERATOR_STATUS_REPORT)) {
                IMessageDataObject data = (IMessageDataObject) request.getData();
                data.put("remoteaddr", req.getRemoteAddr());
                data.put("remotehost", req.getRemoteHost());
                data.put("remoteuser", req.getRemoteUser());
            }

            ServiceRegistry.dispatch(request, responses);
        }

        if (responses.isEmpty()) {
            // no response messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        // setup the response
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setHeader("Connection", "Keep-Alive");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-control", "no-cache, no-store, private, must-revalidate");
        resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");

        // encode the responses
        ServletOutputStream output = resp.getOutputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(1000);
        String responseType = ServiceMarshaller.getMarshaller(type).encode(responses, req.getSession().getId(),
                bout);
        byte buf[] = bout.toByteArray();
        ByteArrayInputStream bin = new ByteArrayInputStream(buf);

        resp.setContentType(responseType);

        // do gzip encoding if browser supports it and if length > 1000 bytes
        String ae = req.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1 && buf.length > 1000) {
            resp.setHeader("Content-Encoding", "gzip");
            //a Vary: Accept-Encoding HTTP response header to alert proxies that a cached response should be sent only to 
            //clients that send the appropriate Accept-Encoding request header. This prevents compressed content from being sent 
            //to a client that will not understand it.
            resp.addHeader("Vary", "Accept-Encoding");
            GZIPOutputStream gzip = new GZIPOutputStream(output, buf.length);
            Util.copy(bin, gzip);
            gzip.flush();
            gzip.finish();
        } else {
            resp.setContentLength(buf.length);
            Util.copy(bin, output);
        }
        output.flush();
    } catch (Throwable e) {
        LOG.error("Error handling incoming POST request", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.auscope.portal.server.web.controllers.JobListController.java

/**
 * Delete the job given by its reference.
 *
 * @param request The servlet request including a jobId parameter
 * @param response The servlet response/* w  ww.j  a  va  2s .  co  m*/
 *
 * @return A JSON object with a success attribute and an error attribute
 *         in case the job was not found or can not be deleted.
 */
@RequestMapping("/deleteJob.do")
public ModelAndView deleteJob(HttpServletRequest request, HttpServletResponse response) {

    String jobIdStr = request.getParameter("jobId");
    GeodesyJob job = null;
    ModelAndView mav = new ModelAndView("jsonView");
    boolean success = false;
    Object credential = request.getSession().getAttribute("userCred");

    if (credential == null) {
        final String errorString = "Invalid grid credentials!";
        logger.error(errorString);
        mav.addObject("error", errorString);
        mav.addObject("success", false);
        return mav;
    }

    if (jobIdStr != null) {
        try {
            int jobId = Integer.parseInt(jobIdStr);
            job = jobManager.getJobById(jobId);
        } catch (NumberFormatException e) {
            logger.error("Error parsing job ID!");
        }
    } else {
        logger.warn("No job ID specified!");
    }

    if (job == null) {
        final String errorString = "The requested job was not found.";
        logger.error(errorString);
        mav.addObject("error", errorString);

    } else {
        // check if current user is the owner of the job
        GeodesySeries s = jobManager.getSeriesById(job.getSeriesId());
        if (request.getRemoteUser().equals(s.getUser())) {
            logger.info("Deleting job with ID " + jobIdStr);
            jobManager.deleteJob(job);
            success = true;
        } else {
            logger.warn(request.getRemoteUser() + "'s attempt to kill " + s.getUser() + "'s job denied!");
            mav.addObject("error", "You are not authorised to delete this job.");
        }
    }
    mav.addObject("success", success);

    return mav;
}

From source file:org.auscope.portal.server.web.controllers.JobListController.java

/**
 * Kills the job given by its reference.
 *
 * @param request The servlet request including a jobId parameter
 * @param response The servlet response//www  .j av a 2 s  .com
 *
 * @return A JSON object with a success attribute and an error attribute
 *         in case the job was not found in the job manager.
 */
@RequestMapping("/killJob.do")
public ModelAndView killJob(HttpServletRequest request, HttpServletResponse response) {

    String jobIdStr = request.getParameter("jobId");
    GeodesyJob job = null;
    ModelAndView mav = new ModelAndView("jsonView");
    boolean success = false;
    Object credential = request.getSession().getAttribute("userCred");

    if (credential == null) {
        final String errorString = "Invalid grid credentials!";
        logger.error(errorString);
        mav.addObject("error", errorString);
        mav.addObject("success", false);
        return mav;
    }

    if (jobIdStr != null) {
        try {
            int jobId = Integer.parseInt(jobIdStr);
            job = jobManager.getJobById(jobId);
        } catch (NumberFormatException e) {
            logger.error("Error parsing job ID!");
        }
    } else {
        logger.warn("No job ID specified!");
    }

    if (job == null) {
        final String errorString = "The requested job was not found.";
        logger.error(errorString);
        mav.addObject("error", errorString);

    } else {
        // check if current user is the owner of the job
        GeodesySeries s = jobManager.getSeriesById(job.getSeriesId());
        if (request.getRemoteUser().equals(s.getUser())) {
            logger.info("Cancelling job with ID " + jobIdStr);
            String newState = gridAccess.killJob(job.getReference(), credential);
            if (newState == null)
                newState = "Cancelled";
            logger.debug("New job state: " + newState);

            job.setStatus(newState);
            jobManager.saveJob(job);
            success = true;
        } else {
            logger.warn(request.getRemoteUser() + "'s attempt to kill " + s.getUser() + "'s job denied!");
            mav.addObject("error", "You are not authorised to cancel this job.");
        }
    }
    mav.addObject("success", success);

    return mav;
}

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

/**
 * Execute report//from  w  ww  . j ava  2  s .  c o  m
 */
private void execute(String userId, HttpServletRequest request, HttpServletResponse response)
        throws IOException, DatabaseException, JRException, EvalError, ParseException {
    log.debug("execute({}, {}, {})", new Object[] { userId, request, response });
    int rpId = WebUtils.getInt(request, "rp_id");
    int format = WebUtils.getInt(request, "format", ReportUtils.OUTPUT_PDF);
    Report rp = ReportDAO.findByPk(rpId);

    // Set file name
    String fileName = rp.getFileName().substring(0, rp.getFileName().indexOf('.'))
            + ReportUtils.FILE_EXTENSION[format];

    // Set default report parameters
    Map<String, Object> params = new HashMap<String, Object>();
    String host = com.openkm.core.Config.APPLICATION_URL;
    params.put("host", host.substring(0, host.lastIndexOf("/") + 1));

    for (FormElement fe : ReportUtils.getReportParameters(rpId)) {
        String value = WebUtils.getString(request, fe.getName());

        if (fe instanceof Input && ((Input) fe).getType().equals(Input.TYPE_DATE)) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                params.put(fe.getName(), sdf.parse(value));
            } catch (java.text.ParseException e) {
                throw new ParseException(e.getMessage(), e);
            }
        } else {
            params.put(fe.getName(), value);
        }
    }

    ByteArrayOutputStream baos = null;
    ByteArrayInputStream bais = null;

    try {
        baos = ReportUtils.execute(rp, params, format);
        bais = new ByteArrayInputStream(baos.toByteArray());
        WebUtils.sendFile(request, response, fileName, ReportUtils.FILE_MIME[format], false, bais);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
    }

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_REPORT_EXECUTE", Integer.toString(rpId), null,
            rp.toString());
    log.debug("execute: void");
}

From source file:alpha.portal.webapp.controller.AdornmentFormController.java

/**
 * shows the adornment form./*from w  ww.  j  a v a  2s.  c  o m*/
 * 
 * @param request
 *            the request
 * @param model
 *            the model
 * @return a new adornment
 * @see adornmentform.jsp
 */
@RequestMapping(method = RequestMethod.GET)
protected String showForm(final HttpServletRequest request, final Model model) {
    final String adornmentId = request.getParameter("id");
    final String cardId = request.getParameter("card");
    final String caseId = request.getParameter("case");
    this.setCancelView("redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId);
    this.setSuccessView("redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId);
    this.setupAdornmentTypes(caseId, cardId);
    final Locale locale = request.getLocale();

    final List<ContributorRole> roles = this.contributorRoleManager.getAll();
    model.addAttribute("roles", roles);

    Adornment adornment = new Adornment();
    if (StringUtils.isNotEmpty(adornmentId)) {
        try {
            Long.valueOf(adornmentId);
        } catch (final NumberFormatException e) {
            this.saveError(request, this.getText("adornment.invalidId", locale));
            model.addAttribute("adornment", adornment);
            return "redirect:/adornmentform?id=" + adornmentId + "&card=" + cardId + "&case=" + caseId;
        }
        adornment = this.adornmentManager.get(Long.valueOf(adornmentId));
        final AdornmentType type = AdornmentType.fromName(adornment.getName());
        model.addAttribute("adornmentType", type);

    }

    final AlphaCard card = this.alphaCardManager.get(new AlphaCardIdentifier(caseId, cardId));
    final Adornment contributor = card.getAlphaCardDescriptor()
            .getAdornment(AdornmentType.Contributor.getName());

    if ((contributor.getValue() == null) || contributor.getValue().isEmpty()) {

        this.saveError(request, this.getText("adornment.noAccess", locale));
        return "redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId;

    } else {

        final Long contributorID = Long.parseLong(contributor.getValue());
        final User currentUser = this.getUserManager().getUserByUsername(request.getRemoteUser());

        if (contributorID != currentUser.getId()) {

            this.saveError(request, this.getText("adornment.noAccess", locale));
            return "redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId;
        }
    }

    model.addAttribute("adornment", adornment);
    return null;
}

From source file:org.apache.hadoop.mapred.TaskLogServlet.java

/**
 * Get the logs via http.//from  w  w w  .j  a v a 2s  . c o m
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    long start = 0;
    long end = -1;
    boolean plainText = false;
    TaskLog.LogName filter = null;
    boolean isCleanup = false;

    String attemptIdStr = request.getParameter("attemptid");
    if (attemptIdStr == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Argument attemptid is required");
        return;
    }

    String logFilter = request.getParameter("filter");
    if (logFilter != null) {
        try {
            filter = TaskLog.LogName.valueOf(TaskLog.LogName.class, logFilter.toUpperCase());
        } catch (IllegalArgumentException iae) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Illegal value for filter: " + logFilter);
            return;
        }
    }

    String sLogOff = request.getParameter("start");
    if (sLogOff != null) {
        start = Long.valueOf(sLogOff).longValue();
    }

    String sLogEnd = request.getParameter("end");
    if (sLogEnd != null) {
        end = Long.valueOf(sLogEnd).longValue();
    }

    String sPlainText = request.getParameter("plaintext");
    if (sPlainText != null) {
        plainText = Boolean.valueOf(sPlainText);
    }

    String sCleanup = request.getParameter("cleanup");
    if (sCleanup != null) {
        isCleanup = Boolean.valueOf(sCleanup);
    }

    TaskAttemptID attemptId = TaskAttemptID.forName(attemptIdStr);
    if (!TaskLog.getAttemptDir(attemptId, isCleanup).exists()) {
        response.sendError(HttpServletResponse.SC_GONE, "Task log directory for task " + attemptId
                + " does not exist. May be cleaned up by Task Tracker, if older logs.");
        return;
    }

    // get user name who is accessing
    String user = request.getRemoteUser();
    if (user != null) {
        ServletContext context = getServletContext();
        TaskTracker taskTracker = (TaskTracker) context.getAttribute("task.tracker");
        JobID jobId = attemptId.getJobID();

        // get jobACLConf from ACLs file
        JobConf jobACLConf = getConfFromJobACLsFile(jobId);
        // Ignore authorization if job-acls.xml is not found
        if (jobACLConf != null) {
            try {
                checkAccessForTaskLogs(jobACLConf, user, jobId.toString(), taskTracker);
            } catch (AccessControlException e) {
                String errMsg = "User " + user + " failed to view tasklogs of job " + jobId + "!\n\n"
                        + e.getMessage();
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, errMsg);
                return;
            }
        }
    }

    OutputStream out = response.getOutputStream();
    if (!plainText) {
        out.write(("<html>\n" + "<title>Task Logs: '" + attemptId + "'</title>\n" + "<body>\n"
                + "<h1>Task Logs: '" + attemptId + "'</h1><br>\n").getBytes());

        if (filter == null) {
            printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.STDOUT, isCleanup);
            printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.STDERR, isCleanup);
            if (haveTaskLog(attemptId, isCleanup, TaskLog.LogName.SYSLOG)) {
                printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.SYSLOG,
                        isCleanup);
            }
            if (haveTaskLog(attemptId, isCleanup, TaskLog.LogName.DEBUGOUT)) {
                printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.DEBUGOUT,
                        isCleanup);
            }
            if (haveTaskLog(attemptId, isCleanup, TaskLog.LogName.PROFILE)) {
                printTaskLog(response, out, attemptId, start, end, plainText, TaskLog.LogName.PROFILE,
                        isCleanup);
            }
        } else {
            printTaskLog(response, out, attemptId, start, end, plainText, filter, isCleanup);
        }

        out.write("</body></html>\n".getBytes());
        out.close();
    } else if (filter == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "You must supply a value for `filter' (STDOUT, STDERR, or SYSLOG) if you set plainText = true");
    } else {
        printTaskLog(response, out, attemptId, start, end, plainText, filter, isCleanup);
    }
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Create a new user in LDAP./*from ww  w.  java2 s. com*/
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView resetPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (!isFormSubmission(request)) {
        return new ModelAndView("resetPassword");
    }

    String password = request.getParameter("password");
    if (!validatePassword(password)) {
        ModelAndView mav = new ModelAndView("resetPassword");
        mav.addObject("password", password);
        mav.addObject("invalidPassword", true);
        return mav;
    }

    String remoteUser = request.getRemoteUser();
    ldapUtils.updatePassword(remoteUser, password);
    return new ModelAndView("passwordReset");
}

From source file:org.auscope.portal.server.web.controllers.JobListController.java

/**
 * Kills all jobs of given series./*from   w w w. j  av  a 2s. c om*/
 *
 * @param request The servlet request including a seriesId parameter
 * @param response The servlet response
 *
 * @return A JSON object with a success attribute and an error attribute
 *         in case the series was not found in the job manager.
 */
@RequestMapping("/killSeriesJobs.do")
public ModelAndView killSeriesJobs(HttpServletRequest request, HttpServletResponse response) {

    String seriesIdStr = request.getParameter("seriesId");
    List<GeodesyJob> jobs = null;
    ModelAndView mav = new ModelAndView("jsonView");
    boolean success = false;
    int seriesId = -1;
    Object credential = request.getSession().getAttribute("userCred");

    if (credential == null) {
        final String errorString = "Invalid grid credentials!";
        logger.error(errorString);
        mav.addObject("error", errorString);
        mav.addObject("success", false);
        return mav;
    }

    if (seriesIdStr != null) {
        try {
            seriesId = Integer.parseInt(seriesIdStr);
            jobs = jobManager.getSeriesJobs(seriesId);
        } catch (NumberFormatException e) {
            logger.error("Error parsing series ID!");
        }
    } else {
        logger.warn("No series ID specified!");
    }

    if (jobs == null) {
        final String errorString = "The requested series was not found.";
        logger.error(errorString);
        mav.addObject("error", errorString);
        mav.addObject("success", false);

    } else {
        // check if current user is the owner of the series
        GeodesySeries s = jobManager.getSeriesById(seriesId);
        if (request.getRemoteUser().equals(s.getUser())) {
            logger.info("Cancelling jobs of series " + seriesIdStr);
            for (GeodesyJob job : jobs) {
                String oldStatus = job.getStatus();
                if (oldStatus.equals("Failed") || oldStatus.equals("Done") || oldStatus.equals("Cancelled")) {
                    logger.debug("Skipping finished job " + job.getId());
                    continue;
                }
                logger.info("Killing job with ID " + job.getId());
                String newState = gridAccess.killJob(job.getReference(), credential);
                if (newState == null)
                    newState = "Cancelled";
                logger.debug("New job state: " + newState);

                job.setStatus(newState);
                jobManager.saveJob(job);
            }
            success = true;
        } else {
            logger.warn(request.getRemoteUser() + "'s attempt to kill " + s.getUser() + "'s jobs denied!");
            mav.addObject("error", "You are not authorised to cancel the jobs of this series.");
        }
    }

    mav.addObject("success", success);
    return mav;
}

From source file:org.auscope.portal.server.web.controllers.JobListController.java

/**
 * delete all jobs of given series.//from   w w w . j  ava 2s . c  om
 *
 * @param request The servlet request including a seriesId parameter
 * @param response The servlet response
 *
 * @return A JSON object with a success attribute and an error attribute
 *         in case the series was not found in the job manager.
 */
@RequestMapping("/deleteSeriesJobs.do")
public ModelAndView deleteSeriesJobs(HttpServletRequest request, HttpServletResponse response) {

    String seriesIdStr = request.getParameter("seriesId");
    List<GeodesyJob> jobs = null;
    ModelAndView mav = new ModelAndView("jsonView");
    boolean success = false;
    int seriesId = -1;
    Object credential = request.getSession().getAttribute("userCred");

    if (credential == null) {
        final String errorString = "Invalid grid credentials!";
        logger.error(errorString);
        mav.addObject("error", errorString);
        mav.addObject("success", false);
        return mav;
    }

    if (seriesIdStr != null) {
        try {
            seriesId = Integer.parseInt(seriesIdStr);
            jobs = jobManager.getSeriesJobs(seriesId);
        } catch (NumberFormatException e) {
            logger.error("Error parsing series ID!");
        }
    } else {
        logger.warn("No series ID specified!");
    }

    if (jobs == null) {
        final String errorString = "The requested series was not found.";
        logger.error(errorString);
        mav.addObject("error", errorString);
        mav.addObject("success", false);

    } else {
        // check if current user is the owner of the series
        GeodesySeries s = jobManager.getSeriesById(seriesId);
        if (request.getRemoteUser().equals(s.getUser())) {
            logger.info("Deleting jobs of series " + seriesIdStr);
            boolean jobsDeleted = true;
            for (GeodesyJob job : jobs) {
                String oldStatus = job.getStatus();
                if (oldStatus.equals("Failed") || oldStatus.equals("Done") || oldStatus.equals("Cancelled")) {
                    jobManager.deleteJob(job);

                } else {
                    logger.debug("Skipping running job " + job.getId());
                    if (jobsDeleted) {
                        jobsDeleted = false;
                        mav.addObject("error", "Can not delete series, there are running jobs.");
                    }
                    continue;
                }
            }
            if (jobsDeleted) {
                logger.info("Deleting series " + seriesIdStr);
                jobManager.deleteSeries(s);
                logger.info("Deleted series " + seriesIdStr);
                success = true;
            } else {
                success = false;
            }
        } else {
            logger.warn(request.getRemoteUser() + "'s attempt to delete " + s.getUser() + "'s jobs denied!");
            mav.addObject("error", "You are not authorised to delete the jobs of this series.");
        }
    }

    mav.addObject("success", success);
    return mav;
}

From source file:com.gtwm.pb.servlets.ServletSchemaMethods.java

public synchronized static void removeOperationalDashboardReport(SessionDataInfo sessionData,
        HttpServletRequest request, DatabaseInfo databaseDefn)
        throws MissingParametersException, ObjectNotFoundException, DisallowedException, CantDoThatException {
    BaseReportInfo report = ServletUtilMethods.getReportForRequest(sessionData, request, databaseDefn,
            ServletUtilMethods.USE_SESSION);
    AppUserInfo appUser = databaseDefn.getAuthManager().getUserByUserName(request, request.getRemoteUser());
    try {//from ww  w  . ja  v  a 2s. co m
        HibernateUtil.startHibernateTransaction();
        HibernateUtil.activateObject(appUser);
        appUser.removeOperationalDashboardReport(report);
        HibernateUtil.currentSession().getTransaction().commit();
    } catch (HibernateException hex) {
        rollbackConnections(null);
        throw new CantDoThatException("report un-hiding failed", hex);
    } finally {
        HibernateUtil.closeSession();
    }
}