Example usage for javax.servlet.http HttpServletRequest getLocalAddr

List of usage examples for javax.servlet.http HttpServletRequest getLocalAddr

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getLocalAddr.

Prototype

public String getLocalAddr();

Source Link

Document

Returns the Internet Protocol (IP) address of the interface on which the request was received.

Usage

From source file:org.openmrs.web.taglib.RequireTag.java

/**
 * This is where all the magic happens. The privileges are checked and the user is redirected if
 * need be. <br>//from   w w w. j av  a2 s .  c  o  m
 * <br>
 * Returns SKIP_PAGE if the user doesn't have the privilege and SKIP_BODY if it does.
 *
 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
 * @should allow user with the privilege
 * @should allow user to have any privilege
 * @should allow user with all privileges
 * @should reject user without the privilege
 * @should reject user without any of the privileges
 * @should reject user without all of the privileges
 * @should set the right session attributes if the authenticated user misses some privileges
 * @should set the referer as the denied page url if no redirect url is specified
 */
public int doStartTag() {

    errorOccurred = false;
    HttpServletResponse httpResponse = (HttpServletResponse) pageContext.getResponse();
    HttpSession httpSession = pageContext.getSession();
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String request_ip_addr = request.getLocalAddr();
    String session_ip_addr = (String) httpSession.getAttribute(WebConstants.OPENMRS_CLIENT_IP_HTTPSESSION_ATTR);

    UserContext userContext = Context.getUserContext();

    if (userContext == null && privilege != null) {
        log.error("userContext is null. Did this pass through a filter?");
        //httpSession.removeAttribute(WebConstants.OPENMRS_CONTEXT_HTTPSESSION_ATTR);
        //TODO find correct error to throw 
        throw new APIException("context.is.null", (Object[]) null);
    }

    // Parse comma-separated list of privileges in allPrivileges and anyPrivileges attributes
    String[] allPrivilegesArray = StringUtils.commaDelimitedListToStringArray(allPrivileges);
    String[] anyPrivilegeArray = StringUtils.commaDelimitedListToStringArray(anyPrivilege);

    boolean hasPrivilege = hasPrivileges(userContext, privilege, allPrivilegesArray, anyPrivilegeArray);
    if (!hasPrivilege) {
        errorOccurred = true;
        if (userContext.isAuthenticated()) {
            httpSession.setAttribute(WebConstants.INSUFFICIENT_PRIVILEGES, true);
            if (missingPrivilegesBuffer != null) {
                httpSession.setAttribute(WebConstants.REQUIRED_PRIVILEGES, missingPrivilegesBuffer.toString());
            }

            String referer = request.getHeader("Referer");
            httpSession.setAttribute(WebConstants.REFERER_URL, referer);
            if (StringUtils.hasText(redirect)) {
                httpSession.setAttribute(WebConstants.DENIED_PAGE, redirect);
            } else if (StringUtils.hasText(referer)) {
                //This is not exactly correct all the time
                httpSession.setAttribute(WebConstants.DENIED_PAGE, referer);
            }

            log.warn("The user: '" + Context.getAuthenticatedUser() + "' has attempted to access: " + redirect
                    + " which requires privilege: " + privilege + " or one of: " + allPrivileges + " or any of "
                    + anyPrivilege);
        } else {
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "require.login");
        }
    } else if (hasPrivilege && userContext.isAuthenticated()) {
        // redirect users to password change form
        User user = userContext.getAuthenticatedUser();
        log.debug("Login redirect: " + redirect);
        if (new UserProperties(user.getUserProperties()).isSupposedToChangePassword()
                && !redirect.contains("options.form")) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.password.change");
            errorOccurred = true;
            redirect = request.getContextPath() + "/options.form#Change Login Info";
            otherwise = redirect;
            try {
                httpResponse.sendRedirect(redirect);
                return SKIP_PAGE;
            } catch (IOException e) {
                // oops, cannot redirect
                log.error("Unable to redirect for password change: " + redirect, e);
                throw new APIException(e);
            }
        }
    }

    if (differentIpAddresses(session_ip_addr, request_ip_addr)) {
        errorOccurred = true;
        // stops warning message in IE when refreshing repeatedly
        if (!"0.0.0.0".equals(request_ip_addr)) {
            log.warn("Invalid ip addr: expected " + session_ip_addr + ", but found: " + request_ip_addr);
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "require.ip_addr");
        }
    }

    log.debug("session ip addr: " + session_ip_addr);

    if (errorOccurred) {
        String url = "";
        if (redirect != null && !"".equals(redirect)) {
            url = request.getContextPath() + redirect;
        } else {
            url = request.getRequestURI();
        }

        if (request.getQueryString() != null) {
            url = url + "?" + request.getQueryString();
        }
        httpSession.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, url);
        try {
            httpResponse.sendRedirect(request.getContextPath() + otherwise);
            return SKIP_PAGE;
        } catch (IOException e) {
            // oops, cannot redirect
            throw new APIException(e);
        }
    }

    return SKIP_BODY;
}

