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:org.apereo.services.persondir.support.web.RequestAttributeSourceFilter.java

/**
 * Add other properties from the request to the attributes map.
 *
 * @param httpServletRequest Http Servlet Request
 * @param attributes Map of attributes to add additional attributes to from the Http Request
 *//*w ww  .j a  v  a 2 s  . co  m*/
protected void addRequestProperties(final HttpServletRequest httpServletRequest,
        final Map<String, List<Object>> attributes) {
    if (this.remoteUserAttribute != null) {
        final String remoteUser = httpServletRequest.getRemoteUser();
        attributes.put(this.remoteUserAttribute, list(remoteUser));
    }
    if (this.remoteAddrAttribute != null) {
        final String remoteAddr = httpServletRequest.getRemoteAddr();
        attributes.put(this.remoteAddrAttribute, list(remoteAddr));
    }
    if (this.remoteHostAttribute != null) {
        final String remoteHost = httpServletRequest.getRemoteHost();
        attributes.put(this.remoteHostAttribute, list(remoteHost));
    }
    if (this.serverNameAttribute != null) {
        final String serverName = httpServletRequest.getServerName();
        attributes.put(this.serverNameAttribute, list(serverName));
    }
    if (this.serverPortAttribute != null) {
        final int serverPort = httpServletRequest.getServerPort();
        attributes.put(this.serverPortAttribute, list(serverPort));
    }
}

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

