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.sfs.dao.SAMLAuthenticationDAOImpl.java

/**
 * Load the UserBean from the SAML (CAS) response.
 *
 * @param userName the user name//from w  w  w .  j av  a2  s  . co m
 * @param request the servlet request
 *
 * @return the user bean
 *
 * @throws SFSDaoException the SFS dao exception
 */
public final UserBean load(final String userName, final HttpServletRequest request) throws SFSDaoException {

    // Loads user details into bean using a supplied username
    if (userName == null) {
        throw new SFSDaoException("Username cannot be null");
    }
    if (userName.compareTo("") == 0) {
        throw new SFSDaoException("Username cannot be an empty string");
    }

    UserBean user = null;

    if (request != null && request.getUserPrincipal() != null) {

        final String username = request.getRemoteUser();

        if (StringUtils.isNotBlank(username)) {
            final AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();

            final Map<?, ?> attributes = principal.getAttributes();

            user = loadUserDetails(username, attributes);
        }
    }

    if (user == null) {
        throw new SFSDaoException("A user object for this username was not found");
    }
    return user;
}

From source file:org.kuali.rice.ken.web.spring.SendEventNotificationMessageController.java

/**
 * Handles the display of the form for sending an event notification message
 * @param request : a servlet request//w  w w. j a  v a2  s.  c om
 * @param response : a servlet response
 * @throws ServletException : an exception
 * @throws IOException : an exception
 * @return a ModelAndView object
 */
public ModelAndView sendEventNotificationMessage(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String view = "SendEventNotificationMessage";
    LOG.debug("remoteUser: " + request.getRemoteUser());

    Map<String, Object> model = setupModelForSendEventNotification(request);
    model.put("errors", new ErrorList()); // need an empty one so we don't have an NPE

    return new ModelAndView(view, model);
}

From source file:org.apache.hadoop.hdfs.server.namenode.GetImageServlet.java

@SuppressWarnings("unchecked")
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    Map<String, String[]> pmap = request.getParameterMap();
    try {//from   w  ww  .jav  a  2s  . c  o  m
        ServletContext context = getServletContext();
        final FSImage nnImage = (FSImage) context.getAttribute("name.system.image");
        final TransferFsImage ff = new TransferFsImage(pmap, request, response);
        final Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);
        if (UserGroupInformation.isSecurityEnabled() && !isValidRequestor(request.getRemoteUser(), conf)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Only Namenode and Secondary Namenode may access this servlet");
            LOG.warn("Received non-NN/SNN request for image or edits from " + request.getRemoteHost());
            return;
        }

        UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                if (ff.getImage()) {
                    // send fsImage
                    TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsImageName());
                } else if (ff.getEdit()) {
                    // send edits
                    TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsEditName());
                } else if (ff.putImage()) {
                    // issue a HTTP get request to download the new fsimage 
                    nnImage.validateCheckpointUpload(ff.getToken());
                    reloginIfNecessary().doAs(new PrivilegedExceptionAction<Void>() {
                        @Override
                        public Void run() throws Exception {
                            TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1",
                                    nnImage.getFsImageNameCheckpoint());
                            return null;
                        }
                    });

                    nnImage.checkpointUploadDone();
                }
                return null;
            }

            // We may have lost our ticket since the last time we tried to open
            // an http connection, so log in just in case.
            private UserGroupInformation reloginIfNecessary() throws IOException {
                // This method is only called on the NN, therefore it is safe to
                // use these key values.
                return UserGroupInformation.loginUserFromKeytabAndReturnUGI(
                        SecurityUtil.getServerPrincipal(conf.get(DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY),
                                NameNode.getAddress(conf).getHostName()),
                        conf.get(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY));
            }
        });

    } catch (Exception ie) {
        String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie);
        response.sendError(HttpServletResponse.SC_GONE, errMsg);
        throw new IOException(errMsg);
    } finally {
        response.getOutputStream().close();
    }
}

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

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*from w w w . j  a  va2s .com*/

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            String fileName = null;
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Set<String> properties = new HashSet<String>();
            Omr om = new Omr();

            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("om_id")) {
                        om.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("om_name")) {
                        om.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_properties")) {
                        properties.add(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_active")) {
                        om.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    fileName = item.getName();
                }
            }

            om.setProperties(properties);

            if (action.equals("create") || action.equals("edit")) {
                // Store locally template file to be used later
                if (is != null && is.available() > 0) { // Case update only name
                    byte[] data = IOUtils.toByteArray(is);
                    File tmp = FileUtils.createTempFile();
                    FileOutputStream fos = new FileOutputStream(tmp);
                    IOUtils.write(data, fos);
                    IOUtils.closeQuietly(fos);

                    // Store template file
                    om.setTemplateFileName(FilenameUtils.getName(fileName));
                    om.setTemplateFileMime(MimeTypeConfig.mimeTypes.getContentType(fileName));
                    om.setTemplateFilContent(data);
                    IOUtils.closeQuietly(is);

                    // Create training files
                    Map<String, File> trainingMap = OMRHelper.trainingTemplate(tmp);
                    File ascFile = trainingMap.get(OMRHelper.ASC_FILE);
                    File configFile = trainingMap.get(OMRHelper.CONFIG_FILE);

                    // Store asc file
                    om.setAscFileName(om.getTemplateFileName() + ".asc");
                    om.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(ascFile);
                    om.setAscFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Store config file
                    om.setConfigFileName(om.getTemplateFileName() + ".config");
                    om.setConfigFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(configFile);
                    om.setConfigFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Delete temporal files
                    FileUtils.deleteQuietly(tmp);
                    FileUtils.deleteQuietly(ascFile);
                    FileUtils.deleteQuietly(configFile);
                }

                if (action.equals("create")) {
                    long id = OmrDAO.getInstance().create(om);

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_CREATE", Long.toString(id), null, om.toString());
                } else if (action.equals("edit")) {
                    OmrDAO.getInstance().updateTemplate(om);
                    om = OmrDAO.getInstance().findByPk(om.getId());

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_EDIT", Long.toString(om.getId()), null, om.toString());
                }

                list(userId, request, response);
            } else if (action.equals("delete")) {
                OmrDAO.getInstance().delete(om.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_DELETE", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editAsc")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setAscFileContent(IOUtils.toByteArray(is));
                omr.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setAscFileName(omr.getTemplateFileName() + ".asc");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_ASC", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editFields")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setFieldsFileContent(IOUtils.toByteArray(is));
                omr.setFieldsFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setFieldsFileName(omr.getTemplateFileName() + ".fields");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_FIELDS", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("check")) {
                File form = FileUtils.createTempFile();
                OutputStream formFile = new FileOutputStream(form);
                formFile.write(IOUtils.toByteArray(is));
                IOUtils.closeQuietly(formFile);
                formFile.close();
                Map<String, String> results = OMRHelper.process(form, om.getId());
                FileUtils.deleteQuietly(form);
                IOUtils.closeQuietly(is);
                UserActivity.log(userId, "ADMIN_OMR_CHECK_TEMPLATE", Long.toString(om.getId()), null, null);
                results(userId, request, response, action, results, om.getId());
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

