Example usage for javax.servlet.http HttpServletRequest getRemoteHost

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

Introduction

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

Prototype

public String getRemoteHost();

Source Link

Document

Returns the fully qualified name of the client or the last proxy that sent the request.

Usage

From source file:org.ngrinder.script.controller.SvnDavController.java

@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());//from w w  w.j  a v a 2  s .c om
}

From source file:org.ngrinder.script.controller.DavSvnController.java

private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());/*from   w w w  .j a  v a2s .co m*/
}

From source file:org.openiam.webadmin.res.AttributeMapController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    log.info("onSubmit called");

    AttributeMapCommand attrMapCmd = (AttributeMapCommand) command;
    String resId = attrMapCmd.getResId();

    String userId = (String) request.getSession().getAttribute("userId");
    String domainId = (String) request.getSession().getAttribute("domainid");
    String login = (String) request.getSession().getAttribute("login");

    Resource res = resourceDataService.getResource(resId);

    //ManagedSys sys;

    String btn = request.getParameter("btn");
    if (btn.equalsIgnoreCase("Delete")) {
        List<AttributeMap> attrMap = attrMapCmd.getAttrMapList();
        if (attrMap != null) {

            for (AttributeMap a : attrMap) {
                if (a.getSelected()) {
                    String mapId = a.getAttributeMapId();
                    if (!mapId.equalsIgnoreCase("NEW")) {
                        this.managedSysService.removeAttributeMap(mapId);

                        auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE",
                                resId, null, "SUCCESS", null, "DELETE POLICY-MAP", a.getAttributeName(), null,
                                null, res.getName(), request.getRemoteHost());
                    }// ww w .  j  av a2s . c  om
                }
            }

        }
    } else {

        List<AttributeMap> attrMap = attrMapCmd.getAttrMapList();

        if (attrMap != null) {

            for (AttributeMap a : attrMap) {
                if (a.getAttributeMapId() == null || a.getAttributeMapId().equalsIgnoreCase("NEW")) {
                    // new
                    if (a.getAttributePolicy().getPolicyId() != null
                            && a.getAttributePolicy().getPolicyId().length() > 0) {
                        a.setAttributeMapId(null);
                        a.setResourceId(resId);
                        a.setManagedSysId(attrMapCmd.getManagedSysId());
                        this.managedSysService.addAttributeMap(a);

                        auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE",
                                resId, null, "SUCCESS", null, "ADD POLICY-MAP", a.getAttributeName(), null,
                                null, res.getName(), request.getRemoteHost());

                    }
                } else {
                    // update
                    a.setResourceId(resId);
                    managedSysService.updateAttributeMap(a);

                    auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE", resId,
                            null, "SUCCESS", null, "MODIFY POLICY-MAP", a.getAttributeName(), null, null,
                            res.getName(), request.getRemoteHost());

                }
            }

        }
    }
    log.info("refreshing attr list for resourceId=" + resId);
    String view = redirectView + "&menuid=RESPOLICYMAP&menugrp=SECURITY_RES&objId=" + resId;
    log.info("redirecting to=" + view);

    return new ModelAndView(new RedirectView(view, true));

}

From source file:org.atricore.idbus.kernel.main.mediation.camel.component.http.IDBusHttpBinding.java