From source file:org.openmrs.module.personalhr.web.controller.ForgotPasswordFormController.java

/**
 * This takes in the form twice. The first time when the input their username and the second
 * when they submit both their username and their secret answer
 * /*  w ww .  j  av  a  2s.  c  om*/
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String username = request.getParameter("uname");

    String ipAddress = request.getLocalAddr();
    Integer forgotPasswordAttempts = loginAttemptsByIP.get(ipAddress);
    if (forgotPasswordAttempts == null)
        forgotPasswordAttempts = 1;

    boolean lockedOut = false;

    if (forgotPasswordAttempts > 5) {
        lockedOut = true;

        Date lockedOutTime = lockoutDateByIP.get(ipAddress);
        if (lockedOutTime != null && new Date().getTime() - lockedOutTime.getTime() > 300000) {
            lockedOut = false;
            forgotPasswordAttempts = 0;
            lockoutDateByIP.put(ipAddress, null);
        } else {
            // they haven't been locked out before, or they're trying again
            // within the time limit.  Set the locked-out date to right now
            lockoutDateByIP.put(ipAddress, new Date());
        }

    }

    if (lockedOut) {
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.forgotPassword.tooManyAttempts");
    } else {
        // if the previous logic didn't determine that the user should be locked out,
        // then continue with the check

        forgotPasswordAttempts++;

        String secretAnswer = request.getParameter("secretAnswer");
        if (secretAnswer == null) {
            // if they are seeing this page for the first time

            User user = null;

            try {
                Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);

                // only search if they actually put in a username
                if (username != null && username.length() > 0)
                    user = Context.getUserService().getUserByUsername(username);
            } finally {
                Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
            }

            if (user == null || user.getSecretQuestion() == null || user.getSecretQuestion().equals("")) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.question.empty");
            } else {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "auth.question.fill");
                request.setAttribute("secretQuestion", user.getSecretQuestion());

                // reset the forgotPasswordAttempts because they have a right user.
                // they will now have 5 more chances to get the question right
                forgotPasswordAttempts = 0;
            }

        } else if (secretAnswer != null) {
            // if they've filled in the username and entered their secret answer

            User user = null;

            try {
                Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                user = Context.getUserService().getUserByUsername(username);
            } finally {
                Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
            }

            // check the secret question again in case the user got here "illegally"
            if (user == null || user.getSecretQuestion() == null || user.getSecretQuestion().equals("")) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.question.empty");
            } else if (user.getSecretQuestion() != null
                    && Context.getUserService().isSecretAnswer(user, secretAnswer)) {

                String randomPassword = "";
                for (int i = 0; i < 8; i++) {
                    randomPassword += String.valueOf((Math.random() * (127 - 48) + 48));
                }

                try {
                    Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                    Context.getUserService().changePassword(user, randomPassword);
                } finally {
                    Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                }

                httpSession.setAttribute("resetPassword", randomPassword);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.auth.password.reset");
                Context.authenticate(username, randomPassword);
                httpSession.setAttribute("loginAttempts", 0);
                return new ModelAndView(
                        new RedirectView(request.getContextPath() + "/phr/options.form#Change Login Info"));
            } else {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.answer.invalid");
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "auth.question.fill");
                request.setAttribute("secretQuestion", user.getSecretQuestion());
            }
        }
    }

    loginAttemptsByIP.put(ipAddress, forgotPasswordAttempts);
    request.setAttribute("uname", username);
    return showForm(request, response, errors);
}

