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.jivesoftware.os.upena.deployable.UpenaEndpoints.java

@GET
@Path("/")
@Produces(MediaType.TEXT_HTML)/*from w w w . ja va 2 s . c  o m*/
public Response get(@Context HttpServletRequest httpRequest, @Context UriInfo uriInfo) {

    String rendered = soyService.render(httpRequest.getRemoteUser(),
            uriInfo.getAbsolutePath() + "propagator/download", amzaClusterName.name);
    return Response.ok(rendered).build();
}

From source file:org.apache.hadoop.chukwa.rest.resource.ViewResource.java

@POST
public ReturnCodeBean changeView(@Context HttpServletRequest request, @FormParam("owner") String owner,
        @FormParam("view_vid") String oldVid, @FormParam("view_name") String name) {
    try {//  w w  w  .j a  v a  2  s  .  c o  m
        ViewStore vs;
        if (oldVid != null) {
            vs = new ViewStore(owner, oldVid);
        } else {
            vs = new ViewStore(null, "default");
        }
        ViewBean view = vs.get();
        view.setOwner(request.getRemoteUser());
        view.setName(name);
        view.setDescription(name);
        if (oldVid == null) {
            view.setPermissionType("private");
        }
        vs = new ViewStore(request.getRemoteUser(), name);
        vs.set(view);
    } catch (Exception e) {
        log.error(ExceptionUtil.getStackTrace(e));
        throw new WebApplicationException(
                Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("View save failed.").build());
    }
    return new ReturnCodeBean(ReturnCodeBean.SUCCESS, "Saved");
}

From source file:org.openhab.io.rest.internal.resources.ContextResource.java

@GET
@Path("/{scriptfile: [a-zA-Z_0-9]*}/{arg1: [a-zA-Z_0-9]*}/{arg2: [a-zA-Z_0-9]*}")
@Produces({ MediaType.WILDCARD })//ww w  .  j  av  a  2s  .  c  o m
public Response callShellScriptAndSendReturnValue(@PathParam("scriptfile") String scriptFile,
        @PathParam("arg1") @DefaultValue("0") String Arg1, @PathParam("arg2") @DefaultValue("0") String Arg2,
        @QueryParam("que1") @DefaultValue("0") String Que1, @QueryParam("que2") @DefaultValue("0") String Que2,
        @QueryParam("type") @DefaultValue("0") String Type, @CookieParam("uid") @DefaultValue("0") String UID,
        @HeaderParam("If-None-Match") @DefaultValue("0") String INM,
        @HeaderParam("Timeout") @DefaultValue("10000") Integer TimeOut, @Context HttpServletRequest request) {
    //logger.info("FYI: ContextResource - HeaderParam 'Timeout':" +TimeOut);

    if (Type.equals(""))
        Type = "0";
    final String responseType = getResponseMediaType(Type);

    String uid = "0";
    if (request.getRemoteUser() != null)
        uid = request.getRemoteUser();
    else
        uid = UID;

    if (INM.equals("0"))
        INM = "0";

    if (Arg1.equals(""))
        Arg1 = "0";
    if (Arg2.equals(""))
        Arg2 = "0";

    if (Que1.equals(""))
        Que1 = "0";
    if (Que2.equals(""))
        Que2 = "0";

    if (TimeOut.equals(""))
        TimeOut = 10000;
    else
        TimeOut = TimeOut - 500;

    //file extention according to Op.Sys.
    String ext = "sh";
    if (SystemUtils.IS_OS_WINDOWS)
        ext = "bat";

    String md5Hash = null;

    if (scriptFile.equals(""))
        scriptFile = "0";
    String fileName = scriptFile + ".GET." + ext;
    File f = new File("contexts/" + fileName);

    //check if scriptfile exists
    if (f.exists() && !f.isDirectory()) {

        String command = "contexts/" + fileName + " " + uid + " " + Arg1 + " " + Arg2 + " " + Que1 + " " + Que2
                + " " + Type;
        //logger.info("FYI: ContextResource - Command To Execute: "+command);
        String result = Exec.executeCommandLine(command, TimeOut);

        md5Hash = md5(result);
        //logger.info("FYI: ContextResource request '{}' md5 hash is: '{}'", uriInfo.getAbsolutePath(), md5Hash);
        EntityTag resultETag = new EntityTag(md5Hash);

        if (resultETag.toString().equals(INM))
            return Response.notModified(resultETag).tag(resultETag).build();
        else
            return Response.ok(result, responseType).tag(resultETag).build();
    } else {
        logger.info("FYI:  ContextResource request at '{}' was for scriptFile '{}' that does not exist",
                uriInfo.getPath(), fileName);
        return Response.status(404).build();
    }
}

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