@Override
public void readRequest(HttpServletRequest httpServletRequest, HttpMessage httpMessage) {

    if (logger.isTraceEnabled())
        logger.trace("Reading HTTP Servlet Request");

    super.readRequest(httpServletRequest, httpMessage);

    if (httpServletRequest.getCookies() != null) {
        for (Cookie cookie : httpServletRequest.getCookies()) {

            if (logger.isDebugEnabled())
                logger.debug("Setting IDBus Cookie header for " + cookie.getName() + "=" + cookie.getValue());

            httpMessage.getHeaders().put("org.atricore.idbus.http.Cookie." + cookie.getName(),
                    cookie.getValue());//w  w  w. j  a v a2  s  .  c  o m
        }
    }

    // Export additional information in CAMEL headers
    httpMessage.getHeaders().put("org.atricore.idbus.http.RequestURL",
            httpServletRequest.getRequestURL().toString());
    httpMessage.getHeaders().put("org.atricore.idbus.http.QueryString", httpServletRequest.getQueryString());

    String remoteAddr = null;
    String remoteHost = null;

    if (httpServletRequest.getAttribute("org.atricore.idbus.http.SecureCookies") != null)
        httpMessage.getHeaders().put("org.atricore.idbus.http.SecureCookies",
                httpServletRequest.getAttribute("org.atricore.idbus.http.SecureCookies"));

    String parentThread = httpServletRequest.getHeader(IDBusHttpConstants.HTTP_HEADER_IDBUS_PROXIED_REQUEST);
    if (parentThread == null) {
        remoteAddr = httpServletRequest.getRemoteAddr();
        remoteHost = httpServletRequest.getRemoteHost();
        if (logger.isTraceEnabled())
            logger.trace("Using request remote address/host : [" + remoteAddr + "/" + remoteHost + "]");
    } else {
        remoteAddr = httpServletRequest.getHeader(IDBusHttpConstants.HTTP_HEADER_IDBUS_REMOTE_ADDRESS);
        remoteHost = httpServletRequest.getHeader(IDBusHttpConstants.HTTP_HEADER_IDBUS_REMOTE_HOST);
        if (logger.isTraceEnabled())
            logger.trace("Using X-IdBus header remote address/host : [" + remoteAddr + "/" + remoteHost + "]");
    }

    httpMessage.getHeaders().put("org.atricore.idbus.http.RemoteAddress", remoteAddr);
    httpMessage.getHeaders().put("org.atricore.idbus.http.RemoteHost", remoteHost);

    if (logger.isDebugEnabled())
        logger.debug("Publishing HTTP Session as Camel header org.atricore.idbus.http.HttpSession");

    httpMessage.getHeaders().put("org.atricore.idbus.http.HttpSession", httpServletRequest.getSession(true));
}

From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // explicitly set character encoding
    req.setCharacterEncoding("UTF-8");
    res.setCharacterEncoding("UTF-8");

    SimpleCredentials creds = BasicAuth.parseAuthorizationHeader(req);
    String credentialsId = creds.getUserID();
    log.debug("credentialsId={}", credentialsId);

    String jcrUserId = req.getParameter("jcrUserId");
    String jcrPath = req.getParameter("jcrPath");
    log.info("jcrUserId={}, jcrPath={}", jcrUserId, jcrPath);

    Session jcrSession = null;//from   w w w .  j  a  v a 2  s  . com
    Session impersonateSession = null;
    Map<String, Object> templateParams = new HashMap<String, Object>();

    try {
        if (creds.getUserID() == null || creds.getUserID().length() == 0) {
            jcrSession = repository.login();
        } else {
            jcrSession = repository.login(creds);
        }
        log.debug("jcrSession={}", jcrSession);
        User user = ((HippoSession) jcrSession).getUser();

        if (user.isSystemUser()) {
            final InetAddress address = InetAddress.getByName(req.getRemoteHost());
            if (!address.isAnyLocalAddress() && !address.isLoopbackAddress()) {
                throw new LoginException();
            }
        }

        templateParams.put("jcrSession", jcrSession);
        templateParams.put("jcrUserId", jcrUserId);
        templateParams.put("jcrPath", jcrPath);

        Credentials impersonateCredentials = new SimpleCredentials(jcrUserId, "".toCharArray());
        impersonateSession = jcrSession.impersonate(impersonateCredentials);
        Privilege[] privileges = getPrivileges(impersonateSession, jcrPath);
        log.info("========= " + ((SimpleCredentials) impersonateCredentials).getUserID() + " ==============");
        Map<String, String> privilegesMap = new HashMap<>();
        for (Privilege p : privileges) {
            privilegesMap.put(p.getName(), "true");
            log.info("p=" + p.getName());
        }
        templateParams.put("privilegesMap", privilegesMap);
        String[] allPermissions = { "jcr:read", "jcr:write", "hippo:author", "hippo:editor", "hippo:admin",
                "jcr:setProperties", "jcr:setAccessControlPolicy", "jcr:addChildNodes",
                "jcr:getAccessControlPolicy", "jcr:removeChildNodes" };

        templateParams.put("allPermissions", allPermissions);

    } catch (LoginException ex) {
        BasicAuth.setRequestAuthorizationHeaders(res, "Repository");
        log.error("Error logging in to repository", ex);
    } catch (Exception ex) {
        templateParams.put("exception", ex);
        log.error("Error retrieving permissions", ex);
    } finally {
        try {
            if (jcrSession != null) {
                renderTemplatePage(req, res, getRenderTemplate(req), templateParams);
            }
        } catch (Exception te) {
            log.warn("Failed to render freemarker template.", te);
        } finally {
            if (jcrSession != null) {
                jcrSession.logout();
            }

            if (impersonateSession != null) {
                impersonateSession.logout();
            }
        }
    }

}