@GET
@Path("/{id}")
@Produces(APPLICATION_JSON)//from   w  ww .  j  a va  2 s  . co m
public Response getReport(@Context HttpServletRequest request, @PathParam("id") Long id,
        @HeaderParam("scopeName") String scopeName, @HeaderParam("roleName") String roleName) {

    String username = request.getRemoteUser();
    ReportDTO report;

    try {
        boolean isAdmin = request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString());
        Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
                scopeName);
        List<String> permittedServiceLayers = new ArrayList<>(ServiceLayerUtils
                .getUserPermittedLayersNames(usmService, request.getRemoteUser(), roleName, scopeName));
        report = reportService.findById(features, id, username, scopeName, isAdmin, permittedServiceLayers);
    } catch (Exception e) {
        log.error("Failed to get report.", e);
        return createErrorResponse();
    }

    Response restResponse;

    if (report != null) {
        restResponse = createSuccessResponse(report);
    } else {
        restResponse = createScNotFoundErrorResponse(ErrorCodes.ENTRY_NOT_FOUND);
    }

    return restResponse;
}

From source file:org.kuali.rice.ken.web.spring.SendEventNotificationMessageController.java

/**
 * This method handles submitting the actual event notification message.
 * @param request//from   w  w w .j av  a 2s.c  om
 * @param response
 * @return ModelAndView
 * @throws ServletException
 * @throws IOException
 */
