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.kuali.rice.ken.web.spring.SendNotificationMessageController.java

/**
 * This method handles submitting the actual simple notification message.
 * @param request//from  w w  w .  ja va2  s  .  co  m
 * @param response
 * @return ModelAndView
 * @throws ServletException
 * @throws IOException
 */
public ModelAndView submitSimpleNotificationMessage(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 simple notification message submission form by user "
                + initiatorId);

        view = "SendSimpleNotificationMessage";

        // 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 = setupModelForSendSimpleNotification(request);
        model.putAll(model2);
        model.put("errors", el);

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

    return new ModelAndView(view, model);
}

From source file:org.apache.hadoop.yarn.server.nodemanager.webapp.NMWebServices.java

@GET
@Path("/containers")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ContainersInfo getNodeContainers(@javax.ws.rs.core.Context HttpServletRequest hsr) {
    init();/*from www.  ja va2 s.com*/
    ContainersInfo allContainers = new ContainersInfo();
    for (Entry<ContainerId, Container> entry : this.nmContext.getContainers().entrySet()) {
        if (entry.getValue() == null) {
            // just skip it
            continue;
        }
        ContainerInfo info = new ContainerInfo(this.nmContext, entry.getValue(),
                uriInfo.getBaseUri().toString(), webapp.name(), hsr.getRemoteUser());
        allContainers.add(info);
    }
    return allContainers;
}

From source file:org.eclipse.orion.server.servlets.PreferencesServlet.java

/**
 * Returns the metadata object associated with this request. This method controls
 * exactly what metadata objects are exposed via this service. If there is no matching
 * metadata object for the request, this method handles the appropriate response
 * and returns <code>null</code>.
 * @param req//from  ww  w .j  a va 2  s  .c o  m
 * @param resp
 */
