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.opennms.web.map.OpenMapController.java

/** {@inheritDoc} */
@Override//  www  .j a v a 2s . c  o m
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    LOG.debug(request.getQueryString());
    String mapIdStr = request.getParameter("MapId");
    LOG.debug("MapId={}", mapIdStr);
    String mapWidthStr = request.getParameter("MapWidth");
    LOG.debug("MapWidth={}", mapWidthStr);
    String mapHeightStr = request.getParameter("MapHeight");
    LOG.debug("MapHeight={}", mapHeightStr);
    String adminModeStr = request.getParameter("adminMode");
    LOG.debug("adminMode={}", adminModeStr);

    String user = request.getRemoteUser();

    if ((request.isUserInRole(org.opennms.web.api.Authentication.ROLE_ADMIN))) {
        LOG.info("{} has Admin admin Role", user);
    }

    float widthFactor = 1;
    float heightFactor = 1;

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));

    try {
        int mapWidth = WebSecurityUtils.safeParseInt(mapWidthStr);
        int mapHeight = WebSecurityUtils.safeParseInt(mapHeightStr);

        LOG.debug("Current mapWidth={} and MapHeight={}", mapWidth, mapHeight);
        VMap map = null;
        if (mapIdStr != null) {
            int mapid = WebSecurityUtils.safeParseInt(mapIdStr);
            LOG.debug("Opening map {} for user {}", mapid, user);
            map = manager.openMap(mapid, user, !(adminModeStr.equals("true")));
        } else {
            LOG.debug("Try to Opening default map");
            VMapInfo defaultmapinfo = manager.getDefaultMapsMenu(user);
            if (defaultmapinfo != null) {
                map = manager.openMap(defaultmapinfo.getId(), user, !(adminModeStr.equals("true")));
            } else {
                map = manager.openMap();
            }
        }

        if (map != null) {
            int dbMapWidth = map.getWidth();
            int dbMapHeight = map.getHeight();
            widthFactor = (float) mapWidth / dbMapWidth;
            heightFactor = (float) mapHeight / dbMapHeight;

            LOG.debug("Old saved mapWidth={} and MapHeight={}", dbMapWidth, dbMapHeight);
            LOG.debug("widthFactor={}", widthFactor);
            LOG.debug("heightFactor={}", heightFactor);
            LOG.debug("Setting new width and height to the session map");

            map.setHeight(mapHeight);
            map.setWidth(mapWidth);

            for (VElement ve : map.getElements().values()) {
                ve.setX((int) (ve.getX() * widthFactor));
                ve.setY((int) (ve.getY() * heightFactor));
            }

            SparseGraph<VElement, VLink> jungGraph = new SparseGraph<VElement, VLink>();

            for (VElement ve : map.getElements().values()) {
                jungGraph.addVertex(ve);
            }
            for (VLink vl : map.getLinks()) {
                jungGraph.addEdge(vl, map.getElement(vl.getFirst()), map.getElement(vl.getSecond()));
            }

            KKLayout<VElement, VLink> layout = new KKLayout<VElement, VLink>(jungGraph);
            layout.setInitializer(initializer(map));
            layout.setSize(selectLayoutSize(map));

            while (!layout.done()) {
                layout.step();
            }

            int vertexCount = map.getElements().size();
            for (VElement ve : map.getElements().values()) {
                LOG.debug("---------Element {}---------", ve.getLabel());
                LOG.debug("dbcoor: X={} Y={}", ve.getX(), ve.getY());
                LOG.debug("kkcoor: X={} Y={}", layout.getX(ve), layout.getY(ve));
                LOG.debug("kkcoor: X={} Y={}", (int) layout.getX(ve), (int) layout.getY(ve));
                LOG.debug("");
                if (vertexCount >= 10) {
                    ve.setX((int) layout.getX(ve) - 100);
                    ve.setY((int) layout.getY(ve) - 100);
                } else {
                    ve.setX((int) layout.getX(ve));
                    ve.setY((int) layout.getY(ve));
                }
                LOG.debug("vmspcoor: X={} Y={}", ve.getX(), ve.getY());
            }
        }

        bw.write(ResponseAssembler.getMapResponse(map));

    } catch (Throwable e) {
        LOG.error("Error while opening map with id:{}, for user:{}", mapIdStr, user, e);
        bw.write(ResponseAssembler.getMapErrorResponse(MapsConstants.OPENMAP_ACTION));
    } finally {
        bw.close();
    }

    return null;
}