public ModelAndView submitEventNotificationMessage(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("remoteUser: " + request.getRemoteUser());

    // obtain a workflow user object first
    //WorkflowIdDTO initiator = new WorkflowIdDTO(request.getRemoteUser());
    String initiatorId = getPrincipalIdFromIdOrName(request.getRemoteUser());
    LOG.debug("initiatorId=" + initiatorId);

    // now construct the workflow document, which will interact with workflow
    WorkflowDocument document;
    Map<String, Object> model = new HashMap<String, Object>();
    String view;
    try {
        document = NotificationWorkflowDocument.createNotificationDocument(initiatorId,
                NotificationConstants.KEW_CONSTANTS.SEND_NOTIFICATION_REQ_DOC_TYPE);

        //parse out the application content into a Notification BO
        NotificationBo notification = populateNotificationInstance(request, model);

        // now get that content in an understandable XML format and pass into document
        String notificationAsXml = messageContentService.generateNotificationMessage(notification);

        Map<String, String> attrFields = new HashMap<String, String>();
        List<NotificationChannelReviewerBo> reviewers = notification.getChannel().getReviewers();
        int ui = 0;
        int gi = 0;
        for (NotificationChannelReviewerBo reviewer : reviewers) {
            String prefix;
            int index;
            if (KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.equals(reviewer.getReviewerType())) {
                prefix = "user";
                index = ui;
                ui++;
            } else if (KimGroupMemberTypes.GROUP_MEMBER_TYPE.equals(reviewer.getReviewerType())) {
                prefix = "group";
                index = gi;
                gi++;
            } else {
                LOG.error("Invalid type for reviewer " + reviewer.getReviewerId() + ": "
                        + reviewer.getReviewerType());
                continue;
            }
            attrFields.put(prefix + index, reviewer.getReviewerId());
        }
        GenericAttributeContent gac = new GenericAttributeContent("channelReviewers");
        document.setApplicationContent(notificationAsXml);
        document.setAttributeContent(
                "<attributeContent>" + gac.generateContent(attrFields) + "</attributeContent>");

        document.setTitle(notification.getTitle());

        document.route("This message was submitted via the event notification message submission form by user "
                + initiatorId);

        view = "SendEventNotificationMessage";

        // This ain't pretty, but it gets the job done for now.
        ErrorList el = new ErrorList();
        el.addError("Notification(s) sent.");
        model.put("errors", el);

    } catch (ErrorList el) {
        // route back to the send form again
        Map<String, Object> model2 = setupModelForSendEventNotification(request);
        model.putAll(model2);
        model.put("errors", el);

        view = "SendEventNotificationMessage";
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return new ModelAndView(view, model);
}

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

/**
 * Purge log/* ww  w  .j  a  va  2 s.  c  o  m*/
 */
@SuppressWarnings("unchecked")
private void purge(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("purge({}, {})", request, response);
    for (File lf : (Collection<File>) FileUtils.listFiles(logFolder, null, false)) {
        if (lf.getName().matches(".+[0-9][0-9]-[0-9][0-9]-[0-9][0-9].*")) {
            lf.delete();
        }
    }

    ServletContext sc = getServletContext();
    sc.setAttribute("files", FileUtils.listFiles(logFolder, null, false));
    sc.getRequestDispatcher("/admin/logcat.jsp").forward(request, response);

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_LOGCAT_PURGE", null, null, null);

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

From source file:org.kuali.rice.ken.web.spring.BaseSendNotificationController.java

/**
 * Submits the actual event notification message.
 *
 * @param request the servlet request//  w ww.jav a2  s.co  m
 * @param routeMessage the message to attach to the route action
 * @param viewName the name of the view to forward to after completion
 *
 * @return the next view to show
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected ModelAndView submitNotificationMessage(HttpServletRequest request, String routeMessage,
        String viewName) throws ServletException, IOException {
    LOG.debug("remoteUser: " + request.getRemoteUser());

    // obtain a workflow user object first
    //WorkflowIdDTO initiator = new WorkflowIdDTO(request.getRemoteUser());
    String initiatorId = getPrincipalIdFromIdOrName(request.getRemoteUser());
    LOG.debug("initiatorId: " + initiatorId);

    // now construct the workflow document, which will interact with workflow
    Map<String, Object> model = new HashMap<String, Object>();

    try {
        WorkflowDocument document = createNotificationWorkflowDocument(request, initiatorId, model);

        document.route(routeMessage + initiatorId);

        // This ain't pretty, but it gets the job done for now.
        ErrorList el = new ErrorList();
        el.addError("Notification(s) sent.");
        model.put("errors", el);
    } catch (ErrorList el) {
        // route back to the send form again
        Map<String, Object> model2 = setupModelForSendNotification(request);
        model.putAll(model2);
        model.put("errors", el);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return new ModelAndView(viewName, model);
}

From source file:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

private Collection<ReportDTO> listReportByUsernameAndScope(HttpServletRequest request, String scopeName,
        String roleName, String existent, Integer numberOfReport)
        throws ServiceException, ReportingServiceException {
    final String username = request.getRemoteUser();
    log.debug("{} is requesting listReports(...), with a scopeName={}", username, scopeName);
    Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
            scopeName);// w  w  w .  j  a v a2  s . co m
    String defaultId = usmService.getUserPreference(DEFAULT_REPORT_ID, username, getApplicationName(request),
            roleName, scopeName);
    Long defaultReportId = StringUtils.isNotBlank(defaultId) ? Long.valueOf(defaultId) : null;
    ReportFeatureEnum requiredFeature = AuthorizationCheckUtil.getRequiredFeatureToListReports();

    if (username != null && features != null
            && (requiredFeature == null || request.isUserInRole(requiredFeature.toString()))) {
        return reportService.listByUsernameAndScope(features, username, scopeName, "Y".equals(existent),
                defaultReportId, numberOfReport);
    } else {
        throw new ReportingServiceException(ErrorCodes.NOT_AUTHORIZED);
    }
}

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

@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute("language") Language language, BindingResult result) throws Exception {

    validator.validate(language, result);

    if (result.hasErrors()) {
        return new ModelAndView("edit_language", new ModelMap());
    }//from   w  w  w  . j a v  a2  s . c  o m

    language.setUpdater(getUser(request).getUsername());
    /* Save language to DB */
    if (!languagesService.update(language)) {
        throw new Exception("Updating language failed.");
    }

    /* Update logged in user */
    HttpSession session = request.getSession();
    session.removeAttribute("user");
    session.setAttribute("user", usersService.getUser(request.getRemoteUser()));
    /* Return to languages page */
    return new ModelAndView(
            "redirect:languages.htm?select_language=" + request.getParameter("select_language"));
}