From source file:net.wastl.webmail.server.WebMailServlet.java

/**
 * Handle a request to the WebMail servlet. This is the central method of
 * the WebMailServlet. It first gathers all of the necessary information
 * from the client, then either creates or gets a Session and executes the
 * URL handler for the given path./*w ww.jav a 2 s .  c o m*/
 */
public void service(ServletRequest req1, ServletResponse res1) throws ServletException {
    final HttpServletRequest req = (HttpServletRequest) req1;
    final HttpServletResponse res = (HttpServletResponse) res1;
    final HTTPRequestHeader http_header = new HTTPRequestHeader();

    if (req.getServletPath().equals("/admin"))
        try {
            log.debug("Forwarding /admin request back to self");
            req.getRequestDispatcher("WebMail/admin").forward(req1, res1);
            return;
        } catch (IOException ioe) {
            log.fatal("Forward from '/admin' failed", ioe);
            throw new ServletException(ioe.getMessage());
        }

    final Enumeration en = req.getHeaderNames();
    while (en.hasMoreElements()) {
        final String s = (String) en.nextElement();
        http_header.setHeader(s, req.getHeader(s));
    }

    http_header.setPath(req.getPathInfo() == null ? "/" : req.getPathInfo());

    InetAddress addr;
    try {
        addr = InetAddress.getByName(req.getRemoteHost());
    } catch (final UnknownHostException e) {
        try {
            addr = InetAddress.getByName(req.getRemoteAddr());
        } catch (final Exception ex) {
            throw new ServletException("Remote host must identify!");
        }
    }

    HTMLDocument content = null;
    final int err_code = 400;
    HTTPSession sess = null;

    /*
     * Here we try to parse the MIME content that the Client sent in his
     * POST since the JServ doesn't do that for us:-( At least we can use
     * the functionality provided by the standalone server where we need to
     * parse the content ourself anyway.
     */
    try {
        final BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());

        /*
         * First we try to use the Servlet API's methods to parse the
         * parameters. Unfortunately, it doesn't know how to handle MIME
         * multipart POSTs, so we will have to handle that ourselves
         */

        /*
         * First get all the parameters and set their values into
         * http_header
         */
        Enumeration enum2 = req.getParameterNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setContent(s, req.getParameter(s));
            // log.info("Parameter "+s);
        }

        /* Then we set all the headers in http_header */
        enum2 = req.getHeaderNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setHeader(s, req.getHeader(s));
        }

        /*
         * In Servlet API 2.2 we might want to fetch the attributes also,
         * but this doesn't work in API 2.0, so we leave it commented out
         */
        // enum2=req.getAttributeNames();
        // while(enum2.hasMoreElements()) {
        // String s=(String)enum2.nextElement();
        // log.info("Attribute "+s);
        // }

        /* Now let's try to handle multipart/form-data posts */

        if (req.getContentType() != null
                && req.getContentType().toUpperCase().startsWith("MULTIPART/FORM-DATA")) {
            final int size = Integer.parseInt(WebMailServer.getStorage().getConfig("max attach size"));
            final MultipartParser mparser = new MultipartParser(req, size);
            Part p;
            while ((p = mparser.readNextPart()) != null) {
                if (p.isFile()) {
                    final ByteStore bs = ByteStore.getBinaryFromIS(((FilePart) p).getInputStream(), size);
                    bs.setName(((FilePart) p).getFileName());
                    bs.setContentType(getStorage().getMimeType(((FilePart) p).getFileName()));
                    http_header.setContent(p.getName(), bs);
                    log.info("File name " + bs.getName());
                    log.info("Type      " + bs.getContentType());

                } else if (p.isParam()) {
                    http_header.setContent(p.getName(), ((ParamPart) p).getStringValue());
                }

                // log.info("Parameter "+p.getName());
            }
        }

        try {
            final String url = http_header.getPath();

            try {
                /* Find out about the session id */
                sess = req.getSession(false) == null ? null
                        : (HTTPSession) req.getSession(false).getAttribute("webmail.session");

                /*
                 * If the user was logging on, he doesn't have a session id,
                 * so generate one. If he already had one, all the better,
                 * we will take the old one
                 */
                if (sess == null && url.startsWith("/login")) {
                    sess = newSession(req, http_header);
                } else if (sess == null && url.startsWith("/admin/login")) {
                    http_header.setHeader("LOGIN", "Administrator");
                    sess = newAdminSession(req, http_header);
                }
                if (sess == null && !url.equals("/") && !url.startsWith("/passthrough")
                        && !url.startsWith("/admin")) {
                    content = getURLHandler().handleURL("/logout", sess, http_header);
                } else {
                    /* Ensure that the session state is up-to-date */
                    if (sess != null) {
                        sess.setEnv();
                    }

                    /* Let the URLHandler determine the result of the query */
                    content = getURLHandler().handleURL(url, sess, http_header);
                }
            } catch (final InvalidPasswordException e) {
                log.error("Connection to " + addr.toString() + ": Authentication failed!");
                if (url.startsWith("/admin/login")) {
                    content = getURLHandler().handleURL("/admin", null, http_header);
                } else if (url.startsWith("/login")) {
                    content = getURLHandler().handleURL("/", null, http_header);
                } else
                    // content=new
                    // HTMLErrorMessage(getStorage(),e.getMessage());
                    throw new ServletException("Invalid URL called!");
            } catch (final Exception ex) {
                content = getURLHandler().handleException(ex, sess, http_header);
                log.debug("Some strange error while handling request", ex);
            }

            /*
             * Set some HTTP headers: Date is now, the document should
             * expire in 5 minutes, proxies and clients shouldn't cache it
             * and all WebMail documents must be revalidated when they think
             * they don't have to follow the "no-cache".
             */
            res.setDateHeader("Date:", System.currentTimeMillis());
            res.setDateHeader("Expires", System.currentTimeMillis() + 300000);
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Cache-Control", "must-revalidate");

            synchronized (out) {
                res.setStatus(content.getReturnCode());

                if (content.hasHTTPHeader()) {
                    final Enumeration enumVar = content.getHTTPHeaderKeys();
                    while (enumVar.hasMoreElements()) {
                        final String s = (String) enumVar.nextElement();
                        res.setHeader(s, content.getHTTPHeader(s));
                    }
                }

                /*
                 * What we will send is an image or some other sort of
                 * binary
                 */
                if (content instanceof HTMLImage) {
                    final HTMLImage img = (HTMLImage) content;
                    /*
                     * the HTMLImage class provides us with most of the
                     * necessary information that we want to send
                     */
                    res.setHeader("Content-Type", img.getContentType());
                    res.setHeader("Content-Transfer-Encoding", img.getContentEncoding());
                    res.setHeader("Content-Length", "" + img.size());
                    res.setHeader("Connection", "Keep-Alive");

                    /* Send 8k junks */
                    int offset = 0;
                    while (offset + chunk_size < img.size()) {
                        out.write(img.toBinary(), offset, chunk_size);
                        offset += chunk_size;
                    }
                    out.write(img.toBinary(), offset, img.size() - offset);
                    out.flush();

                    out.close();
                } else {
                    final byte[] encoded_content = content.toString().getBytes("UTF-8");

                    /*
                     * We are sending HTML text. Set the encoding to UTF-8
                     * for Unicode messages
                     */
                    res.setHeader("Content-Length", "" + (encoded_content.length + 2));
                    res.setHeader("Connection", "Keep-Alive");
                    res.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

                    out.write(encoded_content);
                    out.write("\r\n".getBytes());

                    out.flush();

                    out.close();
                }
            }
        } catch (final DocumentNotFoundException e) {
            log.info("Connection to " + addr.toString() + ": Could not handle request (" + err_code
                    + ") (Reason: " + e.getMessage() + ")");
            throw new ServletException("Error: " + e.getMessage(), e);
            // res.setStatus(err_code);
            // res.setHeader("Content-type","text/html");
            // res.setHeader("Connection","close");

            // content=new HTMLErrorMessage(getStorage(),e.getMessage());
            // out.write((content+"\r\n").getBytes("UTF-8"));
            // out.write("</HTML>\r\n".getBytes());
            // out.flush();
            // out.close();
        }
    } catch (final Exception e) {
        log.info("Connection to " + addr.toString() + " closed unexpectedly", e);
        throw new ServletException(e.getMessage());
    }
}