From source file:org.eclipse.orion.server.docker.servlets.DockerHandler.java

/**
 * Handle the connect request for a user. The request creates an image for the user, a container for the user based 
 * on that image, starts the container and then attaches to the container via a web socket. An existing container 
 * for the user is reused if it already exists. if the singleton container for a user is already attached, 
 * no operation is needed./*from  ww w  . jav a 2 s.  c  om*/
 * @param request
 * @param response
 * @return true if the connect was successful.
 * @throws ServletException
 */
private boolean handleConnectDockerContainerRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    try {
        // get the Orion user from the request
        String user = request.getRemoteUser();

        DockerServer dockerServer = getDockerServer();

        // check if the user is already attached to a docker container
        if (dockerServer.isAttachedDockerContainer(user)) {
            // stop the container
            DockerContainer dockerContainer = dockerServer.getDockerContainer(user);
            if (dockerContainer.getStatusCode() == DockerResponse.StatusCode.OK) {
                dockerContainer = dockerServer.stopDockerContainer(dockerContainer.getId());
                if (dockerContainer.getStatusCode() == DockerResponse.StatusCode.STOPPED) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Stopped Docker Container " + dockerContainer.getIdShort() + " for user "
                                + user);
                    }
                }
            }

            // detach the connection for the user
            dockerServer.detachDockerContainer(user);
        }

        // make sure the image for the user has been created
        String userBase = user + "-base";
        DockerImage dockerImage = dockerServer.getDockerImage(userBase);
        if (dockerImage.getStatusCode() != DockerResponse.StatusCode.OK) {

            // user does not have a image, create one
            dockerImage = dockerServer.createDockerUserBaseImage(user);
            if (dockerImage.getStatusCode() != DockerResponse.StatusCode.CREATED) {
                return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                        HttpServletResponse.SC_BAD_REQUEST, dockerImage.getStatusMessage(), null));
            }
            if (logger.isInfoEnabled()) {
                logger.info("Created Docker Image " + userBase + " for user " + user);
            }
        }

        // get the volume (workspace root) for the user
        String volume = getDockerVolume(user);

        // get the container for the user
        DockerContainer dockerContainer = dockerServer.getDockerContainer(user);
        if (dockerContainer.getStatusCode() != DockerResponse.StatusCode.OK) {

            // user does not have a container, create one
            dockerContainer = dockerServer.createDockerContainer(userBase, user, volume);
            if (dockerContainer.getStatusCode() != DockerResponse.StatusCode.CREATED) {
                return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                        HttpServletResponse.SC_BAD_REQUEST, dockerContainer.getStatusMessage(), null));
            }
            if (logger.isInfoEnabled()) {
                logger.info("Created Docker Container " + dockerContainer.getIdShort() + " for user " + user);
            }

            // if the user does not have a bashrc, create one
            createBashrc(user);
        }

        // get the exposed ports from the docker image
        List<String> portNumbers = new ArrayList<String>();
        for (String port : dockerImage.getPorts()) {
            if (port.contains("/tcp")) {
                port = port.substring(0, port.indexOf("/tcp"));
            }
            portNumbers.add(port);
        }

        // start the container for the user
        dockerContainer = dockerServer.startDockerContainer(user, volume, portNumbers);
        if (dockerContainer.getStatusCode() == DockerResponse.StatusCode.STARTED) {
            if (logger.isInfoEnabled()) {
                logger.info("Started Docker Container " + dockerContainer.getIdShort() + " for user " + user);
            }
        } else if (dockerContainer.getStatusCode() == DockerResponse.StatusCode.RUNNING) {
            if (logger.isInfoEnabled()) {
                logger.info("Docker Container " + dockerContainer.getIdShort() + " for user " + user
                        + " is already running");
            }
        } else {
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, dockerContainer.getStatusMessage(), null));
        }

        // attach to the container for the user 
        String originURL = request.getRequestURL().toString();
        DockerResponse dockerResponse = dockerServer.attachDockerContainer(user, originURL);
        if (dockerResponse.getStatusCode() != DockerResponse.StatusCode.ATTACHED) {
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, dockerContainer.getStatusMessage(), null));
        }
        if (logger.isInfoEnabled()) {
            logger.info("Attach Docker Container " + dockerContainer.getIdShort() + " for user " + user
                    + " successful");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put(DockerContainer.ATTACH_WS, dockerResponse.getStatusMessage());
        OrionServlet.writeJSONResponse(request, response, jsonObject);
        return true;
    } catch (IOException e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "IOException with request", e));
    } catch (JSONException e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "JSONException with request", e));
    }
}

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

