Example usage for javax.servlet.http HttpServletRequest getScheme

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

Introduction

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

Prototype

public String getScheme();

Source Link

Document

Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or <code>ftp</code>.

Usage

From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java

public void setStandardContextPath() {
    try {/*from   w ww . j  av  a  2  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 ww . j av  a  2  s .c  om
            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.opengeoportal.proxy.controllers.OldDynamicOgcController.java

@SuppressWarnings("deprecation")
private void doProxy(String remoteUrl, HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    try {//from  w w w .j a v  a2s.  co  m
        this.targetUri = new URI(remoteUrl);
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //Need to handle https, but think about "restricted" layers for now.  Some institutions don't really have good protection for restricted layers.  Does this open up potential for security
    //problems for those folks?
    if (servletRequest.getScheme().equals("https")) {
        //actually, what matters the most is if the remote url is https
    }

    BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(
            servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest));

    copyRequestHeaders(servletRequest, proxyRequest);

    // Add the input entity (streamed) then execute the request.
    HttpResponse proxyResponse = null;
    InputStream servletRequestInputStream = servletRequest.getInputStream();
    try {
        try {
            proxyRequest.setEntity(
                    new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength()));

            // Execute the request
            logger.debug("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI()
                    + " -- " + proxyRequest.getRequestLine().getUri());

            proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);
        } finally {
            closeQuietly(servletRequestInputStream);
        }

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();
        logger.info("Status from remote server: " + Integer.toString(statusCode));
        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            EntityUtils.consume(proxyResponse.getEntity());
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        // reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        throw new RuntimeException(e);
    }
}

From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java

/**
 * Renders the Metrics tab in the Admin GUI console. Retrieves the list of all metrics being
 * collected in the system by invoking the MetricsEndpoint, and then parsing this JSON
 * response to create the table in the Metrics tab that consists of the list of metric names and
 * hyperlinks for each format for each time range that a metric's data can be retrieved.
 *///from w w  w. j  ava  2s. co  m
@SuppressWarnings("rawtypes")
@Override
protected void renderContent(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOGGER.debug("ENTERING: renderContent");

    final PrintWriter pw = response.getWriter();

    String metricsServiceUrl = SystemBaseUrl.constructUrl(METRICS_SERVICE_BASE_URL, true);

    // Call Metrics Endpoint REST service to get list of all of the monitored
    // metrics and their associated hyperlinks to graph their historical data.
    // Response is a JSON-formatted string.
    LOGGER.debug("(NEW) Creating WebClient to URI {}", metricsServiceUrl);
    WebClient client = WebClient.create(metricsServiceUrl);
    client.accept("application/json");
    if ("https".equals(request.getScheme())) {
        configureHttps(client);
    }
    Response metricsListResponse = client.get();
    InputStream is = (InputStream) metricsListResponse.getEntity();
    LOGGER.debug("Response has this many bytes in it: {}", is.available());
    String metricsList = IOUtils.toString(is);
    LOGGER.debug("metricsList = {}", metricsList);

    JSONParser parser = new JSONParser();

    // Useful class for simple JSON to handle collections when parsing
    // (Called internally by the simple JSON parser.parse(...) method)
    ContainerFactory containerFactory = new ContainerFactory() {
        public List creatArrayContainer() {
            return new LinkedList();
        }

        public Map createObjectContainer() {
            return new LinkedHashMap();
        }
    };

    try {
        LOGGER.debug("Parsing JSON metricsList response");

        // JSON-formatted text will map to a Map1<String1, Map2<String2, Map3<String3,String4>>>
        // (Numbers added to end of Map and String types so that each position could be referred
        // to)
        // String1 = metric name, e.g., "catalogQueries"
        // Map2 = mapping of time range to it list of hyperlinks
        // String2 = time range, e.g., "15m"
        // Map3 = hyperlink for each format type (e.g., PNG) for each time range for each metric
        // String3 = display text for hyperlink, e.g., PNG
        // String4 = hyperlink for metric data in specific format, e.g.,
        // http://host:port/.../catalogQueries.png?dateOffset=900
        Map<String, Map<String, Map<String, String>>> json = new TreeMap(
                (Map<String, Map<String, Map<String, String>>>) parser.parse(metricsList, containerFactory));
        Iterator iter = json.entrySet().iterator();

        // Create HTML table of Metric Name and hyperlinks to its associated
        // RRD graphs
        pw.println("<table class=\"nicetable\">");
        pw.println("<tr>");
        pw.println("<th>Metric</th>");

        // Column headers for the time ranges, e.g., 15m, 1h, 4h, etc.
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Map<String, Map<String, String>> timeRangeData = (Map<String, Map<String, String>>) entry
                    .getValue();
            Set<String> timeRanges = timeRangeData.keySet();
            for (String timeRange : timeRanges) {
                pw.println("<th>" + timeRange + "</th>");
            }
            break; // only need one set of time ranges for column headers
        }
        pw.println("</tr>");

        // List of metric names and associated hyperlinks per format per time range
        int rowCount = 1;
        iter = json.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String metricName = (String) entry.getKey();
            String tableStriping = "odd";
            if ((rowCount % 2) == 0) {
                tableStriping = "even";
            }
            pw.println("<tr class=\"" + tableStriping + " ui-state-default\">");
            pw.println("<td>" + convertCamelCase(metricName) + "</td>");
            Map<String, Map<String, String>> timeRangeData = (Map<String, Map<String, String>>) entry
                    .getValue();

            Iterator metricDataIter = timeRangeData.entrySet().iterator();
            while (metricDataIter.hasNext()) {
                Map.Entry entry2 = (Map.Entry) metricDataIter.next();
                String timeRange = (String) entry2.getKey();

                // For each time range (for each metric), a list of display text and its
                // associated hyperlink
                // is provided, e.g., "1h" and its associated hyperlink with the
                // corresponding dateOffset (in seconds) from current time.
                // Example:
                // http://<host>:<port>/services/internal/metrics?dateOffset=3600
                //
                // key=display text
                // value=URLs
                Map<String, String> metricUrls = (Map<String, String>) entry2.getValue();
                LOGGER.debug("{} -> {}", timeRange, metricUrls);
                pw.println("<td>");

                Iterator metricUrlsIter = metricUrls.entrySet().iterator();
                while (metricUrlsIter.hasNext()) {
                    Map.Entry metricUrl = (Map.Entry) metricUrlsIter.next();
                    String metricUrlCell = "<a class=\"ui-state-default ui-corner-all\" href=\""
                            + metricUrl.getValue() + "\">" + metricUrl.getKey() + "</a>&nbsp;";
                    pw.println(metricUrlCell);
                }
                pw.println("</td>");
            }
            pw.println("</tr>");
            rowCount++;
        }

        LOGGER.debug("==  toJSONString()  ==");
        LOGGER.debug(JSONValue.toJSONString(json));

        // blank line for spacing between tables
        pw.println("<tr><td colspan=\"3\">&nbsp;</td></tr>");

        // Create HTML table for aggregate reports
        pw.println("<tr>");
        pw.println("<th colspan=\"3\">Weekly Reports</th>");
        pw.println("</tr>");
        addWeeklyReportUrls(pw, NUMBER_OF_WEEKLY_REPORTS, metricsServiceUrl);

        // blank line for spacing between tables
        pw.println("<tr><td colspan=\"3\">&nbsp;</td></tr>");

        pw.println("<tr>");
        pw.println("<th colspan=\"3\">Monthly Reports</th>");
        pw.println("</tr>");

        addMonthlyReportUrls(pw, NUMBER_OF_MONTHLY_REPORTS, metricsServiceUrl);

        // blank line for spacing between tables
        pw.println("<tr><td colspan=\"3\">&nbsp;</td></tr>");

        pw.println("<tr>");
        pw.println("<th colspan=\"3\">Yearly Reports</th>");
        pw.println("</tr>");

        addYearlyReportUrls(pw, NUMBER_OF_YEARLY_REPORTS, metricsServiceUrl);

        // blank line for spacing between tables
        pw.println("<tr><td colspan=\"3\">&nbsp;</td></tr>");

        pw.println("</table>");
    } catch (ParseException pe) {
        LOGGER.warn("Parse exception building report structure", pe);
    }

    LOGGER.debug("EXITING: renderContent");
}