private MetadataInfo getNode(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    String pathString = req.getPathInfo();
    if (pathString == null)
        pathString = ""; //$NON-NLS-1$
    IPath path = new Path(pathString);
    int segmentCount = path.segmentCount();
    String scope = path.segment(0);
    try {
        if ("user".equalsIgnoreCase(scope)) { //$NON-NLS-1$
            String username = req.getRemoteUser();
            if (username == null) {
                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return null;
            }
            return OrionConfiguration.getMetaStore().readUser(username);
        } else if ("workspace".equalsIgnoreCase(scope) && segmentCount > 1) { //$NON-NLS-1$
            //format is /workspace/{workspaceId}
            return OrionConfiguration.getMetaStore().readWorkspace(path.segment(1));
        } else if ("project".equalsIgnoreCase(scope) && segmentCount > 2) { //$NON-NLS-1$
            //format is /project/{workspaceId}/{projectName}
            return OrionConfiguration.getMetaStore().readProject(path.segment(1), path.segment(2));
        }
    } catch (CoreException e) {
        handleException(resp, "Internal error obtaining preferences", e,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
    //invalid prefix
    handleNotFound(req, resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    return null;
}

From source file:nl.b3p.viewer.stripes.EditFeatureActionBean.java

private boolean isFeatureWriteAuthorized(ApplicationLayer appLayer, JSONObject jsonFeature,
        HttpServletRequest request) {
    if (appLayer.getDetails() != null && appLayer.getDetails().containsKey("editfeature.usernameAttribute")) {
        String attr = appLayer.getDetails().get("editfeature.usernameAttribute").getValue();

        String featureUsername = jsonFeature.optString(attr);
        if (featureUsername != null && featureUsername.equals(request.getRemoteUser())) {
            return true;
        } else {/*www  .j a v  a2s  .  com*/
            return false;
        }
    }
    return true;
}

From source file:org.apache.hadoop.hbase.http.HttpServer.java

/**
 * Does the user sending the HttpServletRequest has the administrator ACLs? If
 * it isn't the case, response will be modified to send an error to the user.
 *
 * @param servletContext/*from   w ww  . j av  a  2 s .  c om*/
 * @param request
 * @param response used to send the error response if user does not have admin access.
 * @return true if admin-authorized, false otherwise
 * @throws IOException
 */
public static boolean hasAdministratorAccess(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    // If there is no authorization, anybody has administrator access.
    if (!conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
        return true;
    }

    String remoteUser = request.getRemoteUser();
    if (remoteUser == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Unauthenticated users are not " + "authorized to access this page.");
        return false;
    }

    if (servletContext.getAttribute(ADMINS_ACL) != null
            && !userHasAdministratorAccess(servletContext, remoteUser)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "User " + remoteUser + " is unauthorized to access this page.");
        return false;
    }

    return true;
}

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

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    updateSessionManager(request);//www .jav a  2  s.c  om

    try {
        if (action.equals("create")) {
            create(userId, request, response);
        } else if (action.equals("edit")) {
            edit(userId, request, response);
        } else if (action.equals("delete")) {
            delete(userId, request, response);
        } else if (action.equals("downloadFile")) {
            downloadFile(userId, request, response);
        } else if (action.equals("editAsc")) {
            editAscFile(userId, request, response);
        } else if (action.equals("editFields")) {
            editFieldsFile(userId, request, response);
        } else if (action.equals("check")) {
            check(userId, request, response);
        } else {
            list(userId, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.slamd.admin.RequestInfo.java

/**
 * Creates a new set of request state information using the provided request
 * and response./*from www .ja  va 2 s  .co  m*/
 *
 * @param  request   Information about the HTTP request issued by the client.
 * @param  response  Information about the HTTP response that will be returned
 *                   to the client.
 */
public RequestInfo(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;

    generateHTML = true;
    debugInfo = new StringBuilder();
    htmlBody = new StringBuilder();
    infoMessage = new StringBuilder();

    if (request != null) {
        servletBaseURI = request.getRequestURI();
        userIdentifier = request.getRemoteUser();

        if (FileUpload.isMultipartContent(request)) {
            try {
                FileUpload fileUpload = new FileUpload(new DefaultFileItemFactory());
                multipartFieldList = fileUpload.parseRequest(request);
                Iterator iterator = multipartFieldList.iterator();

                while (iterator.hasNext()) {
                    FileItem fileItem = (FileItem) iterator.next();
                    String name = fileItem.getFieldName();
                    if (name.equals(Constants.SERVLET_PARAM_SECTION)) {
                        section = new String(fileItem.get());
                    } else if (name.equals(Constants.SERVLET_PARAM_SUBSECTION)) {
                        subsection = new String(fileItem.get());
                    }
                }
            } catch (FileUploadException fue) {
                fue.printStackTrace();
            }
        } else {
            section = request.getParameter(Constants.SERVLET_PARAM_SECTION);
            subsection = request.getParameter(Constants.SERVLET_PARAM_SUBSECTION);
        }
    }

    if (section == null) {
        section = "";
    }

    if (subsection == null) {
        subsection = "";
    }
}

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

/**
 * Show form./*w ww . ja  v a 2s . c o  m*/
 * 
 * @param request
 *            the request
 * @return the model and view
 */
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView showForm(final HttpServletRequest request) {
    final ModelAndView model = new ModelAndView("dashBoard");
    AlphaCard activeCard = null;

    final String version = request.getParameter("version");
    Long versionL = null;
    if (StringUtils.isNotBlank(version)) {
        try {
            versionL = Long.parseLong(version);
        } catch (final NumberFormatException e) {

        }
    }

    // get the current user
    final User currentUser = this.userManager.getUserByUsername(request.getRemoteUser());

    final List<AlphaCase> caseList = this.caseManager.findByParticipant(currentUser);

    final List<AlphaCard> cardsList = this.cardManager.listDashBoardCards(caseList);

    for (final AlphaCard c : cardsList) {
        if (c.getAlphaCardIdentifier().getSequenceNumber().equals(versionL)) {
            activeCard = c;
            break;
        }
    }

    final List<ContributorRequest> contrReqList = this.contrReqManager.getAll();
    final List<ContributorRequest> newList = new LinkedList<ContributorRequest>();

    if (!contrReqList.isEmpty()) {
        for (final ContributorRequest req : contrReqList) {
            if (currentUser.getId().equals(req.getAcceptingUser().getId())) {
                newList.add(req);
            }
        }
    }

    model.addObject("requests", newList);

    model.addObject("cards", cardsList);
    model.addObject("activeCard", activeCard);

    return model;
}

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

/**
 * This method prepares the model used for the send event notification message form.
 * @param request/*from   w w  w .  ja  va 2s.  c  o m*/
 * @return Map<String, Object>
 */
private Map<String, Object> setupModelForSendEventNotification(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("defaultSender", request.getRemoteUser());
    model.put("channels", notificationChannelService.getAllNotificationChannels());
    model.put("priorities", businessObjectDao.findAll(NotificationPriorityBo.class));
    // set sendDateTime to current datetime if not provided
    String sendDateTime = request.getParameter("sendDateTime");
    String currentDateTime = Util.getCurrentDateTime();
    if (StringUtils.isEmpty(sendDateTime)) {
        sendDateTime = currentDateTime;
    }
    model.put("sendDateTime", sendDateTime);

    // retain the original date time or set to current if
    // it was not in the request
    if (request.getParameter("originalDateTime") == null) {
        model.put("originalDateTime", currentDateTime);
    } else {
        model.put("originalDateTime", request.getParameter("originalDateTime"));
    }
    model.put("summary", request.getParameter("summary"));
    model.put("description", request.getParameter("description"));
    model.put("location", request.getParameter("location"));
    model.put("startDateTime", request.getParameter("startDateTime"));
    model.put("stopDateTime", request.getParameter("stopDateTime"));

    model.put("userRecipients", request.getParameter("userRecipients"));
    model.put("workgroupRecipients", request.getParameter("workgroupRecipients"));
    model.put("workgroupNamespaceCodes", request.getParameter("workgroupNamespaceCodes"));

    return model;
}

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

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*from  w w  w  .j av  a  2 s  .c o m*/

    try {
        if (action.equals("edit")) {
            edit(userId, request, response);
        } else if (action.equals("delete")) {
            delete(userId, request, response);
        } else if (action.equals("create")) {
            create(userId, request, response);
        } else if (action.equals("translate")) {
            translate(userId, request, response);
        } else if (action.equals("flag")) {
            flag(userId, request, response);
        } else if (action.equals("export")) {
            export(userId, request, response);
        } else if (action.equals("addTranslation")) {
            addTranslation(userId, request, response);
        }

        if (action.equals("") || WebUtils.getBoolean(request, "persist")) {
            list(userId, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}