@GET
@Path("/containers/{containerid}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ContainerInfo getNodeContainer(@javax.ws.rs.core.Context HttpServletRequest hsr,
        @PathParam("containerid") String id) {
    ContainerId containerId = null;/*from w ww  .  j a v  a  2  s .  co  m*/
    init();
    try {
        containerId = ContainerId.fromString(id);
    } catch (Exception e) {
        throw new BadRequestException("invalid container id, " + id);
    }

    Container container = nmContext.getContainers().get(containerId);
    if (container == null) {
        throw new NotFoundException("container with id, " + id + ", not found");
    }
    return new ContainerInfo(this.nmContext, container, uriInfo.getBaseUri().toString(), webapp.name(),
            hsr.getRemoteUser());

}

From source file:com.openkm.servlet.admin.ConfigServlet.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 filter = WebUtils.getString(request, "filter");
    String userId = request.getRemoteUser();
    updateSessionManager(request);//from   www.  j  av  a 2 s .  co  m

    try {
        if (action.equals("create")) {
            create(userId, types, request, response);
        } else if (action.equals("edit")) {
            edit(userId, types, request, response);
        } else if (action.equals("delete")) {
            delete(userId, types, request, response);
        } else if (action.equals("view")) {
            view(userId, request, response);
        } else if (action.equals("check")) {
            check(userId, request, response);
        } else if (action.equals("export")) {
            export(userId, request, response);
        } else {
            list(userId, filter, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

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

@PUT
@Produces("text/json")
public Response putProfile(@Context HttpServletRequest con, @PathParam("username") String username,
        String json) {/*from   w  w  w. j a  v  a 2  s.c o m*/

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

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

        // check if remote user == {username} in path param
        if (!username.equals(con.getRemoteUser())) {
            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 ProfileRequest());

        XStream x = Utils.getJasonXStreamer(list);

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

        //TODO: data validation!
        //resp.setStatus(resp.SC_BAD_REQUEST);

        Date dateOfBirth;
        if (r.getDateOfBirth() != null) {
            dateOfBirth = new Date(r.getDateOfBirth());
        } else {
            dateOfBirth = null;
        }

        Date licenseDate;
        if (r.getLicenseDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.clear();
            cal.set(r.getLicenseDate(), 0, 1);
            licenseDate = cal.getTime();
        } else {
            licenseDate = null;
        }

        // Validate email address:
        CustomerEntity other_c = customerControllerBean.getCustomerByEmail(r.getEmail());

        // Allow existing email address if it is the user's current one!
        if (other_c != null && !other_c.getCustEmail().equals(c.getCustEmail())) {
            // "Ein Benutzer mit dieser E-Mail-Adresse ist bereits registriert."
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

        // Pilotierung: nur ZU-Adressen zulssig
        /*if (!r.getEmail().endsWith("zeppelin-university.de") && !r.getEmail().endsWith("zeppelin-university.net") && !r.getEmail().endsWith("fokus.fraunhofer.de")) {
        // "E-Mail-Adresse muss auf \"zeppelin-university.de\" enden."
        return Response.status(Response.Status.BAD_REQUEST).build();
        }*/

        customerControllerBean.setPersonalData(c.getCustId(), dateOfBirth, r.getEmail(),
                r.getMobilePhoneNumber(), r.getFixedPhoneNumber(), r.getStreetAddress(), r.getZipCode(),
                r.getCity(), r.getIsSmoker(), licenseDate);
        carDetailsControllerBean.updateCarDetails(c, r.getCarBrand(), r.getCarBuildYear(), r.getCarColour(),
                r.getCarPlateNo());

        return Response.ok().build();

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

}

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

private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String pathString)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    URI baseLocation = getURI(request);
    String user = request.getRemoteUser();
    // expected path format is 'workspace/{workspaceId}' or 'file/{workspaceId}/{projectName}/{path}]'
    if ("workspace".equals(path.segment(0)) && path.segmentCount() == 2) { //$NON-NLS-1$
        // all clones in the workspace
        WorkspaceInfo workspace = OrionConfiguration.getMetaStore().readWorkspace(path.segment(1));
        if (workspace != null) {
            JSONObject result = new JSONObject();
            JSONArray children = new JSONArray();
            for (String projectName : workspace.getProjectNames()) {
                ProjectInfo project = OrionConfiguration.getMetaStore().readProject(workspace.getUniqueId(),
                        projectName);//  w w w  .j  a v  a 2 s.  c  om
                //this is the location of the project metadata
                if (isAccessAllowed(user, project)) {
                    IPath projectPath = GitUtils.pathFromProject(workspace, project);
                    Map<IPath, File> gitDirs = GitUtils.getGitDirs(projectPath, Traverse.GO_DOWN);
                    for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) {
                        children.put(new Clone().toJSON(entry, baseLocation));
                    }
                }
            }
            result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE);
            result.put(ProtocolConstants.KEY_CHILDREN, children);
            OrionServlet.writeJSONResponse(request, response, result);
            return true;
        }
        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));
    } else if ("file".equals(path.segment(0)) && path.segmentCount() > 1) { //$NON-NLS-1$
        // clones under given path
        ProjectInfo webProject = GitUtils.projectFromPath(path);
        IPath projectRelativePath = path.removeFirstSegments(3);
        if (webProject != null && isAccessAllowed(user, webProject)
                && webProject.getProjectStore().getFileStore(projectRelativePath).fetchInfo().exists()) {
            Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.GO_DOWN);
            JSONObject result = new JSONObject();
            JSONArray children = new JSONArray();
            for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) {
                children.put(new Clone().toJSON(entry, baseLocation));
            }
            result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE);
            result.put(ProtocolConstants.KEY_CHILDREN, children);
            OrionServlet.writeJSONResponse(request, response, result);
            return true;
        }
        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));
    }
    //else the request is malformed
    String msg = NLS.bind("Invalid clone request: {0}", path);
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}

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

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    ServletContext sc = getServletContext();
    String action = null;//  w w w.ja va2 s. c om
    String filter = null;
    String userId = request.getRemoteUser();
    Session dbSession = null;
    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);
            Config cfg = new Config();
            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("filter")) {
                        filter = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("cfg_key")) {
                        cfg.setKey(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("cfg_type")) {
                        cfg.setType(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("cfg_value")) {
                        cfg.setValue(item.getString("UTF-8").trim());
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    is.close();
                }
            }

            if (action.equals("create")) {
                if (Config.BOOLEAN.equals(cfg.getType())) {
                    cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals("")));
                } else if (Config.SELECT.equals(cfg.getType())) {
                    ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey());

                    if (stSelect != null) {
                        for (ConfigStoredOption stOption : stSelect.getOptions()) {
                            if (stOption.getValue().equals(cfg.getValue())) {
                                stOption.setSelected(true);
                            }
                        }
                    }

                    cfg.setValue(new Gson().toJson(stSelect));
                }

                ConfigDAO.create(cfg);
                com.ikon.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_CREATE", cfg.getKey(), null, cfg.toString());
                list(userId, filter, request, response);
            } else if (action.equals("edit")) {
                if (Config.BOOLEAN.equals(cfg.getType())) {
                    cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals("")));
                } else if (Config.SELECT.equals(cfg.getType())) {
                    ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey());

                    if (stSelect != null) {
                        for (ConfigStoredOption stOption : stSelect.getOptions()) {
                            if (stOption.getValue().equals(cfg.getValue())) {
                                stOption.setSelected(true);
                            } else {
                                stOption.setSelected(false);
                            }
                        }
                    }

                    cfg.setValue(new Gson().toJson(stSelect));
                }

                ConfigDAO.update(cfg);
                com.ikon.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_EDIT", cfg.getKey(), null, cfg.toString());
                list(userId, filter, request, response);
            } else if (action.equals("delete")) {
                ConfigDAO.delete(cfg.getKey());
                com.ikon.core.Config.reload(sc, new Properties());

                // Activity log
                UserActivity.log(userId, "ADMIN_CONFIG_DELETE", cfg.getKey(), null, null);
                list(userId, filter, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importConfig(userId, request, response, data, dbSession);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_CONFIG_IMPORT", null, null, null);
                list(userId, filter, 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:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

@PUT
@Path("/{id}")
@Produces(APPLICATION_JSON)//from w ww  . j  a  v a 2 s .c  om
@Consumes(APPLICATION_JSON)
public Response updateReport(@Context HttpServletRequest request, ReportDTO report,
        @DefaultValue("default") @QueryParam(value = "projection") String projection,
        @HeaderParam("scopeName") String scopeName, @HeaderParam("roleName") String roleName,
        @PathParam("id") Long id) {

    String username = request.getRemoteUser();
    log.info("{} is requesting updateReport(...), with a ID={}", username, report.getId());
    Response result;

    try {
        Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
                scopeName);
        boolean isAdmin = request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString());
        List<String> permittedServiceLayers = new ArrayList<>(ServiceLayerUtils
                .getUserPermittedLayersNames(usmService, request.getRemoteUser(), roleName, scopeName));
        ReportDTO originalReport = reportService.findById(features, report.getId(), username, scopeName,
                isAdmin, permittedServiceLayers); // we need the original report because of the 'owner/createdBy' attribute,
        // which is not contained in the JSO
        ReportFeatureEnum requiredFeature = AuthorizationCheckUtil
                .getRequiredFeatureToEditReport(originalReport, username);

        if (requiredFeature != null && !request.isUserInRole(requiredFeature.toString())) {
            result = createErrorResponse(ErrorCodes.NOT_AUTHORIZED);
        } else {
            ReportDTO update = reportService.update(report, username, originalReport.getWithMap(),
                    originalReport.getMapConfiguration());
            switch (Projection.valueOf(projection.toUpperCase())) {

            case DETAILED:
                result = createSuccessResponse(update);
                break;

            default:
                result = createSuccessResponse(update.getId());
            }
        }

    } catch (Exception exc) {
        log.error("Update failed.", exc);
        result = createErrorResponse(ErrorCodes.UPDATE_FAILED);
    }
    return result;
}

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

/**
 * This controller handles displaying the appropriate notification details for a specific record.
 * @param request : a servlet request//from   ww w  .j a v a 2 s.  c  o  m
 * @param response : a servlet response
 * @throws ServletException : an exception
 * @throws IOException : an exception
 * @return a ModelAndView object
 */
public ModelAndView displayNotificationDetail(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String view = "NotificationDetail"; // default to full view

    UserSession userSession = KRADUtils.getUserSessionFromRequest(request);
    String principalId = "";
    if (userSession != null) {
        principalId = userSession.getPrincipalId();
        if (StringUtils.isBlank(principalId)) {
            String principalName = request.getRemoteUser();
            Principal principal = KimApiServiceLocator.getIdentityService()
                    .getPrincipalByPrincipalName(principalName);
            if (principal != null) {
                principalId = principal.getPrincipalId();
            } else {
                throw new RuntimeException("There is no principal for principalName " + principalName);
            }
        }
    }

    String command = request.getParameter(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.COMMAND);
    String standaloneWindow = request
            .getParameter(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.STANDALONE_WINDOW);

    NotificationMessageDelivery messageDelivery = determineMessageFromRequest(request);
    // now get the notification from the message delivery object
    NotificationBo notification = messageDelivery.getNotification();
    boolean actionable = false;

    if (requestIsFromKEW(request)) {
        // check to see if this was a standalone window by examining the command from KEW before setting it to INLINE to force an inline view
        if (command != null && (command.equals(NotificationConstants.NOTIFICATION_DETAIL_VIEWS.NORMAL_VIEW)
                || command.equals(NotificationConstants.NOTIFICATION_DETAIL_VIEWS.DOC_SEARCH_VIEW))) {
            standaloneWindow = "true";
        }

        // we want all messages from the action list in line
        command = NotificationConstants.NOTIFICATION_DETAIL_VIEWS.INLINE;
    }

    actionable = (principalId).equals(messageDelivery.getUserRecipientId())
            && NotificationConstants.MESSAGE_DELIVERY_STATUS.DELIVERED
                    .equals(messageDelivery.getMessageDeliveryStatus());

    String documentId = request.getParameter(KewApiConstants.DOCUMENT_ID_PARAMETER);
    if (StringUtils.isNotBlank(documentId)) {
        boolean authorized = KewApiServiceLocator.getWorkflowDocumentActionsService()
                .isUserInRouteLog(documentId, principalId, false);
        LOG.debug("User in route log = " + authorized);
        if (!authorized) {
            Map<String, String> permissionDetails = new HashMap<String, String>();
            permissionDetails.put(KenApiConstants.KIMTypes.Channel.CHANNEL_ID,
                    notification.getChannel().getId().toString());
            Map<String, String> qualification = new HashMap<String, String>();
            authorized = KimApiServiceLocator.getPermissionService().isAuthorizedByTemplate(principalId,
                    KenApiConstants.Namespaces.CODE, KenApiConstants.Permissions.VIEW_NOTIFICATION,
                    permissionDetails, qualification);
            LOG.debug("User has 'View Notification' permission = " + authorized);
            if (!authorized) {
                return new ModelAndView("NotAuthorized");
            }
        }
    }

    List<NotificationSenderBo> senders = notification.getSenders();
    List<NotificationRecipientBo> recipients = notification.getRecipients();

    String contenthtml = Util.transformContent(notification);

    // check to see if the details need to be rendered in line (no stuff around them)
    if (command != null && command.equals(NotificationConstants.NOTIFICATION_DETAIL_VIEWS.INLINE)) {
        view = "NotificationDetailInline";
    }

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("notification", notification);
    model.put("senders", senders);
    model.put("recipients", recipients);
    model.put("contenthtml", contenthtml);
    model.put("messageDeliveryId", messageDelivery.getId());
    model.put("command", command);
    model.put("actionable", actionable);
    model.put(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.STANDALONE_WINDOW, standaloneWindow);
    return new ModelAndView(view, model);
}

From source file:com.netspective.sparx.security.HttpLoginManager.java

protected void registerLogin(HttpServletValueContext hsvc, MutableAuthenticatedUser user) {
    user.registerLogin(hsvc);//from  w  w w.  j a  va 2  s .  c om
    activeUsers.add(user);

    HttpServletRequest req = hsvc.getHttpRequest();
    if (log.isInfoEnabled()) {

        String userId = user.getUserId().toString();
        StringBuffer info = new StringBuffer();
        info.append("login");
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        info.append(userId);
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        info.append(req.getRemoteUser());
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        info.append(req.getRemoteHost());
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        info.append(req.getRemoteAddr());
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        BitSet perms = user.getUserPermissions();
        info.append(perms != null ? user.getUserPermissions().toString() : "{}");
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        String[] roles = user.getUserRoleNames();
        if (roles != null) {
            for (int r = 0; r < roles.length; r++) {
                if (r > 0)
                    info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
                info.append(roles[r]);
            }
        }
        log.info(info);
    }

    if (log.isDebugEnabled()) {
        String userId = user.getUserId().toString();
        log.debug("User '" + userId + "' (" + user.getUserName() + ") is now authenticated for Session ID '"
                + req.getSession().getId() + "'");

        BitSet perms = user.getUserPermissions();
        if (perms != null)
            log.debug("User '" + userId + "' has permissions " + user.getUserPermissions().toString());
        else
            log.debug("User '" + userId + " has no permissions.");

        String[] roles = user.getUserRoleNames();
        if (roles != null) {
            for (int r = 0; r < roles.length; r++)
                log.debug("User '" + userId + "' has role " + roles[r]);
        } else
            log.debug("User '" + userId + " has no roles.");
    }

    hsvc.getProject().broadcastActivity(new HttpLoginActivity(hsvc.getProject(), hsvc));
}