From source file:edu.umich.its.lti.google.GoogleLtiServlet.java

/**
 * This function is useful in finding the list of users on file
 * or folder  and from that list we are able to get the owner of the file/folder
 * and grab owner's email address and generate the Owner access token 
 * to delete a file/folder/* w  w w .  j  a  v  a 2  s  .co m*/
 * by a user who only has can edit right on the folder/file.
 * @throws Exception 
 * 
 */

private void getOwnerAccessToken(HttpServletRequest request, HttpServletResponse response,
        TcSessionData tcSessionData) throws Exception {
    String fileId = request.getParameter(PARAM_FILE_ID);
    String userEmailAddress = tcSessionData.getUserEmailAddress();
    String ownerOfTheFileEmailAddress = null;
    GoogleCredential credential = GoogleSecurity.authorize(getGoogleServiceAccount(request.getRemoteHost()),
            userEmailAddress);
    Drive drive = GoogleSecurity.getGoogleDrive(credential);
    try {
        PermissionList list = drive.permissions().list(fileId).execute();
        List<Permission> items = list.getItems();
        for (Permission permission : items) {
            String role = permission.getRole();
            if (role.equals("owner")) {
                ownerOfTheFileEmailAddress = permission.getEmailAddress();
                break;
            }
        }
        getGoogleOwnerAccessToken(request, response, tcSessionData, ownerOfTheFileEmailAddress);

    } catch (Exception e) {
        M_log.error("Failed to get the owner email address for the a given folder", e);
        response.getWriter().print("ERROR");
    }

}

