Example usage for javax.servlet.http HttpServletRequest getServerName

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

Introduction

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

Prototype

public String getServerName();

Source Link

Document

Returns the host name of the server to which the request was sent.

Usage

From source file:com.icb123.Controller.ManageController.java

@RequestMapping(value = "/forJsp")
public String forJsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {//w  ww . ja  v a2  s .  com
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Constants.root = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String sysRootPath = request.getSession().getServletContext().getRealPath("\\");
        SystemStaticArgsSet.setSysRootPath(sysRootPath);
        String requestType = request.getParameter("requestType") == null ? ""
                : request.getParameter("requestType");
        int pageSize = 10;
        Employee emp = (Employee) request.getSession().getAttribute("Employee");
        if ("1".equals(requestType)) {//session
            //System.out.println("requestType");
            request.getSession().removeAttribute("Employee");
            request.getSession().removeAttribute("code");
            return "/pcManager/index.html";
        } else if ("2".equals(requestType)) {//?
            String nam1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            int rowCount = employeeManager.countEmployee();
            int num = Integer.parseInt(nam1);
            Page page = new Page(pageSize, num, rowCount);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("startRow", page.getStartRow());
            map.put("pageSize", pageSize);
            map.put("code", code);
            List<LinkedHashMap<String, String>> list = employeeManager.selectAllEmployee(map);
            request.setAttribute("list", list);
            request.setAttribute("page", page);
            request.setAttribute("code", code);
            return "/pcManager/jsp/Employee/listUser.jsp";
        } else if ("3".equals(requestType)) {// ?id
            String code = request.getParameter("id") == null ? "" : request.getParameter("id");
            int num1 = employeeManager.deleteEmployeeByCode(code);
            if (num1 > 0) {
                System.out.println(num1);
                request.setAttribute("ok", "?!!!");
            }
            return "manage/forJsp.do?pageSize1=4&num1=1&requestType=2";
        } else if ("4".equals(requestType)) {//?
            String id = request.getParameter("id") == null ? "" : request.getParameter("id");
            String name = request.getParameter("name1") == null ? "" : request.getParameter("name1");
            String weixinCode = request.getParameter("weixinCode") == null ? ""
                    : request.getParameter("weixinCode");
            String mobile = request.getParameter("mobile") == null ? "" : request.getParameter("mobile");
            String loginName = request.getParameter("loginName") == null ? ""
                    : request.getParameter("loginName");
            String positionCode = request.getParameter("positionCode") == null ? ""
                    : request.getParameter("positionCode");
            String departmentCode = request.getParameter("departmentCode") == null ? ""
                    : request.getParameter("departmentCode");
            String password = request.getParameter("password") == null ? "" : request.getParameter("password");
            String roleCode = request.getParameter("roleCode") == null ? "" : request.getParameter("roleCode");
            int id1 = Integer.parseInt(id);
            if (id1 != 0) {
                String modifiedCode = (String) request.getSession().getAttribute("code");
                Employee e = employeeManager.findEmployeeById(id1);
                String employeeCodeString = e.getCode();
                List<EmployeeRole> list = employeeManager.findRoleByCode(employeeCodeString);
                if (list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        String RoleCode1 = list.get(i).getRoleCode();
                        if (!RoleCode1.equals(roleCode)) {
                            employeeManager.updateEmployeeRole(e.getCode(), roleCode);
                            int num = employeeManager.updateIcbEmployeeById(name, departmentCode, positionCode,
                                    loginName, password, id1, mobile, weixinCode, modifiedCode);
                            if (num != 0) {
                                request.setAttribute("ok", "?");
                            }
                        } else {
                            int num = employeeManager.updateIcbEmployeeById(name, departmentCode, positionCode,
                                    loginName, password, id1, mobile, weixinCode, modifiedCode);
                            if (num != 0) {
                                request.setAttribute("ok", "?");
                            }
                        }
                    }
                } else {
                    employeeManager.saveEmployeeRole(e.getCode(), roleCode);
                    int num = employeeManager.updateIcbEmployeeById(name, departmentCode, positionCode,
                            loginName, password, id1, mobile, weixinCode, modifiedCode);
                    if (num != 0) {
                        request.setAttribute("ok", "?");
                    }
                }
            } else {
                String code = systemParamManager.employeeCode();
                employeeManager.saveEmployee(name, mobile, loginName, password, positionCode, departmentCode,
                        code, emp.getCode(), weixinCode);
                employeeManager.saveEmployeeRole(code, roleCode);
                request.setAttribute("ok", "?");
            }
            return "manage/forJsp.do?requestType=2&num1=1";
        } else if ("5".equals(requestType)) {//?
            String nam1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
            String name = request.getParameter("name1") == null ? "" : request.getParameter("name1");
            String mobile = request.getParameter("mobile1") == null ? "" : request.getParameter("mobile1");
            List<Map<String, String>> list1 = new ArrayList<Map<String, String>>();
            if (name == "" && mobile == "") {
                int rowCount = customerManager.countCustomer();
                int num = Integer.parseInt(nam1);
                Page page = new Page(pageSize, num, rowCount);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                list1 = customerManager.selectAllCustomer(map);
                request.setAttribute("list1", list1);
                request.setAttribute("page", page);
                return "/pcManager/jsp/customer/listCustomer.jsp";
            } else {
                Map<String, Object> map1 = new HashMap<String, Object>();
                map1.put("name", name);
                map1.put("mobile", mobile);
                int rowCount = customerManager.countByNameOrmobile(map1);
                int num = Integer.parseInt(nam1);
                Page page = new Page(pageSize, num, rowCount);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", name);
                map.put("mobile", mobile);
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                list1 = customerManager.findByNameOrmobile(map);
                request.setAttribute("list1", list1);
                request.setAttribute("page", page);
                request.setAttribute("mobile", mobile);
                request.setAttribute("name", name);
                return "/pcManager/jsp/customer/listCustomer.jsp";
            }
        } else if ("6".equals(requestType)) {//? 2015/11/11 ?
            return "/pcManager/jsp/car/listCar.jsp";
        } else if ("7".equals(requestType)) {//??? 2015/11/11 ?
            String typeCode = "";
            String nam1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
            typeCode = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<AccessoriesType> typeList = accessoriesTypeManager.selectAll();
            int num = Integer.parseInt(nam1);
            if (typeCode == "") {
                Map<String, Object> map = new HashMap<String, Object>();
                int rowCount = accessoriesInfoManager.countAccessoriesStorage();
                Page page = new Page(pageSize, num, rowCount);
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                List<AccessoriesStorage> list = accessoriesInfoManager.searchAccessoriesStorage(map);
                request.setAttribute("list", list);
                request.setAttribute("page", page);
                request.setAttribute("typeCode", typeCode);
                request.setAttribute("typeList", typeList);
                return "/pcManager/jsp/accessories/listAccessories.jsp";
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                int rowCount = accessoriesInfoManager.countByTypeCode(typeCode);
                Page page = new Page(pageSize, num, rowCount);
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                map.put("typeCode", typeCode);
                List<AccessoriesStorage> list = accessoriesInfoManager.searchByTypeCode(map);
                request.setAttribute("list", list);
                request.setAttribute("typeList", typeList);
                request.setAttribute("page", page);
                request.setAttribute("typeCode", typeCode);
                return "/pcManager/jsp/accessories/listAccessories.jsp";
            }
        } else if ("8".equals(requestType)) {//? 2015/11/11 ?
            List<FalseAccount> list = falseAccountManager.selectAllFalseAccount();
            request.setAttribute("list", list);
            return "/pcManager/jsp/customer/addAccount.jsp";
        } else if ("9".equals(requestType)) {//? 2015/11/11 ?
            List<Role> list = employeeManager.findAllRole();
            request.setAttribute("list", list);
            return "/pcManager/jsp/Role/listRole.jsp";
        } else if ("10".equals(requestType)) {// 2015/11/12 ?
            String nam1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
            String name = request.getParameter("name1") == null ? "" : request.getParameter("name1");
            String licensePlate = request.getParameter("licensePlate1") == null ? ""
                    : request.getParameter("licensePlate1");
            if (name == "" && licensePlate == "") {
                int num = Integer.parseInt(nam1);
                int rowCount = customerManager.countCustomerCar();
                Page page = new Page(pageSize, num, rowCount);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                List<Map<String, Object>> list = customerManager.selectCustomerCar(map);
                request.setAttribute("list", list);
                request.setAttribute("page", page);
                return "/pcManager/jsp/customer/customerCar.jsp";
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", name);
                map.put("licensePlate", licensePlate);
                int rowCount = customerManager.countByNameOrlicensePlate(map);
                int num = Integer.parseInt(nam1);
                System.out.println(rowCount);
                Page page = new Page(pageSize, num, rowCount);
                Map<String, Object> map1 = new HashMap<String, Object>();
                map1.put("name", name);
                map1.put("licensePlate", licensePlate);
                map1.put("startRow", page.getStartRow());
                map1.put("pageSize", pageSize);
                List<Map<String, Object>> list = customerManager.selectByNameOrlicensePlate(map1);
                request.setAttribute("list", list);
                request.setAttribute("page", page);
                request.setAttribute("name", name);
                request.setAttribute("licensePlate", licensePlate);
                return "/pcManager/jsp/customer/customerCar.jsp";
            }
        }
    } catch (Exception e) {
        outPutErrorInfor(ManageController.class.getName(), "forJsp", e);
        e.printStackTrace();
    }
    return null;
}

