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:com.rapid.actions.Webservice.java

@Override
public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception {

    _logger.trace("Webservice action : " + jsonAction);

    // get the application
    Application application = rapidRequest.getApplication();

    // get the page
    Page page = rapidRequest.getPage();// w ww  .  j a v a  2s. c  o  m

    // get the webservice action call sequence
    int sequence = jsonAction.optInt("sequence", 1);

    // placeholder for the object we're about to return
    JSONObject jsonData = null;

    // only proceed if there is a request and application and page
    if (_request != null && application != null && page != null) {

        // get any json inputs 
        JSONArray jsonInputs = jsonAction.optJSONArray("inputs");

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Webservice action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), jsonInputs.toString());

        }

        // if there is either no cache or we got no data
        if (jsonData == null) {

            // get the body into a string
            String body = _request.getBody().trim();
            // remove prolog if present
            if (body.indexOf("\"?>") > 0)
                body = body.substring(body.indexOf("\"?>") + 3).trim();
            // check number of parameters
            int pCount = Strings.occurrences(body, "?");
            // throw error if incorrect
            if (pCount != jsonInputs.length())
                throw new Exception("Request has " + pCount + " parameter" + (pCount == 1 ? "" : "s") + ", "
                        + jsonInputs.length() + " provided");
            // retain the current position
            int pos = body.indexOf("?");
            // keep track of the index of the ?
            int index = 0;
            // if there are any question marks
            if (pos > 0 && jsonInputs.length() > index) {
                // loop, but check condition at the end
                do {
                    // get the input
                    JSONObject input = jsonInputs.getJSONObject(index);
                    // url escape the value
                    String value = XML.escape(input.optString("value"));
                    // replace the ? with the input value
                    body = body.substring(0, pos) + value + body.substring(pos + 1);
                    // look for the next question mark
                    pos = body.indexOf("?", pos + 1);
                    // inc the index for the next round
                    index++;
                    // stop looping if no more ?
                } while (pos > 0);
            }

            // retrieve the action
            String action = _request.getAction();
            // create a placeholder for the request url
            URL url = null;
            // get the request url
            String requestURL = _request.getUrl();

            // if we got one
            if (requestURL != null) {

                // if the given request url starts with http use it as is, otherwise use the soa servlet
                if (_request.getUrl().startsWith("http")) {
                    // trim it
                    requestURL = requestURL.trim();
                    // insert any parameters
                    requestURL = application
                            .insertParameters(rapidRequest.getRapidServlet().getServletContext(), requestURL);
                    // use the url 
                    url = new URL(requestURL);
                } else {
                    // get our request
                    HttpServletRequest httpRequest = rapidRequest.getRequest();
                    // make a url for the soa servlet
                    url = new URL(httpRequest.getScheme(), httpRequest.getServerName(),
                            httpRequest.getServerPort(), httpRequest.getContextPath() + "/soa");
                    // check whether we have any id / version seperators
                    String[] actionParts = action.split("/");
                    // add this app and version if none
                    if (actionParts.length < 2)
                        action = application.getId() + "/" + application.getVersion() + "/" + action;
                }

                // establish the connection
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // if we are requesting from ourself
                if (url.getPath().startsWith(rapidRequest.getRequest().getContextPath())) {
                    // get our session id
                    String sessionId = rapidRequest.getRequest().getSession().getId();
                    // add it to the call for internal authentication
                    connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
                }

                // set the content type and action header accordingly
                if ("SOAP".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    connection.setRequestProperty("SOAPAction", action);
                } else if ("JSON".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "application/json");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                } else if ("XML".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                }

                // if a body has been specified
                if (body.length() > 0) {

                    // Triggers POST.
                    connection.setDoOutput(true);

                    // get the output stream from the connection into which we write the request
                    OutputStream output = connection.getOutputStream();

                    // write the processed body string into the request output stream
                    output.write(body.getBytes("UTF8"));
                }

                // check the response code
                int responseCode = connection.getResponseCode();

                // read input stream if all ok, otherwise something meaningful should be in error stream
                if (responseCode == 200) {

                    // get the input stream
                    InputStream response = connection.getInputStream();
                    // prepare an soaData object
                    SOAData soaData = null;

                    // read the response accordingly
                    if ("JSON".equals(_request.getType())) {
                        SOAJSONReader jsonReader = new SOAJSONReader();
                        String jsonResponse = Strings.getString(response);
                        soaData = jsonReader.read(jsonResponse);
                    } else {
                        SOAXMLReader xmlReader = new SOAXMLReader(_request.getRoot());
                        soaData = xmlReader.read(response);
                    }

                    SOADataWriter jsonWriter = new SOARapidWriter(soaData);

                    String jsonString = jsonWriter.write();

                    jsonData = new JSONObject(jsonString);

                    if (actionCache != null)
                        actionCache.put(application.getId(), getId(), jsonInputs.toString(), jsonData);

                    response.close();

                } else {

                    InputStream response = connection.getErrorStream();

                    String errorMessage = null;

                    if ("SOAP".equals(_request.getType())) {

                        String responseXML = Strings.getString(response);

                        errorMessage = XML.getElementValue(responseXML, "faultcode");

                    }

                    if (errorMessage == null) {

                        BufferedReader rd = new BufferedReader(new InputStreamReader(response));

                        errorMessage = rd.readLine();

                        rd.close();

                    }

                    // log the error
                    _logger.error(errorMessage);

                    // only if there is no application cache show the error, otherwise it sends an empty response
                    if (actionCache == null) {

                        throw new JSONException(
                                " response code " + responseCode + " from server : " + errorMessage);

                    } else {

                        _logger.debug("Error not shown to user due to cache : " + errorMessage);

                    }

                }

                connection.disconnect();

            } // request url != null

        } // jsonData == null

    } // got app and page

    // if the jsonData is still null make an empty one
    if (jsonData == null)
        jsonData = new JSONObject();

    // add the sequence
    jsonData.put("sequence", sequence);

    // return the object
    return jsonData;

}