From source file:org.openiam.webadmin.res.ResourceApprovalFlowController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    log.info("onSubmit called");

    ResourceApprovalFlowCommand assocCmd = (ResourceApprovalFlowCommand) command;
    String resId = assocCmd.getResId();

    String userId = (String) request.getSession().getAttribute("userId");
    String domainId = (String) request.getSession().getAttribute("domainid");
    String login = (String) request.getSession().getAttribute("login");

    Resource res = resourceDataService.getResource(resId);

    String btn = request.getParameter("btn");
    if (btn.equalsIgnoreCase("Delete")) {
        List<ApproverAssociation> assocList = assocCmd.getApproverAssoc();
        if (assocList != null) {

            for (ApproverAssociation a : assocList) {
                if (a.getSelected()) {
                    String assocId = a.getApproverAssocId();
                    if (!assocId.equalsIgnoreCase("NEW")) {
                        managedSysService.removeApproverAssociation(assocId);

                        auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE",
                                resId, null, "SUCCESS", null, "DELETE APPROVER", a.getApproverUserId(), null,
                                null, res.getName(), request.getRemoteHost());

                    }//from w w  w.j  a  v  a  2 s  .c o m
                }
            }

        }
    } else {

        List<ApproverAssociation> assocList = assocCmd.getApproverAssoc();

        if (assocList != null) {

            for (ApproverAssociation a : assocList) {
                if (a.getApproverRoleId() != null && a.getApproverRoleId().length() > 0) {
                    String roleStr = a.getApproverRoleId();
                    StringTokenizer st = new StringTokenizer(roleStr, "*");
                    if (st.hasMoreTokens()) {
                        a.setApproverRoleDomain(st.nextToken());
                    }
                    if (st.hasMoreElements()) {
                        a.setApproverRoleId(st.nextToken());
                    }

                } else {
                    a.setApproverRoleDomain(null);
                    a.setApproverRoleId(null);
                }

                if (a.getApproverAssocId() == null || a.getApproverAssocId().equalsIgnoreCase("NEW")) {

                    // new
                    if (a.getAssociationType() != null && a.getAssociationType().length() > 0) {
                        a.setApproverAssocId(null);
                        a.setRequestType(resId);
                        if (a.getApproverLevel() == null) {
                            a.setApproverLevel(1);
                        }

                        managedSysService.addApproverAssociation(a);

                        auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE",
                                resId, null, "SUCCESS", null, "ADD APPROVER", a.getApproverUserId(), null, null,
                                res.getName(), request.getRemoteHost());
                    }
                } else {
                    // update
                    if (a.getAssociationType() != null && a.getAssociationType().length() > 0) {
                        if (a.getApproverLevel() == null) {
                            a.setApproverLevel(1);
                        }

                        managedSysService.updateApproverAssociation(a);

                        auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "RESOURCE",
                                resId, null, "SUCCESS", null, "MODIFY APPROVER", a.getApproverUserId(), null,
                                null, res.getName(), request.getRemoteHost());
                    }
                }
            }

        }
    }
    log.info("refreshing attr list for resourceId=" + resId);
    String view = redirectView + "&menuid=RESAPPROVER&menugrp=SECURITY_RES&objId=" + resId;
    log.info("redirecting to=" + view);

    return new ModelAndView(new RedirectView(view, true));

}