/**
 * View action that displays an approve/disapprove/acknowledge view
 * @param request the HttpServletRequest
 * @param response the HttpServletResponse
 * @param command the command object bound for this MultiActionController
 * @return a view ModelAndView/*from ww w  .  j  ava 2 s.c  o m*/
 */
public ModelAndView view(HttpServletRequest request, HttpServletResponse response,
        AdministerNotificationRequestCommand command) {
    // obtain a workflow user object first
    String initiatorId = request.getRemoteUser();

    // now construct the workflow document, which will interact with workflow
    if (command.getDocId() == null) {
        throw new RuntimeException("An invalid document ID was recieved from KEW's action list.");
    }

    //check to see which view is being passed to us from the notification list - pop up or inline
    String view = request.getParameter(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.COMMAND);
    String standaloneWindow = "true";
    if (view != null && view.equals(NotificationConstants.NOTIFICATION_DETAIL_VIEWS.INLINE)) {
        standaloneWindow = "false";
    }

    WorkflowDocument document;
    Map<String, Object> model = new HashMap<String, Object>();
    // set into model whether we are dealing with a pop up or an inline window
    model.put(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.STANDALONE_WINDOW, standaloneWindow);
    try {
        document = NotificationWorkflowDocument.loadNotificationDocument(initiatorId, command.getDocId());

        NotificationBo notification = retrieveNotificationForWorkflowDocument(document);

        // set up model
        command.setDocument(document);
        command.setNotification(notification);
        // render the event content according to registered XSLT stylesheet
        command.setRenderedContent(Util.transformContent(notification));

        LOG.info("notification auto remove date time: " + notification.getAutoRemoveDateTime());
        if (document.isApproved()) {
            command.setValid(false);
            command.setMessage("This notification request has been approved.");
        } else if (document.isDisapproved()) {
            command.setMessage("This notification request has been disapproved.");
        } else if (notification.getAutoRemoveDateTime() != null
                && notification.getAutoRemoveDateTimeValue().before(new Date(System.currentTimeMillis()))) {
            /*if (!document.stateIsCanceled()) {
            workflowDocumentService.terminateWorkflowDocument(new WorkflowDocument(new NetworkIdVO("notsys"), new Long(command.getDocId())));
            }*/
            // the autoremove date time has already passed...this notification request is null and void at this time
            boolean disapproved = document.isDisapproved();
            if (!document.isDisapproved()) {
                List<NotificationChannelReviewerBo> reviewers = notification.getChannel().getReviewers();
                String user = null;
                for (NotificationChannelReviewerBo reviewer : reviewers) {
                    if (KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.equals(reviewer.getReviewerType())) {
                        if (reviewer.getReviewerId().equals(request.getRemoteUser())) {
                            user = request.getRemoteUser();
                        }
                    } else if (KimGroupMemberTypes.GROUP_MEMBER_TYPE.equals(reviewer.getReviewerType())) {
                        // if it's a group
                        String[] members = recipientService.getGroupMembers(reviewer.getReviewerId());
                        for (String member : members) {
                            if (StringUtils.equals(member, request.getRemoteUser())) {
                                user = request.getRemoteUser();
                                break;
                            }
                        }
                    }
                }
                // if the current user is a reviewer, then disapprove as that user
                if (user != null) {
                    WorkflowDocumentFactory.loadDocument(user, command.getDocId()).disapprove(
                            "Disapproving notification request.  Auto-remove datetime has already passed.");
                    disapproved = true;
                }
            }
            command.setValid(false);
            if (disapproved) {
                command.setMessage(
                        "This notification request is no longer valid because the Auto-Remove date has already passed.  It has been disapproved.  Please refresh your action list.");
            } else {
                command.setMessage(
                        "This notification request is no longer valid because the Auto-Remove date has already passed.");
            }
        }

        model.put(getCommandName(command), command);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return new ModelAndView("ViewNotificationRequestDetails", model);
}

From source file:com.idega.slide.authentication.IWSlideAuthenticator.java

private void generateUserFolders(HttpServletRequest request)
        throws HttpException, RemoteException, IOException {
    IWApplicationContext iwac = getIWMainApplication(request).getIWApplicationContext();
    IWSlideService slideService = IBOLookup.getServiceInstance(iwac, IWSlideService.class);
    slideService.generateUserFolders(request.getRemoteUser());
}

From source file:de.fhg.fokus.openride.services.favoritepoint.FavoritePointService.java

@POST
@Produces("text/json")
public Response postFavoritePoint(@Context HttpServletRequest con, @PathParam("username") String username,
        String json) {//w  w w .jav  a2  s  . c  o  m

    System.out.println("postFavoritePoint 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 FavoritePointRequest());

        XStream x = Utils.getJasonXStreamer(list);

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

        Integer favptId = favoritePointControllerBean.addFavoritePoint(r.getFavptAddress(),
                r.getFavptGeoCoords(), r.getFavptDisplayName(), c);

        if (favptId != -1) {
            // Favpt has been added successfully
            return Response.created(UriBuilder.fromPath("{displayName}").build(r.getFavptDisplayName()))
                    .build();
        } else {
            // Could not add favpt - displayName not unique?
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

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

}

From source file:io.adeptj.runtime.servlet.ToolsServlet.java

/**
 * Renders tools page.// w  ww. j  ava 2s . co  m
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    Bundle[] bundles = BundleContextHolder.getInstance().getBundleContext().getBundles();
    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    TemplateEngines.getDefault().render(TemplateContext.builder().request(req).response(resp)
            .template(TOOLS_TEMPLATE).locale(req.getLocale())
            .contextObject(ContextObject.newContextObject().put("username", req.getRemoteUser())
                    .put("sysProps", System.getProperties().entrySet()).put("totalBundles", bundles.length)
                    .put("bundles", bundles)
                    .put("runtime", JAVA_RUNTIME_NAME + "(build " + JAVA_RUNTIME_VERSION + ")")
                    .put("jvm", JAVA_VM_NAME + "(build " + JAVA_VM_VERSION + ", " + JAVA_VM_INFO + ")")
                    .put("startTime", Date.from(Instant.ofEpochMilli(startTime)))
                    .put("upTime", Times.format(startTime))
                    .put("maxMemory",
                            FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getMax()))
                    .put("usedMemory",
                            FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getUsed()))
                    .put("processors", Runtime.getRuntime().availableProcessors()))
            .build());
}

From source file:com.ikon.servlet.admin.MimeTypeServlet.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);/* w w w.j a  v a  2s . co  m*/

    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("export")) {
            export(userId, request, response);
        } else {
            list(userId, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.ikon.servlet.admin.ReportServlet.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 .  j  ava  2 s.  c  o  m*/

    try {
        if (action.equals("create")) {
            ServletContext sc = getServletContext();
            Report rp = new Report();
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("edit")) {
            ServletContext sc = getServletContext();
            int rpId = WebUtils.getInt(request, "rp_id");
            Report rp = ReportDAO.findByPk(rpId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("delete")) {
            ServletContext sc = getServletContext();
            int rpId = WebUtils.getInt(request, "rp_id");
            Report rp = ReportDAO.findByPk(rpId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("paramList")) {
            paramList(userId, request, response);
        } else if (action.equals("getParams")) {
            getParams(userId, request, response);
        } else if (action.equals("execute")) {
            execute(userId, request, response);
        } else {
            list(userId, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (JRException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (EvalError e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (ParseException 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:gov.nih.nci.ncicb.cadsr.common.struts.common.BaseDispatchAction.java

/**
 * Sets default method name if no method is specified
 *
 * @return ActionForward/*w  ww .  j av a  2  s .  c o m*/
 *
 * @throws Exception
 */
protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String name) throws Exception {
    if ((name == null) || name.equals("")) {
        name = DEFAULT_METHOD;
    }

    try {
        return super.dispatchMethod(mapping, form, request, response, name);
    } catch (Throwable throwable) {
        HttpSession session = request.getSession();
        String userName = request.getRemoteUser();
        if (userName == null)
            userName = "";
        Collection keys = (Collection) session.getAttribute(this.CLEAR_SESSION_KEYS);
        if (keys != null) {
            Iterator it = keys.iterator();
            while (it.hasNext()) {
                session.removeAttribute((String) it.next());
            }
        }
        if (log.isFatalEnabled()) {
            log.fatal(userName + ": Exception in dispatchMethod in method " + name, throwable);
        }
        saveMessage(ERROR_FATAL, request);
        throw new FatalException(throwable);
    }
}