From source file:org.ambraproject.action.debug.DebugInfoAction.java

@Override
public String execute() throws Exception {
    if (!checkAccess()) {
        return ERROR;
    }/*from   w ww.ja  v  a2 s . c o  m*/
    timestamp = new Date(System.currentTimeMillis());
    Runtime rt = Runtime.getRuntime();
    jvmFreeMemory = (double) rt.freeMemory() / (1024.0 * 1024.0);
    jvmTotalMemory = (double) rt.totalMemory() / (1024.0 * 1024.0);
    jvmMaxMemory = (double) rt.maxMemory() / (1024.0 * 1024.0);
    HttpServletRequest req = ServletActionContext.getRequest();
    tomcatVersion = ServletActionContext.getServletContext().getServerInfo();
    sessionCount = SessionCounter.getSessionCount();
    host = req.getLocalName();
    hostIp = req.getLocalAddr();
    buildInfo = generateBuildInfo();

    // The easiest way I found to get the URL and username for the DB.
    // It's not that easy and involves opening a connection...
    Context initialContext = new InitialContext();
    Context context = (Context) initialContext.lookup("java:comp/env");
    DataSource ds = (DataSource) context.lookup("jdbc/AmbraDS");
    Connection conn = null;
    try {
        conn = ds.getConnection();
        DatabaseMetaData metadata = conn.getMetaData();
        dbUrl = metadata.getURL();
        dbUser = metadata.getUserName();
    } finally {
        conn.close();
    }

    Configuration config = ConfigurationStore.getInstance().getConfiguration();
    FileStoreService filestoreService = (FileStoreService) context.lookup("ambra/FileStore");
    filestore = filestoreService.toString();
    solrUrl = (String) config.getProperty("ambra.services.search.server.url");
    configuration = dumpConfig(config);
    cmdLine = IOUtils.toString(new FileInputStream("/proc/self/cmdline"));

    return SUCCESS;
}

From source file:com.betel.flowers.web.bean.StockVentasBean.java

private void generatedBarcode() {
    if (this.stockVentas != null && !this.stockVentas.isEmpty()) {
        int size = this.stockVentas.size();
        int length = this.stockVentasG.size();
        String code = RandomStringUtils.randomNumeric(2);
        String barcode = "BETEL-SV" + code + "" + size + "" + length;
        String url = "/var/www/html/mail/" + barcode + "/";
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();//from   w  w w . j ava  2  s  .  c  om
        String ipAdress = request.getLocalAddr();
        String filepath = "http://" + ipAdress + "/mail/" + barcode + "/" + barcode + ".pdf";
        for (int i = 0; i < size; i++) {
            Integer total = this.stockVentas.get(i).getTotalTallos();
            this.stockVentas.get(i).setTotalTallos(total);
            this.stockVentas.get(i).setBarcode(barcode);
            this.stockVentas.get(i).setMessage(this.message);
            this.stockVentas.get(i).setXml(url + barcode + ".xml");
            this.stockVentas.get(i).setHtml(url + barcode + ".html");
            this.stockVentas.get(i).setPdf(url + barcode + ".pdf");
            this.stockVentas.get(i).setUrlPdf(filepath);
        }
        this.mailStockVentaXML.generatedXML(barcode, url, barcode, this.message, this.stockVentas);
        GeneratedPDF runPDF = new GeneratedPDF(url, url + barcode + ".xml", url + barcode + ".html",
                url + barcode + ".pdf", barcode, 1);
        runPDF.run();
        Boolean exito = runPDF.getExito();
        if (exito) {
            FacesUtil.addMessageInfo("Se ha generado con exito.");
        }
    }
}