From source file:org.openiam.webadmin.policy.attr.PolicyDetailController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    String userId = (String) request.getSession().getAttribute("userId");
    String domainId = (String) request.getSession().getAttribute("domainid");
    String login = (String) request.getSession().getAttribute("login");

    PolicyDetailCommand policyCommand = (PolicyDetailCommand) command;

    Policy policy = policyCommand.getPolicy();
    Set<PolicyAttribute> attrSet = policyCommand.getPolicyAttr();

    // Clean up the policy attribute ids
    if (attrSet != null) {
        for (PolicyAttribute a : attrSet) {
            if (a.getPolicyAttrId() == null || a.getPolicyAttrId().length() == 0) {
                a.setPolicyAttrId(null);
                a.setPolicyId(null);//from  w w  w.  j  ava  2s  .co m
            }

        }
    }

    policy.setPolicyAttributes(attrSet);

    // check which button was clicked
    String btn = request.getParameter("btn");
    if (btn != null && btn.equalsIgnoreCase("Delete")) {

        policyDataService.removePolicy(policy.getPolicyId());
    } else {
        if (policy.getPolicyId() == null || policy.getPolicyId().length() == 0) {
            // new
            policy.setPolicyId(null);
            policyDataService.addPolicy(policy);

            auditHelper.addLog("CREATE", domainId, login, "WEBCONSOLE", userId, "0", "POLICY", policy.getName(),
                    null, "SUCCESS", null, null, null, null, null, policy.getName(), request.getRemoteHost());

        } else {
            // update
            policyDataService.updatePolicy(policy);

            auditHelper.addLog("MODIFY", domainId, login, "WEBCONSOLE", userId, "0", "POLICY", policy.getName(),
                    null, "SUCCESS", null, null, null, null, null, policy.getName(), request.getRemoteHost());

        }
    }

    ModelAndView mav = new ModelAndView(getSuccessView());
    return mav;

}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data./*from   w  w w .j a va  2s. c o m*/
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}