List of usage examples for javax.servlet.http HttpServletRequest getServerPort
public int getServerPort();
From source file:jp.aegif.alfresco.online_webdav.WebDAVHelper.java
/** * Check that the destination path is on this server and is a valid WebDAV * path for this server//from w w w .j a v a 2 s . com * * @param request The request made against the WebDAV server. * @param urlStr String * @exception WebDAVServerException */ public void checkDestinationURL(HttpServletRequest request, String urlStr) throws WebDAVServerException { try { // Parse the URL URL url = new URL(urlStr); // Check if the path is on this WebDAV server boolean localPath = true; if (url.getPort() != -1 && url.getPort() != request.getServerPort()) { // Debug if (logger.isDebugEnabled()) logger.debug("Destination path, different server port"); localPath = false; } else if (url.getHost().equalsIgnoreCase(request.getServerName()) == false && url.getHost().equals(request.getLocalAddr()) == false) { // The target host may contain a domain or be specified as a numeric IP address String targetHost = url.getHost(); if (IPAddress.isNumericAddress(targetHost) == false) { String localHost = request.getServerName(); int pos = targetHost.indexOf("."); if (pos != -1) targetHost = targetHost.substring(0, pos); pos = localHost.indexOf("."); if (pos != -1) localHost = localHost.substring(0, pos); // compare the host names if (targetHost.equalsIgnoreCase(localHost) == false) localPath = false; } else { try { // Check if the target IP address is a local address InetAddress targetAddr = InetAddress.getByName(targetHost); if (NetworkInterface.getByInetAddress(targetAddr) == null) localPath = false; } catch (Exception ex) { // DEBUG if (logger.isDebugEnabled()) logger.debug("Failed to check target IP address, " + targetHost); localPath = false; } } // Debug if (localPath == false && logger.isDebugEnabled()) { logger.debug("Destination path, different server name/address"); logger.debug(" URL host=" + url.getHost() + ", ServerName=" + request.getServerName() + ", localAddr=" + request.getLocalAddr()); } } else if (!url.getPath().startsWith(getUrlPathPrefix(request))) { // Debug if (logger.isDebugEnabled()) logger.debug("Destination path, different serlet path"); localPath = false; } // If the URL does not refer to this WebDAV server throw an // exception if (localPath != true) throw new WebDAVServerException(HttpServletResponse.SC_BAD_GATEWAY); } catch (MalformedURLException ex) { // Debug if (logger.isDebugEnabled()) logger.debug("Bad destination path, " + urlStr); throw new WebDAVServerException(HttpServletResponse.SC_BAD_GATEWAY); } }
From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java
public void setStandardContextPath() { try {/*from www. j av a2 s .c om*/ HttpServletRequest request = ((HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest()); this.standardContextPath = new java.net.URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath()); } catch (Exception ex) { log.error(WebUIResourceBundle.getInstance().getString("errorSettingStandardContext") + ex.getMessage()); } }
From source file:org.infoscoop.googleapps.GoogleAppsOpenIDFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { // basically just check for openId parameters HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); String actionName = request.getServletPath(); String uid = (String) session.getAttribute("Uid"); if (uid == null) { UserInfo user = (UserInfo) session.getAttribute("user"); if (user != null) { uid = user.getEmail();//from w w w. ja v a2 s .co m String userName = user.getFirstName() + " " + user.getLastName(); if (log.isInfoEnabled()) log.info(uid + " is logged in by openid."); session.setAttribute("Uid", uid); session.setAttribute(SessionManagerFilter.LOGINUSER_NAME_ATTR_NAME, userName); } } if (uid == null) { String host_url = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() != 80 && request.getServerPort() != 443 ? (":" + request.getServerPort()) : "") + request.getContextPath(); if ("/openid_login".equalsIgnoreCase(actionName)) { try { String domainParam = domain != null ? domain : request.getParameter("hd"); if (domainParam == null) throw new OpenIDException("domain must be set."); AuthRequest authReq = startAuthentication(domainParam, request); response.sendRedirect(authReq.getDestinationUrl(true)); } catch (OpenIDException e) { log.error(e.getMessage(), e); } return; } else if ("/openid_consumer_return".equalsIgnoreCase(actionName)) { try { UserInfo user = completeAuthentication(request); request.getSession().setAttribute("user", user); response.sendRedirect("."); } catch (OpenIDException e) { log.error(e.getMessage(), e); String loginUrl = host_url + "/gapps_openid_login.jsp"; response.sendRedirect(loginUrl); } return; } else if (!isExcludePath(request.getServletPath())) { try { if (this.domain != null) { String opIdentifier = OP_IDENTIFIER_TEMPLATE + URLEncoder.encode(domain, "UTF-8"); String loginUrl = host_url + "/openid_login?openid=" + URLEncoder.encode(opIdentifier, "UTF-8"); response.sendRedirect(loginUrl); } else { String loginUrl = host_url + "/gapps_openid_login.jsp"; response.sendRedirect(loginUrl); } } catch (IOException e) { log.error(e.getMessage(), e); } return; } } chain.doFilter(servletRequest, servletResponse); }
From source file:org.georchestra.security.Proxy.java
private boolean isSameHostAndPort(HttpServletRequest request, URL url) throws IOException { return isSameServer(request, url) && url.getPort() == request.getServerPort(); }
From source file:com.icb123.Controller.ManageController.java
@RequestMapping(value = "/forAjax") public void forAjax(HttpServletRequest request, HttpServletResponse response) { try {/*from w w w . j a va2 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"); 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:org.cyk.ui.web.api.WebNavigationManager.java
public String getRequestUrl(HttpServletRequest request) { String url, path = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (path == null) { url = request.getRequestURL().toString(); if (StringUtils.isNotEmpty(request.getQueryString())) url += Constant.CHARACTER_QUESTION_MARK + request.getQueryString(); } else {//from w w w . j a v a2 s . c om url = request.getScheme() + Constant.CHARACTER_COLON + Constant.CHARACTER_SLASH + Constant.CHARACTER_SLASH + request.getServerName() + Constant.CHARACTER_COLON + request.getServerPort() + path; } //if(StringUtils.isNotEmpty(PrettyContext.getCurrentInstance().getRequestQueryString().toQueryString())) // url += NavigationHelper.QUERY_START+PrettyContext.getCurrentInstance().getRequestQueryString().toQueryString(); return url; }
From source file:com.duroty.application.mail.actions.CreateIdentityAction.java
/** * DOCUMENT ME!/*from w w w. ja v a 2 s. co 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:edu.cornell.mannlib.vitro.webapp.controller.grefine.JSONReconcileServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); resp.setContentType("application/json"); VitroRequest vreq = new VitroRequest(req); try {/*from w w w . j a va2 s . co m*/ if (vreq.getParameter("query") != null || vreq.getParameter("queries") != null) { JSONObject qJson = getResult(vreq, req, resp); log.debug("result: " + qJson.toString()); String responseStr = (vreq.getParameter("callback") == null) ? qJson.toString() : vreq.getParameter("callback") + "(" + qJson.toString() + ")"; // System.out.println("JSONReconcileServlet result: " + responseStr); ServletOutputStream out = resp.getOutputStream(); out.print(responseStr); } else { // metadata String defaultNamespace = null; String defaultTypeList = null; String serverName = null; int serverPort = req.getServerPort(); if (vreq.getWebappDaoFactory() != null) { defaultNamespace = vreq.getWebappDaoFactory().getDefaultNamespace(); } defaultTypeList = ConfigurationProperties.getBean(req) .getProperty("Vitro.reconcile.defaultTypeList"); serverName = req.getServerName(); JSONObject metaJson = getMetadata(req, resp, defaultNamespace, defaultTypeList, serverName, serverPort); String callbackStr = (vreq.getParameter("callback") == null) ? "" : vreq.getParameter("callback"); ServletOutputStream out = resp.getOutputStream(); out.print(callbackStr + "(" + metaJson.toString() + ")"); } } catch (Exception ex) { log.warn(ex, ex); } }
From source file:org.cerberus.servlet.publi.ExecuteNextInQueue.java
/** * Executes the next test case represented by the given * {@link TestCaseExecutionInQueue}//from ww w .java 2 s . c om * * @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:org.commoncrawl.service.listcrawler.ProxyServlet2.java
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {/*from w w w . java 2 s . co m*/ final RequestDetails details = new RequestDetails(); String uri = request.getRequestURI(); if (request.getQueryString() != null) uri += "?" + request.getQueryString(); final URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), uri); if (request.getServerName().equals("proxy")) { serviceProxyInternalRequest(req, res); return; } // context.log("URL="+url); details.url = url; // attempt cache load first ... CacheLoadRequest cacheLoad = new CacheLoadRequest(url); details.log.add("Executing Disk Load Request"); DiskCacheItem cacheItem = cacheLoad.executeRequest(); details.log.add("Disk Load Request Returned:" + cacheItem); // create metadata placeholder CrawlURLMetadata metadata = new CrawlURLMetadata(); NIOHttpHeaders headers = null; boolean revalidate = false; boolean cacheItemValid = true; if (cacheItem != null) { // get headers headers = buildHeaderFromHeaderItems(cacheItem.getHeaderItems()); // set last fetch time in metadata metadata.setLastFetchTimestamp(cacheItem.getFetchTime()); // parse headers HttpHeaderInfoExtractor.parseHeaders(headers, metadata); // ok now validate cache if (HttpCacheUtils.requiresValidation(metadata)) { details.log.add("CACHE Item Present But Needs Revalidation"); revalidate = true; } } // if no cache item or we to revalidate cache item .. if (cacheItem == null || revalidate) { NIOHttpConnection connection = new NIOHttpConnection(url, ProxyServer.getSingleton().getEventLoop().getSelector(), ProxyServer.getSingleton().getEventLoop().getResolver(), _cookieStore); NIOConnectionWrapper wrapper = new NIOConnectionWrapper(connection); // URLConnection connection = url.openConnection(); // connection.setAllowUserInteraction(false); // Set method /* HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection)connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } */ connection.setMethod(request.getMethod()); // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr) || lhdr.equals("cookie")) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.getRequestHeaders().set(hdr, val); // connection.addRequestProperty(hdr,val); details.log.add("req header: " + hdr + ": " + val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } String cookies = _cookieStore.GetCookies(url); if (cookies.length() != 0) { details.log.add("req injected-header: Cookie:" + cookies); connection.getRequestHeaders().set("Cookie", cookies); } // Proxy headers connection.getRequestHeaders().set("Via", "1.1 (jetty)"); // cache headers (if required) if (metadata.isFieldDirty(CrawlURLMetadata.Field_LASTMODIFIEDTIME)) { details.log.add("Sending If-Modified-Since"); connection.getRequestHeaders().set("If-Modified-Since", headers.findValue("Last-Modified")); } if (metadata.isFieldDirty(CrawlURLMetadata.Field_ETAG)) { details.log.add("Sending If-None-Match"); connection.getRequestHeaders().set("If-None-Match", metadata.getETag()); } if (!xForwardedFor) connection.getRequestHeaders().set("X-Forwarded-For", request.getRemoteAddr()); //connection.addRequestProperty("X-Forwarded-For",request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); /* if (cache_control!=null && (cache_control.indexOf("no-cache")>=0 || cache_control.indexOf("no-store")>=0)) connection.setUseCaches(false); */ // customize Connection try { // connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { //connection.setDoOutput(true); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IO.copy(in, stream); wrapper.setUploadBuffer(stream.toByteArray()); } // Connect connection.open(); } catch (Exception e) { details.log.add(CCStringUtils.stringifyException(e)); } boolean connectionSucceeded = wrapper.waitForCompletion(); InputStream proxy_in = null; // handler status codes etc. int code = 500; if (connectionSucceeded) { // set last fetch time in metadata metadata.setLastFetchTimestamp(System.currentTimeMillis()); code = connection.getResponseHeaders().getHttpResponseCode(); if (revalidate && code != 304) { details.log.add("Item ReValidate FAILED"); cacheItemValid = false; } if (code != 304) { HttpHeaderInfoExtractor.parseHeaders(connection.getResponseHeaders(), metadata); response.setStatus(code, ""); details.log.add("response code:" + code); // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getResponseHeaders().getKey(h); String val = connection.getResponseHeaders().getValue(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) response.addHeader(hdr, val); details.log.add("response header:" + hdr + ": " + val); h++; hdr = connection.getResponseHeaders().getKey(h); val = connection.getResponseHeaders().getValue(h); } response.addHeader("Via", "1.1 (jetty)"); response.addHeader("cache-control", "no-cache,no-store"); response.addHeader("Connection", "close"); // IF RESULT IS CACHEABLE ... LifeTimeInfo lifeTimeInfo = HttpCacheUtils.getFreshnessLifetimeInMilliseconds(metadata); details.log.add("getFreshnessLifetime returned:" + lifeTimeInfo._lifetime); details.log.add("getFreshnessLifetime source:" + lifeTimeInfo._source); if (lifeTimeInfo._lifetime != 0) { details.log.add("item is cachable - issuing cache request"); // construct a disk cache item ... final DiskCacheItem cacheItemForWrite = new DiskCacheItem(); // populate cacheItemForWrite.setFetchTime(System.currentTimeMillis()); cacheItemForWrite.setResponseCode(code); // headers .. h = 0; hdr = connection.getResponseHeaders().getKey(h); val = connection.getResponseHeaders().getValue(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null) { if (!hdr.toLowerCase().equals("set-cookie")) { ArcFileHeaderItem item = new ArcFileHeaderItem(); item.setItemKey(hdr); item.setItemValue(val); cacheItemForWrite.getHeaderItems().add(item); } } h++; hdr = connection.getResponseHeaders().getKey(h); val = connection.getResponseHeaders().getValue(h); } if (connection.getContentBuffer().available() != 0) { // copy result to byte array //VERY INEFFICIENT ... BUT ONLY FOR TESTING ... ByteArrayOutputStream tempStream = new ByteArrayOutputStream(); IO.copy(new NIOBufferListInputStream(connection.getContentBuffer()), tempStream); // get the underlying buffer byte[] responseBuffer = tempStream.toByteArray(); // set it into the cache item ... cacheItemForWrite.setContent(new Buffer(responseBuffer)); // and now write out buffer IO.copy(new ByteArrayInputStream(responseBuffer), response.getOutputStream()); } // ok schedule a disk cache write ... _threadPool.execute(new Runnable() { @Override public void run() { LOG.info("Writing Cache Item for URL:" + url); File cacheFileName; try { cacheFileName = cachePathFromURL(url); try { FileOutputStream fileStream = new FileOutputStream(cacheFileName); try { DataOutputStream dataOutputStream = new DataOutputStream( fileStream); cacheItemForWrite.serialize(dataOutputStream, new BinaryProtocol()); } finally { fileStream.close(); } } catch (IOException e) { LOG.error(CCStringUtils.stringifyException(e)); } } catch (MalformedURLException e) { LOG.error(CCStringUtils.stringifyException(e)); } } }); } else { details.log.add("FRESHNESS LIFETIME == 0 - SKIPPING CACHE!"); // no cache direct copy case if (connection.getContentBuffer().available() != 0) { IO.copy(new NIOBufferListInputStream(connection.getContentBuffer()), response.getOutputStream()); } } } } else { response.setStatus(500, "Proxy Request Failed"); details.log.add("Proxy Request Failed"); } } // ok now, if cache item != null and cache-item is still valid if (cacheItem != null && cacheItemValid) { // service request from cache details.log.add("Servicing Request From Disk Cache"); // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response code response.setStatus(cacheItem.getResponseCode()); // set response headers for (ArcFileHeaderItem headerItem : cacheItem.getHeaderItems()) { String key = headerItem.getItemKey().toLowerCase(); // if not in don't proxy headers ... if (key.length() != 0) { if (!_DontProxyHeaders.contains(key) && !key.equals("set-cookie")) { response.addHeader(headerItem.getItemKey(), headerItem.getItemValue()); details.log.add("cache response: " + headerItem.getItemKey() + ": " + headerItem.getItemValue()); } else { details.log.add("cache hidden-hdr: " + headerItem.getItemKey() + ": " + headerItem.getItemValue()); } } } response.addHeader("Via", "1.1 (jetty)"); response.addHeader("cache-control", "no-cache,no-store"); response.addHeader("Connection", "close"); if (cacheItem.getContent().getCount() != 0) { response.setHeader("Content-Length", null); response.addHeader("Content-Length", Integer.toString(cacheItem.getContent().getCount())); IO.copy(new ByteArrayInputStream(cacheItem.getContent().getReadOnlyBytes()), response.getOutputStream()); } } LOG.info(details.toString()); } }