From source file:helma.servlet.AbstractServletClient.java

void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url, int status) {
    String location = url;/*w  ww  . j av a  2s .c  o m*/

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

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

        int p = req.getServerPort();

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

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

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

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

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

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

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;/*from w ww.ja v a  2 s.  c o  m*/
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:fr.xebia.servlet.filter.XForwardedFilterTest.java

/**
 * Test {@link XForwardedFilter} in Jetty
 *//*from   w  w  w.j a  v a  2s .c  om*/
@Test
public void testWithJetty() throws Exception {

    // SETUP
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    // mostly default configuration : enable "x-forwarded-proto"
    XForwardedFilter xforwardedFilter = new XForwardedFilter();
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter(XForwardedFilter.PROTOCOL_HEADER_PARAMETER, "x-forwarded-proto");
    // Following is needed on ipv6 stacks..
    filterConfig.addInitParameter(XForwardedFilter.INTERNAL_PROXIES_PARAMETER,
            InetAddress.getByName("localhost").getHostAddress());
    xforwardedFilter.init(filterConfig);
    context.addFilter(new FilterHolder(xforwardedFilter), "/*", Handler.REQUEST);

    MockHttpServlet mockServlet = new MockHttpServlet();
    context.addServlet(new ServletHolder(mockServlet), "/test");

    server.start();
    try {
        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();
        String expectedRemoteAddr = "my-remote-addr";
        httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
        httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

        // VALIDATE

        Assert.assertEquals(HttpURLConnection.HTTP_OK, httpURLConnection.getResponseCode());
        HttpServletRequest request = mockServlet.getRequest();
        Assert.assertNotNull(request);

        // VALIDATE X-FOWARDED-FOR
        Assert.assertEquals(expectedRemoteAddr, request.getRemoteAddr());
        Assert.assertEquals(expectedRemoteAddr, request.getRemoteHost());

        // VALIDATE X-FORWARDED-PROTO
        Assert.assertTrue(request.isSecure());
        Assert.assertEquals("https", request.getScheme());
        Assert.assertEquals(443, request.getServerPort());
    } finally {
        server.stop();
    }
}

From source file:be.fedict.eid.idp.sp.protocol.ws_federation.AuthenticationRequestServlet.java

/**
 * {@inheritDoc}//w w  w .  ja va2  s  . c o m
 */
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doGet");

    String idpDestination;
    String spDestination;
    String context;
    String language;
    String spRealm;

    AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService();
    if (null != service) {
        idpDestination = service.getIdPDestination();
        context = service.getContext(request.getParameterMap());
        spDestination = service.getSPDestination();
        language = service.getLanguage();
        spRealm = service.getSPRealm();
    } else {
        idpDestination = this.idpDestination;
        context = null;
        if (null != this.spDestination) {
            spDestination = this.spDestination;
        } else {
            spDestination = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + request.getContextPath() + this.spDestinationPage;
        }
        language = this.language;
        spRealm = this.spRealm;
    }

    String targetUrl;
    if (null == spRealm) {
        targetUrl = idpDestination + "?wa=wsignin1.0" + "&wtrealm=" + spDestination;
    } else {
        targetUrl = idpDestination + "?wa=wsignin1.0" + "&wtrealm=" + spRealm + "&wreply=" + spDestination;
    }

    if (null != language && !language.trim().isEmpty()) {
        targetUrl += "&language=" + language;
    }
    if (null != context && !context.trim().isEmpty()) {
        targetUrl += "&wctx=" + context;
    }

    LOG.debug("targetURL: " + targetUrl);
    response.sendRedirect(targetUrl);

    // save state on session
    if (null == spRealm) {
        setRecipient(spDestination, request.getSession());
    } else {
        setRecipient(spRealm, request.getSession());
    }
    setContext(context, request.getSession());
}