From source file:org.eclipse.orion.server.authentication.formpersona.PersonaHelper.java

/**
 * If the request appears to be from a loopback interface, returns an audience constructed from the server name.
 * Otherwise returns null.// w  ww .ja va 2s  .  com
 */
private String getLoopbackAudience(HttpServletRequest req) throws PersonaException {
    try {
        String serverName = req.getServerName();
        try {
            // First ensure the request is coming from the IP of a loopback device
            if (isLoopback(InetAddress.getByName(req.getLocalAddr()))) {
                // Verify that the server name resolves to a loopback device, to prevent spoofing/proxying
                InetAddress addr = InetAddress.getByName(serverName);
                if (isLoopback(addr))
                    return new URI(req.getScheme(), req.getRemoteUser(), serverName, req.getServerPort(), null,
                            null, null).toString();
            }
        } catch (UnknownHostException e) {
            // Bogus serverName, ignore
        }
    } catch (URISyntaxException e) {
        throw new PersonaException(e);
    }
    return null;
}

From source file:com.betel.flowers.web.bean.RegistroExportacionBean.java

private void generatedBarcode() {
    if (this.registrosExportacion != null && !this.registrosExportacion.isEmpty()) {
        int size = this.registrosExportacion.size();
        int length = this.registrosExportacionG.size();
        String code = RandomStringUtils.randomNumeric(2);
        String barcode = "BETEL-RE" + code + "" + size + "" + length;
        String url = "/var/www/html/pdf/" + barcode + "/";
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();//from   ww  w.  j av a  2 s.  com
        String ipAdress = request.getLocalAddr();
        String filepath = "http://" + ipAdress + "/pdf/" + barcode + "/" + barcode + ".pdf";
        for (int i = 0; i < size; i++) {
            Integer total = this.registrosExportacion.get(i).getTotalTallos();
            this.registrosExportacion.get(i).setTotalTallos(total);
            this.registrosExportacion.get(i).setStock(total);
            this.registrosExportacion.get(i).setBarcode(barcode);
            this.registrosExportacion.get(i).setXml(url + barcode + ".xml");
            this.registrosExportacion.get(i).setHtml(url + barcode + ".html");
            this.registrosExportacion.get(i).setPdf(url + barcode + ".pdf");
            this.registrosExportacion.get(i).setUrlPdf(filepath);
        }
        if (this.rendiminetoServiceList.getRendimientos() != null
                && !this.rendiminetoServiceList.getRendimientos().isEmpty()) {
            for (int j = 0; j < this.rendiminetoServiceList.getRendimientos().size(); j++) {
                this.rendiminetoServiceList.getRendimientos().get(j).setBarcode(barcode);
            }
        }
        this.etiquetaRegExpoXML.generatedXML(barcode, url, barcode, this.registrosExportacion);
        GeneratedPDF runPDF = new GeneratedPDF(url, url + barcode + ".xml", url + barcode + ".html",
                url + barcode + ".pdf", barcode, 0);
        runPDF.run();
        Boolean exito = runPDF.getExito();
        if (exito) {
            FacesUtil.addMessageInfo("Se ha genarado con exito.");
        }
    }
}