From source file:com.nec.harvest.controller.SonekihController.java

/**
 * Load given department current page/*  ww  w.j  a va2  s.  com*/
 * 
 * @param request
 *            HttpServletRequest
 * @param processingGroup
 *            Current processing group menu
 * @param selectedDepartment
 *            Given department
 * @param model
 *            Model interchange between client and server
 */
private void loadDepartmentPage(HttpServletRequest request, String processingGroup, String selectedDepartment,
        String processingDepartment, Model model) {
    if (StringUtils.isEmpty(processingGroup) || StringUtils.isEmpty(selectedDepartment)) {
        model.addAttribute("page", null);
        model.addAttribute("manualLoad", false);
    }

    UriComponents uriComponent = UriComponentsBuilder
            .fromUriString(
                    request.getContextPath() + "/{proNo}/pagination/paging/{orglevel}/{deptCode}/{index}")
            .build();
    URI uri = uriComponent.expand(processingGroup, selectedDepartment, processingDepartment, 0).encode()
            .toUri();

    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpHost host = new HttpHost(request.getServerName(), request.getLocalPort(), request.getScheme());
        HttpGet get = new HttpGet(uri);
        HttpResponse response = client.execute(host, get);

        // Get the content
        String htmlPage = read(response.getEntity().getContent());

        // 
        model.addAttribute("page", htmlPage);
        model.addAttribute("manualLoad", true);
        model.addAttribute("unitDept", selectedDepartment);
        model.addAttribute("deptCode", processingDepartment);
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:org.apache.axis2.transport.http.ListingAgent.java

protected void initTransportListener(HttpServletRequest httpServletRequest) {
    // httpServletRequest.getLocalPort() , giving me a build error so I had to use the followin
    String filePart;//w w  w . jav  a 2 s  .c om
    try {
        filePart = httpServletRequest.getRequestURL().toString();
    } catch (Throwable t) {
        log.info("Old Servlet API (fallback to HttpServletRequest.getRequestURI) :" + t);
        filePart = httpServletRequest.getRequestURI();
    }
    int ipindex = filePart.indexOf("//");
    String ip;
    if (ipindex >= 0) {
        ip = filePart.substring(ipindex + 2, filePart.length());
        int seperatorIndex = ip.indexOf(":");
        int slashIndex = ip.indexOf("/");
        String portstr;
        if (seperatorIndex >= 0) {
            portstr = ip.substring(seperatorIndex + 1, slashIndex);
        } else {
            portstr = "80";
        }
        try {
            addTransportListener(httpServletRequest.getScheme(), Integer.parseInt(portstr));
        } catch (NumberFormatException e) {
            log.debug(e.toString(), e);
        }
    }
}

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

@RequestMapping(value = "/forAjax")
public void forAjax(HttpServletRequest request, HttpServletResponse response) {
    try {/*w w w. jav  a2s .c o 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:org.jasig.portal.portlets.account.UserAccountHelper.java

public void sendLoginToken(HttpServletRequest request, ILocalAccountPerson account) {

    IPerson person = personManager.getPerson(request);
    final Locale[] userLocales = localeStore.getUserLocales(person);
    LocaleManager localeManager = new LocaleManager(person, userLocales);
    Locale locale = localeManager.getLocales()[0];

    IPortalUrlBuilder builder = urlProvider.getPortalUrlBuilderByPortletFName(request, "reset-password",
            UrlType.RENDER);//from  ww w.j a v a  2 s  . co  m
    IPortletUrlBuilder portletUrlBuilder = builder.getTargetedPortletUrlBuilder();
    portletUrlBuilder.addParameter("username", account.getName());
    portletUrlBuilder.addParameter("loginToken", (String) account.getAttributeValue("loginToken"));
    portletUrlBuilder.setPortletMode(PortletMode.VIEW);
    portletUrlBuilder.setWindowState(WindowState.MAXIMIZED);

    StringBuffer url = new StringBuffer();
    url.append(request.getScheme());
    url.append("://").append(request.getServerName());
    int port = request.getServerPort();
    if (port != 80 && port != 443) {
        url.append(":").append(port);
    }
    url.append(builder.getUrlString());

    log.debug("Sending password reset instructions to user with url " + url.toString());

    String emailAddress = (String) account.getAttributeValue("mail");

    final STGroup group = new STGroupDir(templateDir, '$', '$');
    final ST template = group.getInstanceOf(passwordResetTemplate);
    template.add("displayName", person.getAttribute("displayName"));
    template.add("url", url.toString());

    MimeMessage message = mailSender.createMimeMessage();
    String body = template.render();

    try {

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(emailAddress);
        helper.setText(body, true);
        helper.setSubject(messageSource.getMessage("reset.your.password", new Object[] {}, locale));
        helper.setFrom(portalEmailAddress, messageSource.getMessage("portal.name", new Object[] {}, locale));

        log.debug("Sending message to " + emailAddress + " from " + Arrays.toString(message.getFrom())
                + " subject " + message.getSubject());
        this.mailSender.send(message);

    } catch (MailException e) {
        log.error("Unable to send password reset email ", e);
    } catch (MessagingException e) {
        log.error("Unable to send password reset email ", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Unable to send password reset email ", e);
    }
}

From source file:com.duroty.application.mail.actions.CreateIdentityAction.java

/**
 * DOCUMENT ME!//from   w  ww.  j  a  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}/*from   w  w w  .  j  a va  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();
        }
    }

}