@RequestMapping(value = "/forAjax")
public void forAjax(HttpServletRequest request, HttpServletResponse response) {
    try {/*from w ww .  ja va2s. co  m*/
        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");
        Employee employee = (Employee) request.getSession().getAttribute("Employee");
        if ("car1".equals(requestType)) {//??
            String parentCode = request.getParameter("carCode") == null ? "" : request.getParameter("carCode");
            List<CarInfo> list = carInfoManager.findListByParentCode(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("time1".equals(requestType)) {//?
            List<ServiceTime> list = serviceManager.findAllServiceTime();
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("service1".equals(requestType)) {//??
            String parentCode = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Service> list = serviceManager.findServiceByParentCode(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("access1".equals(requestType)) {//????
            String serviceCode = request.getParameter("serviceCode") == null ? ""
                    : request.getParameter("serviceCode");
            String carCode = request.getParameter("carCode") == null ? "" : request.getParameter("carCode");
            List<AccessoriesInfo> list = accessoriesInfoManager.findServiceMatchAccessories(serviceCode,
                    carCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("access2".equals(requestType)) {//????
            String type = request.getParameter("type") == null ? "" : request.getParameter("type");
            List<AccessoriesInfo> list = accessoriesInfoManager.findAccessoriesByType(type);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("wxMenu".equals(requestType)) {//???
            String accessToken = WeixinUntil.getAccessToken();
            int flag = wmenuManager.creatMenu(accessToken);
            Map<String, String> map = new HashMap<String, String>();
            map.put("flag", flag + "");
            OutputUtil.outPutJsonObject(response, map);
        } else if ("100".equals(requestType)) {//?
            String loginName = request.getParameter("loginName") == null ? ""
                    : request.getParameter("loginName");
            String password = request.getParameter("password") == null ? "" : request.getParameter("password");
            String nickname = request.getParameter("nickname") == null ? "" : request.getParameter("nickname");
            int flag = employeeManager.saveWeixinKefu(loginName, password, nickname, employee.getCode());
            Map<String, String> map = new HashMap<String, String>();
            map.put("flag", flag + "");
            OutputUtil.outPutJsonObject(response, map);
        } else if ("1".equals(requestType)) {//???
            String psw1 = request.getParameter("psw") == null ? "" : request.getParameter("psw");
            String id1 = request.getParameter("id") == null ? "" : request.getParameter("id");
            int i = Integer.valueOf(id1).intValue();
            Employee icbEmployee = new Employee();
            Map<String, String> result = new HashMap<String, String>();
            icbEmployee.setId(i);
            icbEmployee.setPassword(psw1);
            int num = employeeManager.findPsw(icbEmployee);
            if (num == 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("2".equals(requestType)) {//?id?
            String psw1 = request.getParameter("psw") == null ? "" : request.getParameter("psw");
            String id1 = request.getParameter("id") == null ? "" : request.getParameter("id");
            int id = Integer.valueOf(id1).intValue();
            int num = employeeManager.updatePwd(id, psw1);
            Map<String, String> result = new HashMap<String, String>();
            if (num != 0) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("3".equals(requestType)) {//session?
            String num = "";
            if (null != request.getSession()) {
                Employee user = (Employee) request.getSession().getAttribute("Employee");
                if (null != user && !"".equals(user)) {
                    num = "1";
                    response.getWriter().write(num);
                } else {
                    num = "2";
                    response.getWriter().write(num);
                }
            }
        } else if ("4".equals(requestType)) {//?id??
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            Map<String, Object> map = employeeManager.findEmployee(code);
            OutputUtil.outPutJsonObject(response, map);
        } else if ("5".equals(requestType)) {//???            
            String nam = request.getParameter("name") == null ? "" : request.getParameter("name");
            int num = employeeManager.findEmployeeName(nam);
            Map<String, String> result = new HashMap<String, String>();
            if (num >= 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("6".equals(requestType)) {//???
            String logN = request.getParameter("loginName") == null ? "" : request.getParameter("loginName");
            int num = employeeManager.findEmployeeloName(logN);
            Map<String, String> result = new HashMap<String, String>();
            if (num >= 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("9".equals(requestType)) {//
            List<Role> listRole = employeeManager.findAllRole();
            OutputUtil.outPutJsonArrary(response, listRole);
        } else if ("10".equals(requestType)) {//??
            List<Position> listposition = employeeManager.findPosition();
            OutputUtil.outPutJsonArrary(response, listposition);
        } else if ("11".equals(requestType)) {//
            List<Department> listDepartment = employeeManager.findDepartment();
            OutputUtil.outPutJsonArrary(response, listDepartment);
        } else if ("12".equals(requestType)) {//?Code
            String nickName = request.getParameter("nickName") == null ? "" : request.getParameter("nickName");
            WeixinCustomer weixinCustomer = weixinCustomerManager.findByName(nickName);
            Map<String, String> result = new HashMap<String, String>();
            if (weixinCustomer == null) {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);

            } else {
                String weixinCode = weixinCustomer.getCode();
                String code = (String) request.getSession().getAttribute("code");
                int num = employeeManager.saveEmployeeweixinCode(code, weixinCode);
                if (num == 1) {
                    result.put("msg", "1");
                    OutputUtil.outPutJsonObject(response, result);
                }
            }
        } else if ("13".equals(requestType)) {
            String code = request.getParameter("weixinCode") == null ? "" : request.getParameter("weixinCode");
            WeixinCustomer weixinCustomer = weixinCustomerManager.findByCode(code);
            Map<String, String> result = new HashMap<String, String>();
            if (weixinCustomer == null) {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("14".equals(requestType)) {//
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String orderCol = request.getParameter("orderCol") == null ? "" : request.getParameter("orderCol");
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            Map<String, String> result = new HashMap<String, String>();
            String maxCode = carInfoManager.findMaxCode(parentCode);
            String code;
            if (maxCode == null || maxCode.trim().length() == 0) {
                maxCode = "";
                code = carInfoManager.saveCar(name, parentCode, orderCol, maxCode);
            } else {
                code = carInfoManager.saveCar(name, parentCode, orderCol, maxCode);
            }
            if (StringUtils.isNotBlank(code)) {
                result.put("msg", "1");
                result.put("code", code);
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("15".equals(requestType)) {//?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            CarInfo listCarInfo = carInfoManager.findByCode(code);
            if (listCarInfo != null) {
                OutputUtil.outPutJsonObject(response, listCarInfo);
            }
        } else if ("16".equals(requestType)) {//
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String orderCol = request.getParameter("orderCol") == null ? "" : request.getParameter("orderCol");
            int number = carInfoManager.updateByCode(name, code, orderCol);
            Map<String, String> result = new HashMap<String, String>();
            if (number == 1) {
                result.put("msg", "1");
                result.put("code", code);
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("17".equals(requestType)) {//????
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            Map<String, String> result = new HashMap<String, String>();
            int number = carInfoManager.findName(name, parentCode);
            if (number >= 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("18".equals(requestType)) {//
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            Map<String, String> result = new HashMap<String, String>();
            int num = carInfoManager.deleteByCode(code);
            if (num == 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("19".equals(requestType)) {//Car
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            List<CarInfo> list = carInfoManager.findListByParentCode(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("20".equals(requestType)) {//? 2015/11/11 ?
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            List<CarInfo> list = carInfoManager.findListByParentCode(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("21".equals(requestType)) {
            String accCode = request.getParameter("name") == null ? "" : request.getParameter("name");
            String num = request.getParameter("num") == null ? "" : request.getParameter("num");
            String ioType = request.getParameter("ioType") == null ? "" : request.getParameter("ioType");
            String carCode = request.getParameter("carCode") == null ? "" : request.getParameter("carCode");
            String beizhu = request.getParameter("beizhu") == null ? "" : request.getParameter("beizhu");
            String price = request.getParameter("price") == null ? "" : request.getParameter("price");
            String empCode = request.getParameter("empCode") == null ? "" : request.getParameter("empCode");
            String moneyType = request.getParameter("moneyType") == null ? ""
                    : request.getParameter("moneyType");
            Map<String, String> result = accessoriesInfoManager.accInAndOutStorage(accCode, num, price, ioType,
                    beizhu, empCode, employee.getCode(), carCode, moneyType);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("22".equals(requestType)) {//??
            String creatCode = employee.getCode();
            String id = request.getParameter("id") == null ? "" : request.getParameter("id");
            String newBrand = request.getParameter("newBrand") == null ? "" : request.getParameter("newBrand");
            String newManufacturer = request.getParameter("newManufacturer") == null ? ""
                    : request.getParameter("newManufacturer");
            String typeCode = request.getParameter("typeCode") == null ? "" : request.getParameter("typeCode");
            String unit = request.getParameter("unit") == null ? "" : request.getParameter("unit");
            String newModel = request.getParameter("newModel") == null ? "" : request.getParameter("newModel");
            Map<String, String> result = accessoriesInfoManager.saveOrUpdateAccessoriesStorage(id, newBrand,
                    newManufacturer, typeCode, unit, newModel, creatCode);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("23".equals(requestType)) {//?id?? 2015/11/11 ?
            String id1 = request.getParameter("id") == null ? "" : request.getParameter("id");
            int id = Integer.valueOf(id1).intValue();
            AccessoriesStorage accessoriesStorage = accessoriesInfoManager.findAccessoriesStorageById(id);
            if (accessoriesStorage != null) {
                OutputUtil.outPutJsonObject(response, accessoriesStorage);
            }
        } else if ("24".equals(requestType)) {//?? 2015/11/11 ?
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String address = request.getParameter("address") == null ? "" : request.getParameter("address");
            String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone");
            String models = request.getParameter("models") == null ? "" : request.getParameter("models");
            falseAccountManager.saveAccount(name, address, models, phone);
            Map<String, String> result = new HashMap<String, String>();
            result.put("msg", "1");
            OutputUtil.outPutJsonObject(response, result);
        } else if ("25".equals(requestType)) {//? 2015/11/11 ?
            String id1 = request.getParameter("id") == null ? "" : request.getParameter("id");
            int id = Integer.valueOf(id1).intValue();
            Map<String, String> result = new HashMap<String, String>();
            int number = falseAccountManager.deleteById(id);
            if (number == 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("26".equals(requestType)) {//?? 2015/11/11 ?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Menu> list1 = menuManager.findMenu(code);
            OutputUtil.outPutJsonArrary(response, list1);
        } else if ("27".equals(requestType)) {//?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map<String, String>> list = roleManager.findByCodeUpdate(code);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("28".equals(requestType)) {//?? 2015/11/11 ?
            List<Menu> list = menuManager.selectAllMenu();
            if (list.size() > 0) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("29".equals(requestType)) {//comment 2015/11/11 ?
            String comment = request.getParameter("comment") == null ? "" : request.getParameter("comment");
            String RoleName = request.getParameter("name") == null ? "" : request.getParameter("name");
            String chestr = request.getParameter("chestr") == null ? "" : request.getParameter("chestr");
            String roleCode = request.getParameter("code") == null ? "" : request.getParameter("code");
            int number = roleManager.updateNameByCode(RoleName, roleCode, comment, employee.getCode());
            int num = roleManager.deleteRoleByCode(roleCode);
            if (num > 0) {
                String[] cheStrings = chestr.split(",");
                for (int i = 0; i < cheStrings.length; i++) {
                    String menuCode = cheStrings[i];
                    roleManager.add(roleCode, menuCode);
                }
                if (number == 1) {
                    Map<String, String> result = new HashMap<String, String>();
                    result.put("msg", "1");
                    OutputUtil.outPutJsonObject(response, result);
                }
            }
        } else if ("30".equals(requestType)) {// 2015/11/11 ?
            String isValid = "0";
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            int number = roleManager.deleteRole(isValid, code);
            if (number > 0) {
                Map<String, String> result = new HashMap<String, String>();
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("31".equals(requestType)) {// 2015/11/11 ?
            String isValid = "1";
            String comment = request.getParameter("comment") == null ? "" : request.getParameter("comment");
            String chestr = request.getParameter("chestr") == null ? "" : request.getParameter("chestr");
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String MaxCode = roleManager.findMaxCode();
            int IntCode = Integer.valueOf(MaxCode).intValue();
            int number = IntCode + 1;
            String code = "0" + String.valueOf(number);
            int num = roleManager.addOneRole(name, comment, isValid, code, employee.getCode());
            if (num == 1) {
                String[] cheStrings = chestr.split(",");
                for (int i = 0; i < cheStrings.length; i++) {
                    String menuCode = cheStrings[i];
                    roleManager.add(code, menuCode);
                }
                Map<String, String> result = new HashMap<String, String>();
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("32".equals(requestType)) {//?code ?? 2015/11/11 ?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map<String, Object>> list = customerManager.findCustomerAllService(code);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("33".equals(requestType)) {//
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            CustomerCar customerCar = customerManager.findCustomerCar(code);
            Map<Object, Object> map = new HashMap<Object, Object>();
            Date time = customerCar.getInsuranceTime();
            String insuranceTime = "";
            if (time != null) {
                insuranceTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time);
            }
            Date time1 = customerCar.getCarefulTime();
            String carefulTime = "";
            if (time1 != null) {
                carefulTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time1);
            }
            map.put("insuranceTime", insuranceTime);
            map.put("carefulTime", carefulTime);
            map.put("virCode", customerCar.getVirCode());
            map.put("engineCode", customerCar.getEngineCode());
            map.put("mileage", customerCar.getMileage());
            if (map != null) {
                OutputUtil.outPutJsonObject(response, map);
            }
        } else if ("34".equals(requestType)) {//?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<AccessoriesStorage> list = accessoriesInfoManager.findAccessoriesStorageByTypeCode(code);
            if (list != null) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("35".equals(requestType)) {//??
            List<Employee> list = employeeManager.findAllEmployee();
            if (list != null) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("36".equals(requestType)) {//? 2015.11.25 ?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map<String, String>> list = accessoriesInfoManager.findOutAccessoriesStorageRecord(code);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("37".equals(requestType)) {//? 2015.11.25 ?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map<String, String>> list = accessoriesInfoManager.findInAccessoriesStorageRecord(code);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("39".equals(requestType)) {
            List<AccessoriesStorage> list = accessoriesInfoManager.findAllAccessoriesStorage();
            if (list != null && list.size() != 0) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("40".equals(requestType)) {//?
            String code = request.getParameter("name") == null ? "" : request.getParameter("name");
            String num = request.getParameter("num") == null ? "" : request.getParameter("num");
            Map<String, Object> result = accessoriesInfoManager.outNumberChecked(code, num);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("41".equals(requestType)) {//? ? 2015.11.28
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            int number = weixinCustomerManager.setVip(code);
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", number);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("42".equals(requestType)) {//???
            List<AccessoriesType> list = accessoriesTypeManager.selectAll();
            Iterator<AccessoriesType> iterator = list.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
            if (list.size() != 0) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("43".equals(requestType)) {
            String typeName = request.getParameter("typeName") == null ? "" : request.getParameter("typeName");
            String maxCode = accessoriesTypeManager.findMaxCode();
            System.out.println(maxCode + "aaa");
            if (maxCode != "") {
                int num = Integer.valueOf(maxCode).intValue();
                int num1 = num + 1;
                System.out.println(num1);
                String code = String.valueOf(num1);
                int number = accessoriesTypeManager.addAccessoriesType(code, typeName);
                if (number == 1) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    result.put("msg", number);
                    result.put("typeName", typeName);
                    result.put("maxCode", code);
                    OutputUtil.outPutJsonObject(response, result);
                }
            }
        } else if ("44".equals(requestType)) {//??
            String typeName = request.getParameter("typeName") == null ? "" : request.getParameter("typeName");
            int num2 = accessoriesTypeManager.textName(typeName);
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", num2);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("45".equals(requestType)) {//
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            List<CarInfo> list = carInfoManager.findNewCar(parentCode);
            System.out.println(list.size());
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("46".equals(requestType)) {//
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            List<CarInfo> list = carInfoManager.findUpdateCar(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        }

    } catch (UnsupportedEncodingException e) {
        outPutErrorInfor(ManageController.class.getName(), "?", e);
    } catch (IOException e) {
        outPutErrorInfor(ManageController.class.getName(), "?", e);
    }
}

From source file:com.boyuanitsm.fort.web.rest.AccountResource.java

/**
 * POST  /register : register the user.//from  www.  ja v  a  2s. co m
 *
 * @param managedUserDTO the managed user DTO
 * @param request the HTTP request
 * @return the ResponseEntity with status 201 (Created) if the user is registred or 400 (Bad Request) if the login or e-mail is already in use
 */
@RequestMapping(value = "/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE,
        MediaType.TEXT_PLAIN_VALUE })
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserDTO managedUserDTO,
        HttpServletRequest request) {

    HttpHeaders textPlainHeaders = new HttpHeaders();
    textPlainHeaders.setContentType(MediaType.TEXT_PLAIN);

    return userRepository.findOneByLogin(managedUserDTO.getLogin().toLowerCase())
            .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
            .orElseGet(() -> userRepository.findOneByEmail(managedUserDTO.getEmail())
                    .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders,
                            HttpStatus.BAD_REQUEST))
                    .orElseGet(() -> {
                        User user = userService.createUserInformation(managedUserDTO.getLogin(),
                                managedUserDTO.getPassword(), managedUserDTO.getFirstName(),
                                managedUserDTO.getLastName(), managedUserDTO.getEmail().toLowerCase(),
                                managedUserDTO.getLangKey());
                        String baseUrl = request.getScheme() + // "http"
                        "://" + // "://"
                        request.getServerName() + // "myhost"
                        ":" + // ":"
                        request.getServerPort() + // "80"
                        request.getContextPath(); // "/myContextPath" or "" if deployed in root context

                        mailService.sendActivationEmail(user, baseUrl);
                        return new ResponseEntity<>(HttpStatus.CREATED);
                    }));
}

From source file:eu.europeana.core.util.web.ExceptionResolver.java

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object,
        Exception exception) {/*from   ww w  .j  a  v a2 s. c om*/
    PortalTheme theme = ThemeFilter.getTheme();
    if (theme == null) {
        theme = themeHandler.getDefaultTheme();
    }
    final EmailTarget emailTarget = theme.getEmailTarget();
    if (request.getRequestURI().endsWith(".ajax")) {
        return ajaxFailure(request, response, exception);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        QueryProblem queryProblem = QueryProblem.NONE;
        if (exception instanceof EuropeanaQueryException) {
            queryProblem = ((EuropeanaQueryException) exception).getFetchProblem();
        }
        Boolean debugMode = Boolean.valueOf(debug);
        String stackTrace = getStackTrace(exception);
        if (queryProblem == QueryProblem.NONE || queryProblem == QueryProblem.SOLR_UNREACHABLE) {
            if (!debugMode) { // don't send email in debugMode
                emailSender.create("exception").setFrom(emailTarget.getSystemFrom())
                        .setTo(emailTarget.getExceptionTo()).setSubject(queryProblem.getFragment())
                        .set("hostName", request.getServerName())
                        .set("request", ControllerUtil.formatFullRequestUrl(request))
                        .set("stackTrace", stackTrace).set("cacheUrl", cacheUrl).set("portalName", portalName)
                        .set("portalTheme", theme.getName()).set("portalColor", theme.getColorScheme())
                        .set("portalDisplayName", theme.getDisplayName())
                        .set("agent", request.getHeader("User-Agent"))
                        .set("referer", request.getHeader("referer")).send();
            }
            log.error(stackTrace + queryProblem);
        } else {
            log.warn("Oops", exception);
        }
        String errorMessage = MessageFormat.format("errorMessage={0}", queryProblem.toString());
        clickStreamLogger.logCustomUserAction(request, ClickStreamLogger.UserAction.EXCEPTION_CAUGHT,
                errorMessage);
        ModelAndView mav = ThemeFilter.createThemedModelAndViewPage("exception");
        mav.addObject("debug", debugMode);
        mav.addObject("interfaceLanguage", ControllerUtil.getLocale(request));
        mav.addObject("cacheUrl", theme.getCacheUrl());
        mav.addObject("portalName", portalName);
        mav.addObject("portalTheme", "theme/" + theme.getName());
        mav.addObject("portalThemeName", theme.getName());
        mav.addObject("portalColor", theme.getColorScheme());
        mav.addObject("portalDisplayName", theme.getDisplayName());
        mav.addObject("queryProblem", queryProblem);
        mav.addObject("exception", exception);
        mav.addObject("stackTrace", stackTrace);
        mav.addObject("includedMacros", includedMacros);
        final QueryParamList queryParamList = FreemarkerUtil.createQueryParamList(request.getParameterMap());
        mav.addObject("queryParamList", queryParamList);
        mav.addObject("defaultParams", queryParamList.getDefaultParamsFormatted());
        mav.addObject("pageGrabber", freeMarkerUtil);
        return mav;
    }
}

From source file:org.georchestra.security.Proxy.java

private boolean isSameServer(HttpServletRequest request, URL url) {
    try {/*from  w  w w.j  a v  a2  s .co  m*/
        return InetAddress.getByName(request.getServerName()).equals(InetAddress.getByName(url.getHost()));
    } catch (UnknownHostException e) {
        logger.error("Unknown host: " + request.getServerName());
        return false;
    }
}

From source file:com.frequentis.maritime.mcsr.web.rest.AccountResource.java

/**
 * POST  /register : register the user./*from  ww w. j a va 2 s.c om*/
 *
 * @param managedUserDTO the managed user DTO
 * @param request the HTTP request
 * @return the ResponseEntity with status 201 (Created) if the user is registered or 400 (Bad Request) if the login or e-mail is already in use
 */
@RequestMapping(value = "/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE,
        MediaType.TEXT_PLAIN_VALUE })
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserDTO managedUserDTO,
        HttpServletRequest request) {

    HttpHeaders textPlainHeaders = new HttpHeaders();
    textPlainHeaders.setContentType(MediaType.TEXT_PLAIN);

    return userRepository.findFirstByLogin(managedUserDTO.getLogin().toLowerCase())
            .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
            .orElseGet(() -> userRepository.findFirstByEmail(managedUserDTO.getEmail())
                    .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders,
                            HttpStatus.BAD_REQUEST))
                    .orElseGet(() -> {
                        User user = userService.createUserInformation(managedUserDTO.getLogin(),
                                managedUserDTO.getPassword(), managedUserDTO.getFirstName(),
                                managedUserDTO.getLastName(), managedUserDTO.getEmail().toLowerCase(),
                                managedUserDTO.getLangKey());
                        String baseUrl = request.getScheme() + // "http"
                        "://" + // "://"
                        request.getServerName() + // "myhost"
                        ":" + // ":"
                        request.getServerPort() + // "80"
                        request.getContextPath(); // "/myContextPath" or "" if deployed in root context

                        mailService.sendActivationEmail(user, baseUrl);
                        return new ResponseEntity<>(HttpStatus.CREATED);
                    }));
}

From source file:axiom.servlet.AbstractServletClient.java

void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url) {
    String location = url;/*w  w w  . j  a va2s .  c o  m*/

    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("://");
        String hostname = req.getServerName();
        boolean forwarded = false;
        if (req.getHeader("X-Forwarded-Host") != null) {
            hostname = req.getHeader("X-Forwarded-Host");
            forwarded = true;
        }
        loc.append(hostname);

        int p = (!forwarded) ? req.getServerPort() : 80;

        // 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();
    }

    // send status code 303 for HTTP 1.1, 302 otherwise
    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:com.duroty.application.mail.actions.CreateIdentityAction.java

/**
 * DOCUMENT ME!/*from w w w  .  ja v a  2s .c  o  m*/
 *
 * @param mapping DOCUMENT ME!
 * @param form DOCUMENT ME!
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {
        Preferences preferencesInstance = getPreferencesInstance(request);

        PreferencesObj preferencesObj = preferencesInstance.getPreferences();

        DynaActionForm _form = (DynaActionForm) form;

        IdentityObj identityObj = new IdentityObj();

        identityObj.setEmail((String) _form.get("email"));

        Boolean important = (Boolean) _form.get("default");

        if (important == null) {
            important = new Boolean(false);
        }

        identityObj.setImportant(important.booleanValue());
        identityObj.setName((String) _form.get("name"));
        identityObj.setReplyTo((String) _form.get("replyTo"));

        String code = preferencesInstance.createIdentity(identityObj);

        String body = getEmailBody(request, preferencesObj.getLanguage());

        MessageResources message = getResources(request);
        String subject = message.getMessage("general.title");

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + path + "/mail/preferences/validateIdentity.drt?user=" + request.getUserPrincipal() + "&code="
                + code;

        body = body.replaceAll("\\$\\{email\\}", identityObj.getEmail());
        body = body.replaceAll("\\$\\{url\\}", basePath);

        IdentityObj identityDefault = preferencesInstance.getIdentityDefault();

        Send sendInstance = getSendInstance(request);
        sendInstance.sendIdentity(identityDefault.getEmail(), identityObj.getEmail(), subject, body);
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:org.cerberus.servlet.publi.ExecuteNextInQueue.java

/**
 * Executes the next test case represented by the given
 * {@link TestCaseExecutionInQueue}/*  ww  w .j av a  2s  .co  m*/
 * 
 * @param lastInQueue
 * @param req
 * @param resp
 * @throws IOException
 */
private void executeNext(TestCaseExecutionInQueue lastInQueue, HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    String charset = resp.getCharacterEncoding();
    String query = "";
    try {
        ParamRequestMaker paramRequestMaker = makeParamRequestfromLastInQueue(lastInQueue);
        // TODO : Prefer use mkString(charset) instead of mkString().
        // However the RunTestCase servlet does not decode parameters,
        // then we have to mkString() without using charset
        query = paramRequestMaker.mkString();
    } catch (UnsupportedEncodingException uee) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, uee.getMessage());
        return;
    } catch (IllegalArgumentException iae) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
        return;
    } catch (IllegalStateException ise) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ise.getMessage());
        return;
    }

    CloseableHttpClient httpclient = null;
    HttpGet httpget = null;
    try {
        httpclient = HttpClients.createDefault();
        URI uri = new URIBuilder().setScheme(req.getScheme()).setHost(req.getServerName())
                .setPort(req.getServerPort()).setPath(req.getContextPath() + RunTestCase.SERVLET_URL)
                .setCustomQuery(query).build();
        httpget = new HttpGet(uri);
    } catch (URISyntaxException use) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, use.getMessage());
        return;
    }

    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            resp.sendError(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    } catch (ClientProtocolException cpe) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, cpe.getMessage());
    } finally {
        if (response != null) {
            response.close();
        }
    }

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.SetEmailDA.java

public ActionForward setEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final String host = HostAccessControl.getRemoteAddress(request);
    final String ip = request.getRemoteAddr();
    final String password = request.getParameter("password");
    final String userUId = request.getParameter("userUId");
    final String email = URLDecoder.decode(request.getParameter("email"), "UTF-8");

    String message = "ko";

    try {/* w w  w.  j av a 2 s.com*/

        SetEmail.run(host, ip, password, userUId, email);
        final User user = User.findByUsername(userUId);
        if (user.getPerson() != null && user.getPerson().getStudent() != null) {
            final Student student = user.getPerson().getStudent();
            for (final Registration registration : student.getRegistrationsSet()) {
                final StudentCandidacy candidacy = registration.getStudentCandidacy();
                if (candidacy != null
                        && (candidacy instanceof DegreeCandidacy || candidacy instanceof IMDCandidacy)
                        && candidacy.getExecutionYear().isCurrent()
                        && !candidacy.getCandidacySituationsSet().isEmpty()) {
                    new PDFGeneratorThread(candidacy.getExternalId(), request.getServerName(),
                            request.getServerPort(), request.getContextPath(), request.getServletPath())
                                    .start();
                }
            }
        }
        message = "ok";
    } catch (NotAuthorizedException ex) {
        message = "Not authorized";
    } catch (UserAlreadyHasEmailException ex) {
        message = "User already has email.";
    } catch (UserDoesNotExistException ex) {
        message = "User does not exist.";
    } catch (Throwable ex) {
        message = ex.getMessage();
        logger.error(ex.getMessage(), ex);
    } finally {
        final ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("text/html");
        servletOutputStream.print(message);
        servletOutputStream.flush();
        response.flushBuffer();
    }

    return null;
}