From source file:de.appsolve.padelcampus.filter.LoginFilter.java

/**
 * @param request/*  w w  w. java2 s.com*/
 * @param response
 * @param chain
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        for (Pattern pattern : NO_FILTER_LIST) {
            if (pattern.matcher(requestURI).matches()) {
                sessionUtil.setCustomer(httpRequest, null);
                chain.doFilter(request, response);
                return;
            }
        }

        CustomerI customer = sessionUtil.getCustomer(httpRequest);
        if (customer == null) {
            String hostHeader = httpRequest.getHeader("host");
            if (!StringUtils.isEmpty(hostHeader)) {
                String[] hostHeaderSplit = hostHeader.split(":");
                customer = customerDAO.findByDomainName(hostHeaderSplit[0]);
            }
            if (customer == null) {
                String url = "";
                String serverName = httpRequest.getServerName();
                if (!StringUtils.isEmpty(serverName)) {
                    String[] domainParts = serverName.split("\\.");
                    if (domainParts.length > 2) {
                        url = httpRequest.getScheme() + "://" + domainParts[domainParts.length - 2] + "."
                                + domainParts[domainParts.length - 1];
                        if (httpRequest.getScheme().equals("http") && httpRequest.getServerPort() != 80) {
                            url += ":" + httpRequest.getServerPort();
                        }
                    }
                }
                url += PATH_START_PAGE;
                httpResponse.setStatus(HttpStatus.PERMANENT_REDIRECT.value());
                httpResponse.sendRedirect(url);
                return;
            }
            sessionUtil.setCustomer(httpRequest, customer);
        }

        //login user in case of valid login cookie
        Player user = sessionUtil.getUser(httpRequest);
        if (user == null) {
            Cookie[] cookies = httpRequest.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName() != null && cookie.getName().equals(COOKIE_LOGIN_TOKEN)) {
                        String cookieValue = cookie.getValue();
                        if (StringUtils.isEmpty(cookieValue)) {
                            loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                        } else {
                            String[] cookieValueSplit = cookieValue.split(":");
                            if (cookieValueSplit.length != 2) {
                                loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                            } else {
                                String uuid = cookieValueSplit[0];
                                String loginCookieRandomValue = cookieValueSplit[1];
                                LoginCookie loginCookie = loginUtil.isValidLoginCookie(uuid,
                                        loginCookieRandomValue);
                                if (loginCookie == null) {
                                    loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                                } else {
                                    Player player = playerDAO.findByUUID(loginCookie.getPlayerUUID());
                                    if (player == null) {
                                        loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                                    } else {
                                        //log user in
                                        sessionUtil.setUser(httpRequest, player);

                                        //update loginCookieHash
                                        loginUtil.updateLoginCookie(httpRequest, httpResponse);
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }

        moduleUtil.initModules(httpRequest);
    }
    chain.doFilter(request, response);
}

From source file:gov.nih.nci.security.upt.actions.LoginAction.java

public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();

    AuthenticationManager authenticationManager = null;
    AuthorizationManager authorizationManager = null;
    UserProvisioningManager userProvisioningManager = null;
    boolean loginSuccessful = false;
    boolean hasPermission = false;
    String uptContextName = DisplayConstants.UPT_CONTEXT_NAME;
    Application application = null;//from w w w  .j a  v  a 2s  .c  o  m

    String serverInfoPathPort = (request.isSecure() ? "https://" : "http://") + request.getServerName() + ":"
            + request.getServerPort();
    ObjectFactory.initialize("upt-beans.xml");
    UPTProperties uptProperties = null;
    String urlContextForLoginApp = "";
    String centralUPTConfiguration = "";
    try {
        uptProperties = (UPTProperties) ObjectFactory.getObject("UPTProperties");
        urlContextForLoginApp = uptProperties.getBackwardsCompatibilityInformation()
                .getLoginApplicationContextName();
        if (!StringUtils.isBlank(urlContextForLoginApp)) {
            serverInfoPathPort = serverInfoPathPort + "/" + urlContextForLoginApp + "/";
        } else {
            serverInfoPathPort = serverInfoPathPort + "/" + DisplayConstants.LOGIN_APPLICATION_CONTEXT_NAME
                    + "/";
        }
        uptContextName = DisplayConstants.UPT_AUTHENTICATION_CONTEXT_NAME;
    } catch (UPTConfigurationException e) {
        serverInfoPathPort = serverInfoPathPort + "/" + DisplayConstants.LOGIN_APPLICATION_CONTEXT_NAME + "/";

    }

    if (loginForm == null) {
        loginForm = new LoginForm();
        loginForm.setApplicationContextName(applicationContextName);
        loginForm.setLoginId(loginId);
        loginForm.setPassword(password);
    }

    if (StringUtils.isBlank(loginForm.getApplicationContextName())
            || StringUtils.isBlank(loginForm.getLoginId()) || StringUtils.isBlank(loginForm.getPassword())) {

        redirectAction = serverInfoPathPort;
        return "redirect";
    }

    UserInfoHelper.setUserInfo(loginForm.getLoginId(), request.getSession().getId());
    clearActionErrors();

    try {
        authorizationManager = SecurityServiceProvider.getAuthorizationManager(uptContextName);
        if (null == authorizationManager) {
            addActionError(
                    "Unable to initialize Authorization Manager for the given application context using new configuration");
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to instantiate Authorization Manager for UPT application using new configuration||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    } catch (CSException cse) {

        authorizationManager = null;
    }

    if (null == authorizationManager) {

        try {

            if (null == uptContextName || uptContextName.equalsIgnoreCase("")) {
                addActionError("Unable to read the UPT Context Name from Security Config File");
                if (log.isDebugEnabled())
                    log.debug("|" + loginForm.getLoginId()
                            + "||Login|Failure|Unable to read the UPT Context Name from Security Config File");
                return ForwardConstants.LOGIN_FAILURE;
            }
        } catch (Exception ex) {
            addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(ex.getMessage()));
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to read the UPT Context Name from Security Config File||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    }
    try {

        authenticationManager = SecurityServiceProvider
                .getAuthenticationManager(DisplayConstants.UPT_AUTHENTICATION_CONTEXT_NAME);
        if (null == authenticationManager) {
            addActionError("Unable to initialize Authentication Manager for the given application context");
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to instantiate AuthenticationManager for UPT application||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId()
                    + "||Login|Failure|Unable to instantiate AuthenticationManager for UPT application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }
    try {
        loginSuccessful = authenticationManager.login(loginForm.getLoginId(), loginForm.getPassword());
    } catch (CSCredentialExpiredException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId() + "||Login|Failure|Password Expired for user name "
                    + loginForm.getLoginId() + " and" + loginForm.getApplicationContextName() + " application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.EXPIRED_PASSWORD;
    } catch (CSFirstTimeLoginException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId() + "||Login|Failure|Password Expired for user name "
                    + loginForm.getLoginId() + " and" + loginForm.getApplicationContextName() + " application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.EXPIRED_PASSWORD;
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId() + "||Login|Failure|Login Failed for user name "
                    + loginForm.getLoginId() + " and" + loginForm.getApplicationContextName() + " application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }

    try {
        authorizationManager = SecurityServiceProvider.getAuthorizationManager(uptContextName);
        if (null == authorizationManager) {
            addActionError("Unable to initialize Authorization Manager for the given application context");
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to instantiate Authorization Manager for UPT application||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId()
                    + "||Login|Failure|Unable to instantiate AuthorizationManager for UPT application|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }
    try {
        hasPermission = authorizationManager.checkPermission(loginForm.getLoginId(),
                loginForm.getApplicationContextName(), null);
        if (!hasPermission) {
            try {
                userProvisioningManager = getUserProvisioningManager(authorizationManager,
                        loginForm.getApplicationContextName());
                if (null == userProvisioningManager) {
                    addActionError(
                            "Unable to initialize Authorization Manager for the given application context");
                    if (log.isDebugEnabled())
                        log.debug("|" + loginForm.getLoginId()
                                + "||Login|Failure|Unable to instantiate User Provisioning Manager for "
                                + loginForm.getApplicationContextName() + " application||");
                    return ForwardConstants.LOGIN_FAILURE;
                }
            } catch (CSException cse) {
                addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
                if (log.isDebugEnabled())
                    log.debug("|" + loginForm.getLoginId()
                            + "||Login|Failure|Unable to instantiate User Provisioning Manager for |"
                            + loginForm.toString() + "|" + cse.getMessage());
                return ForwardConstants.LOGIN_FAILURE;
            }
            sessionMap.put(DisplayConstants.USER_PROVISIONING_MANAGER, userProvisioningManager);
            sessionMap.put(DisplayConstants.LOGIN_OBJECT, loginForm);
            sessionMap.put(DisplayConstants.CURRENT_TABLE_ID, DisplayConstants.HOME_ID);

            sessionMap.put(Constants.UPT_USER_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE, "false");
            sessionMap.put(Constants.UPT_PROTECTION_ELEMENT_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE,
                    "false");
            sessionMap.put(Constants.UPT_PRIVILEGE_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE, "false");
            sessionMap.put(Constants.UPT_GROUP_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE, "false");
            sessionMap.put(Constants.UPT_PROTECTION_GROUP_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE,
                    "false");
            sessionMap.put(Constants.UPT_ROLE_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE, "false");
            sessionMap.put(Constants.UPT_INSTANCE_LEVEL_OPERATION + "_" + Constants.CSM_ACCESS_PRIVILEGE,
                    "false");

            return ForwardConstants.LOGIN_SUCCESS;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId() + "||Login|Failure|Error in checking permission|"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }

    try {
        //UserProvisioningManager upm = (UserProvisioningManager)authorizationManager;
        application = authorizationManager.getApplication(loginForm.getApplicationContextName());
        userProvisioningManager = getUserProvisioningManager(authorizationManager,
                loginForm.getApplicationContextName());
        if (null == userProvisioningManager) {
            addActionError("Unable to initialize Authorization Manager for the given application context");
            if (log.isDebugEnabled())
                log.debug("|" + loginForm.getLoginId()
                        + "||Login|Failure|Unable to instantiate User Provisioning Manager for "
                        + loginForm.getApplicationContextName() + " application||");
            return ForwardConstants.LOGIN_FAILURE;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId()
                    + "||Login|Failure|Unable to instantiate User Provisioning Manager for |"
                    + loginForm.toString() + "|" + cse.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }

    sessionMap.put(DisplayConstants.USER_PROVISIONING_MANAGER, userProvisioningManager);
    sessionMap.put(DisplayConstants.LOGIN_OBJECT, loginForm);
    sessionMap.put(DisplayConstants.CURRENT_TABLE_ID, DisplayConstants.HOME_ID);

    authenticationManager = null;
    authorizationManager = null;

    try {
        processUptOperation(userProvisioningManager, loginForm.getLoginId(), application.getApplicationName());
    } catch (CSTransactionException e) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(e.getMessage()));
        if (log.isDebugEnabled())
            log.debug("|" + loginForm.getLoginId()
                    + "||Login|Failure|Unable to check permissions for the user operations |"
                    + loginForm.toString() + "|" + e.getMessage());
        return ForwardConstants.LOGIN_FAILURE;
    }

    if (loginForm.getApplicationContextName().equalsIgnoreCase(uptContextName)) {
        sessionMap.put(DisplayConstants.ADMIN_USER, DisplayConstants.ADMIN_USER);
        if (log.isDebugEnabled())
            log.debug(request.getSession().getId() + "|"
                    + ((LoginForm) sessionMap.get(DisplayConstants.LOGIN_OBJECT)).getLoginId()
                    + "||Login|Success|Login Successful for user " + loginForm.getLoginId() + " and "
                    + loginForm.getApplicationContextName()
                    + " application, Forwarding to the Super Admin Home Page||");
        return ForwardConstants.ADMIN_LOGIN_SUCCESS;
    } else {
        if (log.isDebugEnabled())
            log.debug(request.getSession().getId() + "|"
                    + ((LoginForm) sessionMap.get(DisplayConstants.LOGIN_OBJECT)).getLoginId()
                    + "||Login|Success|Login Successful for user " + loginForm.getLoginId() + " and "
                    + loginForm.getApplicationContextName() + " application, Forwarding to the Home Page||");
        return ForwardConstants.LOGIN_SUCCESS;
    }
}

From source file:io.starter.datamodel.Sys.java

/**
 * Get the /1.0/application.wadl/*w  w  w .  ja  va  2s  . c  o m*/
 * 
 * TODO: implement extended WADL Apply XSLT to the WADL output to generate
 * human-readable api docs per: https://wikis.oracle.com/display/Jersey/WADL
 * 
 * 
 * @return
 * @throws IOException
 * @throws TransformerException
 */
@GET
@Path("apidocs")
@Produces(MediaType.TEXT_HTML)
public String getWADL(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse)
        throws IOException, TransformerException {

    servletResponse.addHeader("Access-Control-Allow-Origin", "*");

    // Transform the WADL to HTML using XSLT
    TransformerFactory factory = TransformerFactory.newInstance();

    // Make a URL to the XML
    String iserv = servletRequest.getScheme() + "://" + servletRequest.getServerName() + ":"
            + servletRequest.getServerPort() + "/" + SystemConstants.REST_BASE_PATH + "/";
    URL url = new URL(iserv + WADL_SOURCE_URL);

    URLConnection con = url.openConnection();
    con.setDoOutput(true);
    Source text = new StreamSource(con.getInputStream());

    // path to the XSLT
    URL urlx = new URL(SystemConstants.REST_API_SERVER_HOST + "/wadl_html_doc.xslt");
    HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();

    InputStream is = null;

    is = new BufferedInputStream(urlConnection.getInputStream());

    Source xslt = new StreamSource(is);

    Transformer transformer = factory.newTransformer(xslt);
    servletResponse.setContentType("text/html");
    OutputStream ous = servletResponse.getOutputStream();

    transformer.transform(text, new StreamResult(ous));
    ous.flush();
    ous.close();

    return "ok";
}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

private void aniLogGetMessage(HttpServletRequest request, BackplaneMessage message, Token token) {
    if (!anilogger.isEnabled()) {
        return;//  w w  w . ja  v a  2  s  . c o  m
    }

    String bus = message.getBus();
    String channelId = "https://" + request.getServerName() + "/v2/bus/" + bus + "/channel/"
            + message.getChannel();
    Map<String, Object> aniEvent = new HashMap<String, Object>();
    aniEvent.put("message_id", message.getIdValue());
    aniEvent.put("bus", bus);
    aniEvent.put("channel_id", channelId);
    aniEvent.put("client_id", token.get(Token.TokenField.ISSUED_TO_CLIENT_ID));

    aniLog("get_message", aniEvent);
}

From source file:helma.servlet.AbstractServletClient.java

void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url, int status) {
    String location = url;//from w  ww .j av a2  s. com

    if (url.indexOf("://") == -1) {
        // need to transform a relative URL into an absolute one
        String scheme = req.getScheme();
        StringBuffer loc = new StringBuffer(scheme);

        loc.append("://");
        loc.append(req.getServerName());

        int p = req.getServerPort();

        // check if we need to include server port
        if ((p > 0) && (("http".equals(scheme) && (p != 80)) || ("https".equals(scheme) && (p != 443)))) {
            loc.append(":");
            loc.append(p);
        }

        if (!url.startsWith("/")) {
            String requri = req.getRequestURI();
            int lastSlash = requri.lastIndexOf("/");

            if (lastSlash == (requri.length() - 1)) {
                loc.append(requri);
            } else if (lastSlash > -1) {
                loc.append(requri.substring(0, lastSlash + 1));
            } else {
                loc.append("/");
            }
        }

        loc.append(url);
        location = loc.toString();
    }

    // if status code was explicitly set use that, or use 303 for HTTP 1.1,
    // 302 for earlier protocol versions
    if (status >= 301 && status <= 303) {
        res.setStatus(status);
    } else if (isOneDotOne(req.getProtocol())) {
        res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    } else {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    res.setContentType("text/html");
    res.setHeader("Location", location);
}

From source file:io.getlime.push.controller.web.WebAdminController.java

@RequestMapping(value = "web/admin/message/create/do.submit", method = RequestMethod.POST)
public String actionCreatePushMessage(@Valid ComposePushMessageForm form, BindingResult bindingResult,
        RedirectAttributes attr, HttpServletRequest httpRequest) {
    if (bindingResult.hasErrors()) {
        attr.addFlashAttribute("fields", bindingResult);
        attr.addFlashAttribute("form", form);
        return "redirect:/web/admin/message/create";
    }/*from w  ww.ja  va  2s  .  com*/
    SendPushMessageRequest request = new SendPushMessageRequest();
    request.setAppId(form.getAppId());
    PushMessage message = new PushMessage();
    message.setUserId(form.getUserId());
    PushMessageBody body = new PushMessageBody();
    body.setTitle(form.getTitle());
    body.setBody(form.getBody());
    body.setSound(form.isSound() ? "default" : null);
    message.setBody(body);
    request.setMessage(message);
    HttpEntity<ObjectRequest<SendPushMessageRequest>> requestEntity = new HttpEntity<>(
            new ObjectRequest<>(request));
    RestTemplate template = new RestTemplate();
    String baseUrl = String.format("%s://%s:%d/%s", httpRequest.getScheme(), httpRequest.getServerName(),
            httpRequest.getServerPort(), httpRequest.getContextPath());
    template.exchange(baseUrl + "/push/message/send", HttpMethod.POST, requestEntity,
            new ParameterizedTypeReference<ObjectResponse<PushMessageSendResult>>() {
            });
    return "redirect:/web/admin/message/create";
}

From source file:org.edeoliveira.oauth2.dropwizard.oauth2.auth.OAuth2Resource.java

@GET
@Timed/*  w w  w .  j av a 2 s  .  co m*/
@Path(value = "/refresh")
public Response refreshToken(@Auth User user, @Context final HttpServletRequest request)
        throws AuthenticationException {
    WebTarget target = client.target(tokenUrl);
    Invocation.Builder builder = target.request();

    Form form = new Form();
    form.param("grant_type", "refresh_token");
    form.param("refresh_token", user.getToken().getRefreshToken());
    form.param("client_id", cfg.getClient_id());
    form.param("client_secret", cfg.getClient_secret());

    Response response = builder.accept(MediaType.APPLICATION_JSON)
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));

    if (response.getStatus() == HttpStatus.SC_BAD_REQUEST) {
        log.debug("Error {} : invalid refresh token {}", user.getToken().getRefreshToken(),
                response.getStatus());
        response.close();
        throw new AuthenticationException("Invalid credentials");
    }

    try {
        AccessToken newToken = response.readEntity(AccessToken.class);
        NewCookie nc = engine.buildCookie(user.getName(), newToken, request.getServerName());

        StringBuilder sb = new StringBuilder();
        sb.append("{\"name\": \"").append(user.getName()).append("\", ");
        sb.append("\"expiresIn\": \"").append(newToken.getExpiresIn()).append("\"}");

        return Response.ok(sb.toString()).cookie(nc).build();
    } catch (Exception ex) {
        log.error("Error while building login response", ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        response.close();
    }
}

From source file:com.groupdocs.HomeController.java

@RequestMapping(value = "/view", method = RequestMethod.GET)
public String index(Model model, HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "fileId", required = false) String fileId,
        @RequestParam(value = "fileUrl", required = false) String fileUrl,
        @RequestParam(value = "filePath", required = false) String filePath,
        @RequestParam(value = "tokenId", required = false) String tokenId,
        @RequestParam(value = "userName", required = false) final String userName) throws Exception {
    if (annotationHandler == null) {
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Vilnius"));
        // Application path
        String appPath = "http://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        // File storage path
        String basePath = applicationConfig.getBasePath();
        // File license path
        String licensePath = applicationConfig.getLicensePath();
        // INITIALIZE GroupDocs Java Annotation Object
        ServiceConfiguration config = new ServiceConfiguration(appPath, basePath, licensePath, Boolean.FALSE,
                applicationConfig.getWidth());
        annotationHandler = new AnnotationHandler(config);
        // InputDataHandler.setInputDataHandler(new CustomInputDataHandler(config));
    }// w  w w  .j  av a2 s . c  o  m
    // Setting header in jsp page
    model.addAttribute("groupdocsHeader", annotationHandler.getHeader());
    // Initialization of Viewer with document from this path
    final GroupDocsPath groupDocsFilePath;

    if (fileId != null && !fileId.isEmpty()) {
        groupDocsFilePath = new FileId(fileId);
    } else if (filePath != null && !filePath.isEmpty()) {
        groupDocsFilePath = new FilePath(filePath, annotationHandler.getConfiguration());
    } else if (fileUrl != null && !fileUrl.isEmpty()) {
        groupDocsFilePath = new FileUrl(fileUrl);
    } else if (tokenId != null && !tokenId.isEmpty()) {
        TokenId tki = new TokenId(tokenId);
        if (tki.isExpired()) {
            groupDocsFilePath = null;
        } else {
            groupDocsFilePath = tki;
        }
    } else {
        groupDocsFilePath = null;
    }
    final String userGuid = annotationHandler.addCollaborator(userName, groupDocsFilePath.getPath(),
            AccessRights.All, getIntFromColor(Color.black));
    HashMap<String, String> params = new HashMap<String, String>() {
        {
            // You can skip parameters which have default value
            put("filePath", groupDocsFilePath.getPath()); // Default value: empty string
            put("width", Integer.toString(applicationConfig.getWidth())); // Default value: 800
            put("height", Integer.toString(applicationConfig.getHeight())); // Default value: 600
            put("quality", "75"); // Default value: 90
            put("enableRightClickMenu", "true"); // Default value: true
            put("showHeader", Boolean.toString(applicationConfig.getShowHeader())); // Default value: true
            put("showZoom", Boolean.toString(applicationConfig.getShowZoom())); // Default value: true
            put("showPaging", Boolean.toString(applicationConfig.getShowPaging())); // Default value: true
            put("showPrint", Boolean.toString(applicationConfig.getShowPrint())); // Default value: false
            put("showFileExplorer", "true"); // Default value: true
            put("showThumbnails", Boolean.toString(applicationConfig.getShowThumbnails())); // Default value: true
            put("openThumbnails", Boolean.toString(applicationConfig.getOpenThumbnails())); // Default value: false
            put("zoomToFitWidth", "false"); // Default value: false
            put("zoomToFitHeight", "false"); // Default value: false
            put("initialZoom", "100"); // Default value: 100
            put("preloadPagesCount", "0"); // Default value: 0
            put("enableSidePanel", "true"); // Default value: true
            put("strikeOutColor", ""); // Default value: empty string
            put("enabledTools", "255"); // Default value: 255
            put("saveReplyOnFocusLoss", "false"); // Default value: false
            put("strikeoutMode", "0"); // Default value: 0
            put("sideboarContainerSelector", "div.comments_sidebar_wrapper"); // Default value: div.comments_sidebar_wrapper
            put("usePageNumberInUrlHash", "false"); // Default value: false
            put("textSelectionSynchronousCalculation", "true"); // Default value: true
            put("variableHeightPageSupport", "true"); // Default value: true
            put("useJavaScriptDocumentDescription", "true"); // Default value: true
            put("isRightPanelEnabled", "true"); // Default value: true
            put("createMarkup", "true"); // Default value: true
            put("use_pdf", "true"); // Default value: true
            put("_mode", "annotatedDocument"); // Default value: annotatedDocument
            put("selectionContainerSelector", "[name='selection-content']"); // Default value: [name='selection-content']
            put("graphicsContainerSelector", ".annotationsContainer"); // Default value: .annotationsContainer
            put("widgetId", "annotation-widget"); // Default value: annotation-widget
            put("userName", userName == null ? "Anonimous" : userName);
            put("userGuid", userGuid);
            //            put("showFolderBrowser", Boolean.toString(applicationConfig.getShowFolderBrowser())); // Not used
            //            put("showDownload", Boolean.toString(applicationConfig.getShowDownload())); // Not used
            //            put("showSearch", Boolean.toString(applicationConfig.getShowSearch())); // Not used
        }
    };
    model.addAttribute("groupdocsScripts", annotationHandler.getScripts(params));
    model.addAttribute("width", applicationConfig.getWidth()); // It is for sample JSP (index.jsp)
    model.addAttribute("height", applicationConfig.getHeight()); // It is for sample JSP (index.jsp)

    return "index";
}