From source file:com.trsst.ui.AppServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // FLAG: limit access only to local clients
    if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed.");
        return;//from  www  .j a va 2 s .c  om
    }

    // in case of any posted files
    InputStream inStream = null;

    // determine if supported command: pull, push, post
    String path = request.getPathInfo();
    System.err.println(new Date().toString() + " " + path);
    if (path != null) {
        // FLAG: limit only to pull and post
        if (path.startsWith("/pull/") || path.startsWith("/post")) {
            // FLAG: we're sending the user's keystore
            // password over the wire (over SSL)
            List<String> args = new LinkedList<String>();
            if (path.startsWith("/pull/")) {
                path = path.substring("/pull/".length());
                response.setContentType("application/atom+xml; type=feed; charset=utf-8");
                // System.out.println("doPull: " +
                // request.getParameterMap());
                args.add("pull");
                if (request.getParameterMap().size() > 0) {
                    boolean first = true;
                    for (Object name : request.getParameterMap().keySet()) {
                        // FLAG: don't allow "home" (server-abuse)
                        // FLAG: don't allow "attach" (file-system access)
                        if ("decrypt".equals(name) || "pass".equals(name)) {
                            for (String value : request.getParameterValues(name.toString())) {
                                args.add("--" + name.toString());
                                args.add(value);
                            }
                        } else {
                            for (String value : request.getParameterValues(name.toString())) {
                                if (first) {
                                    path = path + '?';
                                    first = false;
                                } else {
                                    path = path + '&';
                                }
                                path = path + name + '=' + value;
                            }
                        }
                    }
                }
                args.add(path);

            } else if (path.startsWith("/post")) {
                // System.out.println("doPost: " +
                // request.getParameterMap());
                args.add("post");

                try { // h/t http://stackoverflow.com/questions/2422468
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // process regular form field
                            String name = item.getFieldName();
                            String value = item.getString("UTF-8").trim();
                            // System.out.println("AppServlet: " + name
                            // + " : " + value);
                            if (value.length() > 0) {
                                // FLAG: don't allow "home" (server-abuse)
                                // FLAG: don't allow "attach" (file-system
                                // access)
                                if ("id".equals(name)) {
                                    if (value.startsWith("urn:feed:")) {
                                        value = value.substring("urn:feed:".length());
                                    }
                                    args.add(value);
                                } else if (!"home".equals(name) && !"attach".equals(name)) {
                                    args.add("--" + name);
                                    args.add(value);
                                }
                            } else {
                                log.debug("Empty form value for name: " + name);
                            }
                        } else if (item.getSize() > 0) {
                            // process form file field (input type="file").
                            // String filename = FilenameUtils.getName(item
                            // .getName());
                            if (item.getSize() > 1024 * 1024 * 10) {
                                throw new FileUploadException("Current maximum upload size is 10MB");
                            }
                            String name = item.getFieldName();
                            if ("icon".equals(name) || "logo".equals(name)) {
                                args.add("--" + name);
                                args.add("-");
                            }
                            inStream = item.getInputStream();
                            // NOTE: only handles one file!
                        } else {
                            log.debug("Ignored form field: " + item.getFieldName());
                        }
                    }
                } catch (FileUploadException e) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Could not parse multipart request: " + e);
                    return;
                }
            }

            // send post data if any to command input stream
            if (inStream != null) {
                args.add("--attach");
            }
            //System.out.println(args);

            // make sure we don't create another local server
            args.add("--host");
            args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/feed");

            PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8");
            int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream);
            if (result != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal error code: " + result);
            } else {
                outStream.flush();
            }
            return;
        }

        // otherwise: determine if static resource request
        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        byte[] result = resources.get(path);
        String mimetype = null;
        if (result == null) {
            // if ("".equals(path) || path.endsWith(".html")) {
            // treat all html requests with index doc
            result = resources.get("index.html");
            mimetype = "text/html";
            // }
        }
        if (result != null) {
            if (mimetype == null) {
                if (path.endsWith(".html")) {
                    mimetype = "text/html";
                } else if (path.endsWith(".css")) {
                    mimetype = "text/css";
                } else if (path.endsWith(".js")) {
                    mimetype = "application/javascript";
                } else if (path.endsWith(".png")) {
                    mimetype = "image/png";
                } else if (path.endsWith(".jpg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".jpeg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".gif")) {
                    mimetype = "image/gif";
                } else {
                    mimetype = new Tika().detect(result);
                }
            }
            if (request.getHeader("If-None-Match:") != null) {
                // client should always use cached version
                log.info("sending 304");
                response.setStatus(304); // Not Modified
                return;
            }
            // otherwise allow ETag/If-None-Match
            response.setHeader("ETag", Long.toHexString(path.hashCode()));
            if (mimetype != null) {
                response.setContentType(mimetype);
            }
            response.setContentLength(result.length);
            response.getOutputStream().write(result);
            return;
        }

    }

    // // otherwise: 404 Not Found
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:com.jd.survey.web.settings.GlobalSettingsController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid GlobalSettings globalSettings, BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");

    try {//from   w  ww .j a v a2 s .  co m
        User user = userService.user_findByLogin(principal.getName());

        if (!user.isAdmin()) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, globalSettings, user);
                return "settings/globalSettings/update";
            }
            uiModel.asMap().clear();
            globalSettings = applicationSettingsService.globalSettings_merge(globalSettings);
            return "redirect:/settings/globalSettings/"
                    + encodeUrlPathSegment(globalSettings.getId().toString(), httpServletRequest);
        } else {
            return "redirect:/settings/globalSettings/"
                    + encodeUrlPathSegment(globalSettings.getId().toString(), httpServletRequest);
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.openmrs.module.personalhr.web.taglib.RequireTag.java

/**
 * This is where all the magic happens. The privileges are checked and the user is redirected if
 * need be. <br/>/* ww w . j  a va  2 s. c om*/
 * <br/>
 * Returns SKIP_PAGE if the user doesn't have the privilege and SKIP_BODY if it does.
 * 
 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
 * @should allow user with the privilege
 * @should allow user to have any privilege
 * @should allow user with all privileges
 * @should reject user without the privilege
 * @should reject user without any of the privileges
 * @should reject user without all of the privileges
 */
@Override
public int doStartTag() {
    this.log.debug("PHR RequireTag started...");

    this.errorOccurred = false;
    final HttpServletResponse httpResponse = (HttpServletResponse) this.pageContext.getResponse();
    final HttpSession httpSession = this.pageContext.getSession();
    final HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
    final String request_ip_addr = request.getLocalAddr();
    final String session_ip_addr = (String) httpSession
            .getAttribute(WebConstants.OPENMRS_CLIENT_IP_HTTPSESSION_ATTR);

    final UserContext userContext = Context.getUserContext();

    if ((userContext == null) && (this.privilege != null)) {
        this.log.error("userContext is null. Did this pass through a filter?");
        //httpSession.removeAttribute(WebConstants.OPENMRS_CONTEXT_HTTPSESSION_ATTR);
        //TODO find correct error to throw 
        throw new APIException("The context is currently null.  Please try reloading the site.");
    }

    final User user = userContext.getAuthenticatedUser();

    Integer patientId = PersonalhrUtil.getInteger(this.pageContext.getAttribute("patientId"));
    if (patientId == null) {
        patientId = PersonalhrUtil.getInteger(this.pageContext.getRequest().getAttribute("patientId"));
    }
    if (patientId == null) {
        patientId = PersonalhrUtil.getInteger(this.pageContext.getRequest().getParameter("patientId"));
    }

    Integer personId = PersonalhrUtil.getInteger(this.pageContext.getAttribute("personId"));
    if (personId == null) {
        personId = PersonalhrUtil.getInteger(this.pageContext.getRequest().getAttribute("personId"));
    }
    if (personId == null) {
        personId = PersonalhrUtil.getInteger(this.pageContext.getRequest().getParameter("personId"));
    }

    this.log.debug("Checking user " + user + " for privs " + this.privilege + " on personId|patientId "
            + personId + "|" + patientId);

    final Patient pat = patientId == null ? null : Context.getPatientService().getPatient(patientId);

    final Person per = personId == null ? null : Context.getPersonService().getPerson(personId);

    if (per != null) {
        this.log.debug("Checking user " + user + " for privs " + this.privilege + " on person " + per);
    }

    if (pat != null) {
        this.log.debug("Checking user " + user + " for privs " + this.privilege + " on patient " + pat);
    }

    if ((per == null) && (pat == null)) {
        this.log.debug("Checking user " + user + " for privs " + this.privilege);
    }

    this.log.debug("Checking user " + user + " for privs|role " + this.privilege + "|" + this.role
            + " on person|patient " + per + "|" + pat);

    // Parse comma-separated list of privileges in allPrivileges and anyPrivileges attributes
    final String[] allPrivilegesArray = StringUtils.commaDelimitedListToStringArray(this.allPrivileges);
    final String[] anyPrivilegeArray = StringUtils.commaDelimitedListToStringArray(this.anyPrivilege);

    boolean hasPrivilege = hasPrivileges(user, per, pat, this.privilege, allPrivilegesArray, anyPrivilegeArray);
    if ((hasPrivilege || this.privilege == null) && (this.role != null && !this.role.trim().isEmpty())) {
        hasPrivilege = user.hasRole(role);
    }

    if (!hasPrivilege) {
        this.errorOccurred = true;
        if (userContext.isAuthenticated()) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "require.unauthorized");
            this.log.warn("The user: '" + Context.getAuthenticatedUser() + "' has attempted to access: "
                    + this.redirect + " which requires privilege: " + this.privilege + " or one of: "
                    + this.allPrivileges + " or any of " + this.anyPrivilege);
        } else {
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "require.login");
        }
    } else if (hasPrivilege && userContext.isAuthenticated()) {
        // redirect users to password change form
        this.log.debug("Login redirect: " + this.redirect);
        if (new UserProperties(user.getUserProperties()).isSupposedToChangePassword()
                && !this.redirect.contains("options.form")) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.password.change");
            this.errorOccurred = true;
            this.redirect = request.getContextPath() + "/options.form#Change Login Info";
            this.otherwise = this.redirect;
            try {
                httpResponse.sendRedirect(this.redirect);
                return SKIP_PAGE;
            } catch (final IOException e) {
                // oops, cannot redirect
                this.log.error("Unable to redirect for password change: " + this.redirect, e);
                throw new APIException(e);
            }
        }
    }

    if (differentIpAddresses(session_ip_addr, request_ip_addr)) {
        this.errorOccurred = true;
        // stops warning message in IE when refreshing repeatedly
        if ("0.0.0.0".equals(request_ip_addr) == false) {
            this.log.warn("Invalid ip addr: expected " + session_ip_addr + ", but found: " + request_ip_addr);
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "require.ip_addr");
        }
    }

    this.log.debug("session ip addr: " + session_ip_addr);

    if (this.errorOccurred) {

        String url = "";
        if ((this.redirect != null) && !this.redirect.equals("")) {
            url = request.getContextPath() + this.redirect;
        } else {
            url = request.getRequestURI();
        }

        if (request.getQueryString() != null) {
            url = url + "?" + request.getQueryString();
        }
        httpSession.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, url);
        try {
            httpResponse.sendRedirect(request.getContextPath() + this.otherwise);
            return SKIP_PAGE;
        } catch (final IOException e) {
            // oops, cannot redirect
            throw new APIException(e);
        }
    }

    return SKIP_BODY;
}

From source file:org.cloudifysource.rest.command.CommandManager.java

/**
 * Constructor takes as input the entire commands URI, held in the request
 * and the root object from which to begin invocation.
 * @param request - the commands request 
 * @param root - the root command's object
 */// w w w  .j  a v  a2  s  . c  o m
public CommandManager(HttpServletRequest request, Object root) {
    final String prefix = "/admin/";
    String executionPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    if (executionPath.endsWith("/")) {
        executionPath = executionPath.substring(0, executionPath.length() - 1);
    }
    if (!executionPath.startsWith(prefix)) {
        throw new IllegalArgumentException("Bad request URL " + request.getRequestURL());
    }
    String restUrl = "http://" + request.getLocalAddr() + ":" + request.getLocalPort()
            + request.getContextPath();
    this.commandURL = restUrl + executionPath;
    initilizeCommandList(executionPath.substring(prefix.length()), root);
}