From source file:fr.insalyon.creatis.vip.core.server.rpc.ConfigurationServiceImpl.java

private URL getBaseURL() throws MalformedURLException {
    URL url = null;// ww  w . j  ava2s . c o m
    HttpServletRequest request = this.getThreadLocalRequest();
    if ((request.getServerPort() == 80) || (request.getServerPort() == 443)) {
        url = new URL(request.getScheme() + "://" + request.getServerName() + request.getContextPath());
    } else {
        url = new URL(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath());
    }
    return url;
}

From source file:com.boundlessgeo.geoserver.api.controllers.ThumbnailController.java

/**
 * Creates a thumbnail for the layer as a Resource, and updates the layer with the new thumbnail
 * @param ws The workspace of the layer/*w ww .j a  v  a  2  s .  c  o  m*/
 * @param layer The layer or layerGroup to get the thumbnail for
 * @return The thumbnail image as a Resource
 * @throws Exception
 */
protected void createThumbnail(WorkspaceInfo ws, PublishedInfo layer, HttpServletRequest baseRequest)
        throws Exception {
    //Sync against this map/layer
    Semaphore s = semaphores.get(layer);
    s.acquire();
    try {
        //(SUITE-1072) Initialize the thumbnail to a blank image in case the WMS request crashes geoserver
        BufferedImage blankImage = new BufferedImage(THUMBNAIL_SIZE * 2, THUMBNAIL_SIZE * 2,
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g = blankImage.createGraphics();
        g.setColor(new Color(0, 0, 0, 0));
        g.fillRect(0, 0, blankImage.getWidth(), blankImage.getHeight());
        writeThumbnail(layer, blankImage);

        //Set up getMap request
        String url = baseRequest.getScheme() + "://localhost:" + baseRequest.getLocalPort()
                + baseRequest.getContextPath() + "/" + ws.getName() + "/wms/reflect";

        url += "?FORMAT=" + MIME_TYPE;

        ReferencedEnvelope bbox = null;
        if (layer instanceof LayerInfo) {
            url += "&LAYERS=" + layer.getName();
            url += "&STYLES=" + ((LayerInfo) layer).getDefaultStyle().getName();
            bbox = ((LayerInfo) layer).getResource().boundingBox();
        } else if (layer instanceof LayerGroupInfo) {

            LayerGroupHelper helper = new LayerGroupHelper((LayerGroupInfo) layer);
            bbox = ((LayerGroupInfo) layer).getBounds();
            url += "&CRS=" + CRS.toSRS(bbox.getCoordinateReferenceSystem());

            List<LayerInfo> layerList = helper.allLayersForRendering();
            if (layerList.size() > 0) {
                url += "&LAYERS=";
                for (int i = 0; i < layerList.size(); i++) {
                    if (i > 0) {
                        url += ",";
                    }
                    url += layerList.get(i) == null ? "" : layerList.get(i).getName();
                }
            }
            List<StyleInfo> styleList = helper.allStylesForRendering();
            if (styleList.size() > 0) {
                url += "&STYLES=";
                for (int i = 0; i < styleList.size(); i++) {
                    if (i > 0) {
                        url += ",";
                    }
                    if (styleList.get(i) == null) {
                        url += layerList.get(i).getDefaultStyle() == null ? ""
                                : layerList.get(i).getDefaultStyle().getName();
                    } else {
                        url += styleList.get(i) == null ? "" : styleList.get(i).getName();
                    }
                }
            }
        } else {
            throw new RuntimeException("layer must be one of LayerInfo or LayerGroupInfo");
        }
        //Set the size of the HR thumbnail
        //Take the smallest bbox dimension as the min dimension. We can then crop the other 
        //dimension to give a square thumbnail
        url += "&BBOX=" + ((float) bbox.getMinX()) + "," + ((float) bbox.getMinY()) + ","
                + ((float) bbox.getMaxX()) + "," + ((float) bbox.getMaxY());
        if (bbox.getWidth() < bbox.getHeight()) {
            url += "&WIDTH=" + (2 * THUMBNAIL_SIZE);
            url += "&HEIGHT=" + (2 * THUMBNAIL_SIZE * Math.round(bbox.getHeight() / bbox.getWidth()));
        } else {
            url += "&HEIGHT=" + (2 * THUMBNAIL_SIZE);
            url += "&WIDTH=" + (2 * THUMBNAIL_SIZE * Math.round(bbox.getWidth() / bbox.getHeight()));
        }

        //Run the getMap request through the WMS Reflector
        //WebMap response = wms.reflect(request);            
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        BufferedImage image = ImageIO.read(con.getInputStream());
        if (image == null) {
            throw new RuntimeException(
                    "Failed to encode thumbnail for " + ws.getName() + ":" + layer.getName());
        }
        writeThumbnail(layer, image);
    } finally {
        s.release();
    }
}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

/**
 * Processes requests for both HTTP//from w ww  . j a  v  a  2  s .  c om
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    res.setContentType("text/plain;charset=gbk");

    res.setContentType("text/html; charset=utf-8");
    PrintWriter pw = res.getWriter();
    try {
        //initialize the prefix url
        if (prefix_url == null) {
            //                String hostname = req.getServerName ();
            //                int port = req.getServerPort ();
            //                prefix_url = "http://"+hostname+":"+port+"/igfds/"+relativePath+"/";
            //updated by Ziheng - on 8/27/2015
            //This method should be used everywhere.
            int num = req.getRequestURI().indexOf("/PACS");
            String prefix = req.getRequestURI().substring(0, num + "/PACS".length()); //in case there is something before PACS
            prefix_url = req.getScheme() + "://" + req.getServerName()
                    + ("http".equals(req.getScheme()) && req.getServerPort() == 80
                            || "https".equals(req.getScheme()) && req.getServerPort() == 443 ? ""
                                    : ":" + req.getServerPort())
                    + prefix + "/" + relativePath + "/";
        }
        pw.println("<!DOCTYPE html>");
        pw.println("<html>");
        String head = "<head>" + "<title>File Uploading Response</title>"
                + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
                + "<script type=\"text/javascript\" src=\"js/TaskGridTool.js\"></script>" + "</head>";
        pw.println(head);
        pw.println("<body>");

        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold  2M 
        //extend to 2M - updated by ziheng - 9/25/2014
        diskFactory.setSizeThreshold(2 * 1024);
        // repository 
        diskFactory.setRepository(new File(tempPath));

        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        // 2M
        upload.setSizeMax(2 * 1024 * 1024);
        // HTTP
        List fileItems = upload.parseRequest(req);
        Iterator iter = fileItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                processFormField(item, pw);
            } else {
                processUploadFile(item, pw);
            }
        } // end while()
          //add some buttons for further process
        pw.println("<input type=\"button\" id=\"bt\" value=\"load\" onclick=\"load();\">");
        pw.println("<input type=\"button\" id=\"close\" value=\"close window\" onclick=\"window.close();\">");
        pw.println("</body>");
        pw.println("</html>");
    } catch (Exception e) {
        e.printStackTrace();
        pw.println("ERR:" + e.getClass().getName() + ":" + e.getLocalizedMessage());
    } finally {
        pw.flush();
        pw.close();
    }
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationResponseServlet.java

@SuppressWarnings("unchecked")
private void doIdRes(HttpServletRequest request, HttpServletResponse response)
        throws MessageException, DiscoveryException, AssociationException, IOException, ServletException {
    LOG.debug("id_res");
    LOG.debug("request URL: " + request.getRequestURL());

    // force UTF-8 encoding
    try {//ww  w  . j  a  va2 s. co  m
        request.setCharacterEncoding("UTF8");
        response.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new MessageException(e);
    }

    ParameterList parameterList = new ParameterList(request.getParameterMap());
    DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc");
    LOG.debug("request context path: " + request.getContextPath());
    LOG.debug("request URI: " + request.getRequestURI());
    String receivingUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getLocalPort()
            + request.getRequestURI();
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        receivingUrl += "?" + queryString;
    }
    LOG.debug("receiving url: " + receivingUrl);
    ConsumerManager consumerManager = AuthenticationRequestServlet.getConsumerManager(request);
    VerificationResult verificationResult = consumerManager.verify(receivingUrl, parameterList, discovered);
    Identifier identifier = verificationResult.getVerifiedId();
    if (null != identifier) {

        Date authenticationTime = null;
        String userId = identifier.getIdentifier();
        List<String> authnPolicies = new LinkedList<String>();
        Map<String, Object> attributeMap = new HashMap<String, Object>();
        LOG.debug("userId: " + userId);
        Message authResponse = verificationResult.getAuthResponse();

        // verify return_to nonce
        AuthSuccess authResp = AuthSuccess.createAuthSuccess(parameterList);

        String returnTo = authResp.getReturnTo();
        String requestReturnTo = (String) request.getSession()
                .getAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);
        if (null == returnTo || null == requestReturnTo) {
            showErrorPage("Insufficient args for validation of " + " \"openid.return_to\".", null, request,
                    response);
            return;
        }
        if (!consumerManager.verifyReturnTo(requestReturnTo, authResp)) {
            showErrorPage("Invalid \"return_to\" in response!", null, request, response);
            return;
        }
        // cleanup
        request.getSession().removeAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);

        // AX
        if (authResponse.hasExtension(AxMessage.OPENID_NS_AX)) {

            MessageExtension messageExtension = authResponse.getExtension(AxMessage.OPENID_NS_AX);
            if (messageExtension instanceof FetchResponse) {

                FetchResponse fetchResponse = (FetchResponse) messageExtension;

                Map<String, String> attributeTypes = fetchResponse.getAttributeTypes();
                for (Map.Entry<String, String> entry : attributeTypes.entrySet()) {
                    attributeMap.put(entry.getValue(), fetchResponse.getAttributeValue(entry.getKey()));
                }

            }

        }

        // PAPE
        if (authResponse.hasExtension(PapeResponse.OPENID_NS_PAPE)) {

            MessageExtension messageExtension = authResponse.getExtension(PapeResponse.OPENID_NS_PAPE);
            if (messageExtension instanceof PapeResponse) {

                PapeResponse papeResponse = (PapeResponse) messageExtension;

                authnPolicies = papeResponse.getAuthPoliciesList();
                authenticationTime = papeResponse.getAuthDate();

            }
        }

        OpenIDAuthenticationResponse openIDAuthenticationResponse = new OpenIDAuthenticationResponse(
                authenticationTime, userId, authnPolicies, attributeMap);
        request.getSession().setAttribute(this.responseSessionAttribute, openIDAuthenticationResponse);

        response.sendRedirect(request.getContextPath() + this.redirectPage);
    } else {
        showErrorPage("No verified identifier", null, request, response);
    }
}

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

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