Example usage for javax.servlet.http HttpUtils getRequestURL

List of usage examples for javax.servlet.http HttpUtils getRequestURL

Introduction

In this page you can find the example usage for javax.servlet.http HttpUtils getRequestURL.

Prototype

public static StringBuffer getRequestURL(HttpServletRequest req) 

Source Link

Document

Reconstructs the URL the client used to make the request, using information in the <code>HttpServletRequest</code> object.

Usage

From source file:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * Process a POST to the servlet by handing it off to the Axis Engine.
 * Here is where SOAP messages are received
 * @param req posted request//from  w  w  w  .j ava2 s.  c  o m
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
public void doPost(HttpServletRequest req, HttpServletResponse res, Component component)
        throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;

    Message rspMsg = null;
    String contentType = null;
    InputStream is = null;
    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            log.debug("No Engine!", se);
            throw se;
        }

        res.setBufferSize(1024 * 8); // provide performance boost.

        /** get message context w/ various properties set
         */
        msgContext = createMessageContext(engine, req, res, component);
        ComponentController.set(msgContext);

        // ? OK to move this to 'getMessageContext',
        // ? where it would also be picked up for 'doGet()' ?
        if (securityProvider != null) {
            if (isDebug) {
                log.debug("securityProvider:" + securityProvider);
            }
            msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider);
        }

        is = req.getInputStream();
        Message requestMsg = new Message(is, false, req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
        // Transfer HTTP headers to MIME headers for request message.
        MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements();) {
                String headerValue = (String) f.nextElement();
                requestMimeHeaders.addHeader(headerName, headerValue);
            }
        }

        if (isDebug) {
            log.debug("Request Message:" + requestMsg);

            /* Set the request(incoming) message field in the context */
            /**********************************************************/
        }
        msgContext.setRequestMessage(requestMsg);
        String url = HttpUtils.getRequestURL(req).toString().toLowerCase();
        msgContext.setProperty(MessageContext.TRANS_URL, url);
        // put character encoding of request to message context
        // in order to reuse it during the whole process.

        try {
            String reqEnc = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (reqEnc != null)
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, reqEnc);
        } catch (SOAPException e1) {
        }

        try {
            /**
             * Save the SOAPAction header in the MessageContext bag.
             * This will be used to tell the Axis Engine which service
             * is being invoked.  This will save us the trouble of
             * having to parse the Request message - although we will
             * need to double-check later on that the SOAPAction header
             * does in fact match the URI in the body.
             */
            // (is this last stmt true??? (I don't think so - Glen))
            /********************************************************/
            soapAction = getSoapAction(req);
            if (soapAction != null) {
                msgContext.setUseSOAPAction(true);
                msgContext.setSOAPActionURI(soapAction);
            }

            // Create a Session wrapper for the HTTP session.
            // These can/should be pooled at some point.
            // (Sam is Watching! :-)
            msgContext.setSession(new AxisHttpSession(req));

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }
            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug) {
                log.debug("Invoking Axis Engine.");
                //here we run the message by the engine
            }
            //msgContext.setProperty("disablePrettyXML", "false");
            engine.invoke(msgContext);
            if (isDebug) {
                log.debug("Return from Axis Engine.");
            }
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }

            rspMsg = msgContext.getResponseMessage();

            // We used to throw exceptions on null response messages.
            // They are actually OK in certain situations (asynchronous
            // services), so fall through here and return an ACCEPTED
            // status code below.  Might want to install a configurable
            // error check for this later.
        } catch (AxisFault fault) {

            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            rspMsg = msgContext.getResponseMessage();
            if (rspMsg == null) {
                rspMsg = new Message(fault);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException)
                t = ((InvocationTargetException) t).getTargetException();
            // Exception
            if (t instanceof Exception) {
                Exception e = (Exception) t;
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = convertExceptionToAxisFault(e, rspMsg);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);

            }
            // throwable
            else {
                logException(t);
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = new Message(new AxisFault(t.toString(), t));
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        }
    } catch (AxisFault fault) {

        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        rspMsg = msgContext.getResponseMessage();
        if (rspMsg == null) {
            rspMsg = new Message(fault);
            ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    } finally {
        IOUtil.closeEL(is);
    }

    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    // Send response back along the wire... 
    if (rspMsg != null) {

        // Transfer MIME headers to HTTP headers for response message.
        MimeHeaders responseMimeHeaders = rspMsg.getMimeHeaders();
        for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader responseMimeHeader = (MimeHeader) i.next();
            res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue());
        }
        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null) {
            try {
                rspMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
            } catch (SOAPException e) {
            }
        }

        //determine content type from message response
        contentType = rspMsg.getContentType(msgContext.getSOAPConstants());
        if (isDebug)
            log.debug("Returned Content-Type:" + contentType);

        // write result to response stream
        try {
            res.setContentType(contentType);
            rspMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }

        if (!res.isCommitted())
            res.flushBuffer(); // Force it right now.
    } else {
        // No content, so just indicate accepted
        res.setStatus(202);
    }

    if (isDebug) {
        log.debug("Response sent.");
        log.debug("Exit: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post="
                + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "."
                + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName()));
    }

}

From source file:gsn.http.ac.MyDataSourceCandidateWaitingListServlet.java

private void redirectToLogin(HttpServletRequest req, HttpServletResponse res) throws IOException {
    req.getSession().setAttribute("login.target", HttpUtils.getRequestURL(req).toString());
    res.sendRedirect("/gsn/MyLoginHandlerServlet");
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

private boolean doGet(HttpServletRequest request, HttpServletResponse response, PrintWriter writer,
        Component component) throws AxisFault, ClassException, SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    String path = request.getServletPath();
    String queryString = request.getQueryString();

    AxisEngine engine = getEngine();/*  w  w  w.j  ava2s  .  co  m*/

    Iterator i = this.transport.getOptions().keySet().iterator();

    if (queryString == null) {
        return false;
    }

    String servletURI = request.getContextPath() + path;
    String reqURI = request.getRequestURI();

    // service name
    String serviceName;
    if (servletURI.length() + 1 < reqURI.length()) {
        serviceName = reqURI.substring(servletURI.length() + 1);
    } else {
        serviceName = "";
    }

    while (i.hasNext()) {
        String queryHandler = (String) i.next();
        if (queryHandler.startsWith("qs.")) {
            // Only attempt to match the query string with transport
            // parameters prefixed with "qs:".

            String handlerName = queryHandler.substring(queryHandler.indexOf(".") + 1).toLowerCase();
            // Determine the name of the plugin to invoke by using all text
            // in the query string up to the first occurence of &, =, or the
            // whole string if neither is present.

            int length = 0;
            boolean firstParamFound = false;

            while (firstParamFound == false && length < queryString.length()) {
                char ch = queryString.charAt(length++);

                if (ch == '&' || ch == '=') {
                    firstParamFound = true;

                    --length;
                }
            }

            if (length < queryString.length()) {
                queryString = queryString.substring(0, length);
            }

            if (queryString.toLowerCase().equals(handlerName) == true) {
                // Query string matches a defined query string handler name.

                // If the defined class name for this query string handler is blank,
                // just return (the handler is "turned off" in effect).

                if (this.transport.getOption(queryHandler).equals("")) {
                    return false;
                }

                // Attempt to dynamically load the query string handler
                // and its "invoke" method.

                MessageContext msgContext = createMessageContext(engine, request, response, component);
                Class plugin = ClassUtil.loadClass((String) this.transport.getOption(queryHandler));
                Method pluginMethod = plugin.getDeclaredMethod("invoke", new Class[] { msgContext.getClass() });

                msgContext.setProperty(MessageContext.TRANS_URL,
                        HttpUtils.getRequestURL(request).toString().toLowerCase());
                //msgContext.setProperty(MessageContext.TRANS_URL, "http://DefaultNamespace");
                msgContext.setProperty(HTTPConstants.PLUGIN_SERVICE_NAME, serviceName);
                msgContext.setProperty(HTTPConstants.PLUGIN_NAME, handlerName);
                msgContext.setProperty(HTTPConstants.PLUGIN_IS_DEVELOPMENT, Caster.toBoolean(isDevelopment));
                msgContext.setProperty(HTTPConstants.PLUGIN_ENABLE_LIST, Boolean.FALSE);
                msgContext.setProperty(HTTPConstants.PLUGIN_ENGINE, engine);
                msgContext.setProperty(HTTPConstants.PLUGIN_WRITER, writer);
                msgContext.setProperty(HTTPConstants.PLUGIN_LOG, log);
                msgContext.setProperty(HTTPConstants.PLUGIN_EXCEPTION_LOG, exceptionLog);

                // Invoke the plugin.
                pluginMethod.invoke(ClassUtil.loadInstance(plugin), new Object[] { msgContext });
                writer.close();

                return true;

            }
        }
    }

    return false;
}

From source file:org.apache.axis.transport.http.AxisServlet.java

/**
 * Process GET requests. This includes handoff of pseudo-SOAP requests
 *
 * @param request request in//  w w w . java  2  s  .  com
 * @param response request out
 * @throws ServletException
 * @throws IOException
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (isDebug) {
        log.debug("Enter: doGet()");

    }
    PrintWriter writer = new FilterPrintWriter(response);

    try {
        AxisEngine engine = getEngine();
        ServletContext servletContext = getServletConfig().getServletContext();

        String pathInfo = request.getPathInfo();
        String realpath = servletContext.getRealPath(request.getServletPath());
        if (realpath == null) {
            realpath = request.getServletPath();
        }

        //JWS pages are special; they are the servlet path and there
        //is no pathinfo...we map the pathinfo to the servlet path to keep
        //it happy
        boolean isJWSPage = request.getRequestURI().endsWith(".jws");
        if (isJWSPage) {
            pathInfo = request.getServletPath();
        }

        // Try to execute a query string plugin and return upon success.

        if (processQuery(request, response, writer) == true) {
            return;
        }

        boolean hasNoPath = (pathInfo == null || pathInfo.equals(""));
        if (!disableServicesList) {
            if (hasNoPath) {
                // If the user requested the servlet (i.e. /axis/servlet/AxisServlet)
                // with no service name, present the user with a list of deployed
                // services to be helpful
                // Don't do this if has been turned off
                reportAvailableServices(response, writer, request);
            } else if (realpath != null) {
                // We have a pathname, so now we perform WSDL or list operations

                // get message context w/ various properties set
                MessageContext msgContext = createMessageContext(engine, request, response);

                // NOTE:  HttpUtils.getRequestURL has been deprecated.
                // This line SHOULD be:
                //    String url = req.getRequestURL().toString()
                // HOWEVER!!!!  DON'T REPLACE IT!  There's a bug in
                // req.getRequestURL that is not in HttpUtils.getRequestURL
                // req.getRequestURL returns "localhost" in the remote
                // scenario rather than the actual host name.
                //
                // But more importantly, getRequestURL() is a servlet 2.3
                // API and to support servlet 2.2 (aka WebSphere 4)
                // we need to leave this in for a while longer. tomj 10/14/2004
                //
                String url = HttpUtils.getRequestURL(request).toString();

                msgContext.setProperty(MessageContext.TRANS_URL, url);

                // See if we can locate the desired service.  If we
                // can't, return a 404 Not Found.  Otherwise, just
                // print the placeholder message.

                String serviceName;
                if (pathInfo.startsWith("/")) {
                    serviceName = pathInfo.substring(1);
                } else {
                    serviceName = pathInfo;
                }

                SOAPService s = engine.getService(serviceName);
                if (s == null) {
                    //no service: report it
                    if (isJWSPage) {
                        reportCantGetJWSService(request, response, writer);
                    } else {
                        reportCantGetAxisService(request, response, writer);
                    }

                } else {
                    //print a snippet of service info.
                    reportServiceInfo(response, writer, s, serviceName);
                }
            }
        } else {
            // We didn't have a real path in the request, so just
            // print a message informing the user that they reached
            // the servlet.

            response.setContentType("text/html; charset=utf-8");
            writer.println("<html><h1>Axis HTTP Servlet</h1>");
            writer.println(Messages.getMessage("reachedServlet00"));

            writer.println("<p>" + Messages.getMessage("transportName00", "<b>" + transportName + "</b>"));
            writer.println("</html>");
        }
    } catch (AxisFault fault) {
        reportTroubleInGet(fault, response, writer);
    } catch (Exception e) {
        reportTroubleInGet(e, response, writer);
    } finally {
        writer.close();
        if (isDebug) {
            log.debug("Exit: doGet()");
        }
    }
}

From source file:org.apache.axis.transport.http.AxisServlet.java

/**
 * Process a POST to the servlet by handing it off to the Axis Engine.
 * Here is where SOAP messages are received
 * @param req posted request/*from w  ww .  j  a  v a  2 s. com*/
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;
    if (isDebug) {
        log.debug("Enter: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }

    Message responseMsg = null;
    String contentType = null;

    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            log.debug("No Engine!", se);
            throw se;
        }

        res.setBufferSize(1024 * 8); // provide performance boost.

        /** get message context w/ various properties set
         */
        msgContext = createMessageContext(engine, req, res);

        // ? OK to move this to 'getMessageContext',
        // ? where it would also be picked up for 'doGet()' ?
        if (securityProvider != null) {
            if (isDebug) {
                log.debug("securityProvider:" + securityProvider);
            }
            msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider);
        }

        /* Get request message
         */
        Message requestMsg = new Message(req.getInputStream(), false,
                req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
        // Transfer HTTP headers to MIME headers for request message.
        MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements();) {
                String headerValue = (String) f.nextElement();
                requestMimeHeaders.addHeader(headerName, headerValue);
            }
        }

        if (isDebug) {
            log.debug("Request Message:" + requestMsg);

            /* Set the request(incoming) message field in the context */
            /**********************************************************/
        }
        msgContext.setRequestMessage(requestMsg);
        String url = HttpUtils.getRequestURL(req).toString();
        msgContext.setProperty(MessageContext.TRANS_URL, url);
        // put character encoding of request to message context
        // in order to reuse it during the whole process.
        String requestEncoding;
        try {
            requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (requestEncoding != null) {
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
            }
        } catch (SOAPException e1) {
        }

        try {
            /**
             * Save the SOAPAction header in the MessageContext bag.
             * This will be used to tell the Axis Engine which service
             * is being invoked.  This will save us the trouble of
             * having to parse the Request message - although we will
             * need to double-check later on that the SOAPAction header
             * does in fact match the URI in the body.
             */
            // (is this last stmt true??? (I don't think so - Glen))
            /********************************************************/
            soapAction = getSoapAction(req);

            if (soapAction != null) {
                msgContext.setUseSOAPAction(true);
                msgContext.setSOAPActionURI(soapAction);
            }

            // Create a Session wrapper for the HTTP session.
            // These can/should be pooled at some point.
            // (Sam is Watching! :-)
            msgContext.setSession(new AxisHttpSession(req));

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }
            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug) {
                log.debug("Invoking Axis Engine.");
                //here we run the message by the engine
            }
            engine.invoke(msgContext);
            if (isDebug) {
                log.debug("Return from Axis Engine.");
            }
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }
            responseMsg = msgContext.getResponseMessage();

            // We used to throw exceptions on null response messages.
            // They are actually OK in certain situations (asynchronous
            // services), so fall through here and return an ACCEPTED
            // status code below.  Might want to install a configurable
            // error check for this later.
        } catch (AxisFault fault) {
            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(fault);
                ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage()
                        .setMessageContext(msgContext);
            }
        } catch (Exception e) {
            //other exceptions are internal trouble
            responseMsg = msgContext.getResponseMessage();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            responseMsg = convertExceptionToAxisFault(e, responseMsg);
            ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        } catch (Throwable t) {
            logException(t);
            //other exceptions are internal trouble
            responseMsg = msgContext.getResponseMessage();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            responseMsg = new Message(new AxisFault(t.toString(), t));
            ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    } catch (AxisFault fault) {
        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        responseMsg = msgContext.getResponseMessage();
        if (responseMsg == null) {
            responseMsg = new Message(fault);
            ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    }

    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    /* Send response back along the wire...  */
    /***********************************/
    if (responseMsg != null) {
        // Transfer MIME headers to HTTP headers for response message.
        MimeHeaders responseMimeHeaders = responseMsg.getMimeHeaders();
        for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader responseMimeHeader = (MimeHeader) i.next();
            res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue());
        }
        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null) {
            try {
                responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
            } catch (SOAPException e) {
            }
        }
        //determine content type from message response
        contentType = responseMsg.getContentType(msgContext.getSOAPConstants());
        sendResponse(contentType, res, responseMsg);
    } else {
        // No content, so just indicate accepted
        res.setStatus(202);
    }

    if (isDebug) {
        log.debug("Response sent.");
        log.debug("Exit: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post="
                + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "."
                + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName()));
    }

}

From source file:org.apache.axis.transport.http.AxisServlet.java

/**
 * Attempts to invoke a plugin for the query string supplied in the URL.
 *
 * @param request the servlet's HttpServletRequest object.
 * @param response the servlet's HttpServletResponse object.
 * @param writer the servlet's PrintWriter object.
 *//*from w  w  w  .  ja v a  2s  . c  om*/

private boolean processQuery(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
        throws AxisFault {
    // Attempt to instantiate a plug-in handler class for the query string
    // handler classes defined in the HTTP transport.

    String path = request.getServletPath();
    String queryString = request.getQueryString();
    String serviceName;
    AxisEngine engine = getEngine();
    Iterator i = this.transport.getOptions().keySet().iterator();

    if (queryString == null) {
        return false;
    }

    String servletURI = request.getContextPath() + path;
    String reqURI = request.getRequestURI();
    // chop off '/'.
    if (servletURI.length() + 1 < reqURI.length()) {
        serviceName = reqURI.substring(servletURI.length() + 1);
    } else {
        serviceName = "";
    }
    while (i.hasNext() == true) {
        String queryHandler = (String) i.next();

        if (queryHandler.startsWith("qs.") == true) {
            // Only attempt to match the query string with transport
            // parameters prefixed with "qs:".

            String handlerName = queryHandler.substring(queryHandler.indexOf(".") + 1).toLowerCase();

            // Determine the name of the plugin to invoke by using all text
            // in the query string up to the first occurence of &, =, or the
            // whole string if neither is present.

            int length = 0;
            boolean firstParamFound = false;

            while (firstParamFound == false && length < queryString.length()) {
                char ch = queryString.charAt(length++);

                if (ch == '&' || ch == '=') {
                    firstParamFound = true;

                    --length;
                }
            }

            if (length < queryString.length()) {
                queryString = queryString.substring(0, length);
            }

            if (queryString.toLowerCase().equals(handlerName) == true) {
                // Query string matches a defined query string handler name.

                // If the defined class name for this query string handler is blank,
                // just return (the handler is "turned off" in effect).

                if (this.transport.getOption(queryHandler).equals("")) {
                    return false;
                }

                try {
                    // Attempt to dynamically load the query string handler
                    // and its "invoke" method.

                    MessageContext msgContext = createMessageContext(engine, request, response);
                    Class plugin = Class.forName((String) this.transport.getOption(queryHandler));
                    Method pluginMethod = plugin.getDeclaredMethod("invoke",
                            new Class[] { msgContext.getClass() });
                    String url = HttpUtils.getRequestURL(request).toString();

                    // Place various useful servlet-related objects in
                    // the MessageContext object being delivered to the
                    // plugin.
                    msgContext.setProperty(MessageContext.TRANS_URL, url);
                    msgContext.setProperty(HTTPConstants.PLUGIN_SERVICE_NAME, serviceName);
                    msgContext.setProperty(HTTPConstants.PLUGIN_NAME, handlerName);
                    msgContext.setProperty(HTTPConstants.PLUGIN_IS_DEVELOPMENT, new Boolean(isDevelopment()));
                    msgContext.setProperty(HTTPConstants.PLUGIN_ENABLE_LIST, new Boolean(enableList));
                    msgContext.setProperty(HTTPConstants.PLUGIN_ENGINE, engine);
                    msgContext.setProperty(HTTPConstants.PLUGIN_WRITER, writer);
                    msgContext.setProperty(HTTPConstants.PLUGIN_LOG, log);
                    msgContext.setProperty(HTTPConstants.PLUGIN_EXCEPTION_LOG, exceptionLog);

                    // Invoke the plugin.

                    pluginMethod.invoke(plugin.newInstance(), new Object[] { msgContext });

                    writer.close();

                    return true;
                } catch (InvocationTargetException ie) {
                    reportTroubleInGet(ie.getTargetException(), response, writer);
                    // return true to prevent any further processing
                    return true;
                } catch (Exception e) {
                    reportTroubleInGet(e, response, writer);
                    // return true to prevent any further processing
                    return true;
                }
            }
        }
    }

    return false;
}

From source file:org.josso.agent.http.HttpSSOAgent.java

/**
 * This method builds the back_to URL value pointing to the given URI.
 * <p/>//from w  ww .j  a v a  2s  .com
 * The determines the host used to build the back_to URL in the following order :
 * <p/>
 * First, checks the singlePointOfAccess agent's configuration property.
 * Then checks the reverse-proxy-host HTTP header value from the request.
 * Finally uses current host name.
 */
public String buildBackToURL(HttpServletRequest hreq, String uri) {
    String backto = null;

    // Build the back to url.
    String contextPath = hreq.getContextPath();

    // This is the root context
    if (contextPath == null || "".equals(contextPath))
        contextPath = "/";

    String reverseProxyHost = hreq.getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
    String singlePointOfAccess = getSinglePointOfAccess();

    if (singlePointOfAccess != null) {
        // Using single-point of access configuration.
        if (debug >= 1)
            log("josso_back_to option : singlePointOfAccess: " + singlePointOfAccess);
        backto = singlePointOfAccess + contextPath + uri;

    } else if (reverseProxyHost != null) {
        // Using reverse proxy host header.
        if (debug >= 1)
            log("josso_back_to option : reverse-proxy-host: " + reverseProxyHost);
        backto = reverseProxyHost + contextPath + uri;

    } else {
        // Using default host
        StringBuffer mySelf = HttpUtils.getRequestURL(hreq);

        try {
            java.net.URL url = new java.net.URL(mySelf.toString());
            backto = url.getProtocol() + "://" + url.getHost()
                    + ((url.getPort() > 0) ? ":" + url.getPort() : "");
        } catch (java.net.MalformedURLException e) {
            throw new RuntimeException(e);
        }

        backto += (contextPath.endsWith("/") ? contextPath.substring(0, contextPath.length() - 1) : contextPath)
                + uri;

    }

    if (debug >= 1)
        log("Using josso_back_to : " + backto);

    return backto;
}

From source file:ORG.oclc.oai.server.verb.ListErrors.java

public static String construct(HashMap context, HttpServletRequest request, HttpServletResponse response,
        Transformer serverTransformer) throws OAIInternalServerError, TransformerException {
    Properties properties = (Properties) context.get("OAIHandler.properties");
    AbstractCatalog abstractCatalog = (AbstractCatalog) context.get("OAIHandler.catalog");
    boolean xmlEncodeSetSpec = "true".equalsIgnoreCase(properties.getProperty("OAIHandler.xmlEncodeSetSpec"));
    boolean urlEncodeSetSpec = !"false".equalsIgnoreCase(properties.getProperty("OAIHandler.urlEncodeSetSpec"));
    String baseURL = properties.getProperty("OAIHandler.baseURL");
    if (baseURL == null) {
        try {//from   w ww .  j a v  a  2 s  .  co  m
            baseURL = request.getRequestURL().toString();
        } catch (java.lang.NoSuchMethodError f) {
            baseURL = HttpUtils.getRequestURL(request).toString();
        }
    }
    StringBuffer sb = new StringBuffer();
    String oldResumptionToken = request.getParameter("resumptionToken");
    // String metadataPrefix = request.getParameter("metadataPrefix");

    // if (metadataPrefix != null && metadataPrefix.length() == 0) {
    // metadataPrefix = null;
    // }

    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
    String styleSheet = properties.getProperty("OAIHandler.styleSheet");
    if (styleSheet != null) {
        sb.append("<?xml-stylesheet type=\"text/xsl\" href=\"");
        sb.append(styleSheet);
        sb.append("\"?>");
    }
    sb.append("<OAI-PMH xmlns=\"http://www.openarchives.org/OAI/2.0/\"");
    sb.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
    sb.append(" xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/");
    sb.append(" http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd\">");
    sb.append("<responseDate>");
    sb.append(createResponseDate(new Date()));
    sb.append("</responseDate>");
    // sb.append("<requestURL>");
    // sb.append(getRequestURL(request));
    // sb.append("</requestURL>");

    if (!abstractCatalog.isHarvestable()) {
        sb.append("<request verb=\"ListErrors\">");
        sb.append(baseURL);
        sb.append("</request>");
        sb.append("<error code=\"badArgument\">Database is unavailable for harvesting</error>");
    } else {
        ArrayList validParamNames = null;
        ArrayList requiredParamNames = null;
        Map ListErrorsMap = null;
        if (oldResumptionToken == null) {
            validParamNames = validParamNames1;
            requiredParamNames = requiredParamNames1;
            String identifier = request.getParameter("identifier");
            String from = StringUtils.defaultString(request.getParameter("from")).trim();
            String until = StringUtils.defaultString(request.getParameter("until")).trim();
            try {
                if (from.length() > 0 && from.length() < 10) {
                    throw new BadArgumentException();
                }
                if (until.length() > 0 && until.length() < 10) {
                    throw new BadArgumentException();
                }
                if (from.length() == 0) {
                    from = "0001-01-01";
                }
                if (until.length() == 0) {
                    until = "9999-12-31";
                }
                from = abstractCatalog.toFinestFrom(from);
                until = abstractCatalog.toFinestUntil(until);
                if (from.compareTo(until) > 0) {
                    throw new BadArgumentException();
                }
                String set = request.getParameter("set");
                if (set != null) {
                    if (set.length() == 0) {
                        set = null;
                    } else if (urlEncodeSetSpec) {
                        set = set.replace(' ', '+');
                    }
                }
                Crosswalks crosswalks = abstractCatalog.getCrosswalks();
                // if (metadataPrefix == null) {
                // throw new BadArgumentException();
                // }

                // if (!crosswalks.containsValue(metadataPrefix)) {
                // throw new CannotDisseminateFormatException(metadataPrefix);
                // }
                // else {
                ListErrorsMap = abstractCatalog.listErrors(from, until, identifier, set);
                // }
            } catch (NoItemsMatchException e) {
                sb.append(getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            } catch (BadArgumentException e) {
                sb.append("<request verb=\"ListErrors\">");
                // sb.append(HttpUtils.getRequestURL(request));
                sb.append(baseURL);
                sb.append("</request>");
                sb.append(e.getMessage());
                // } catch (BadGranularityException e) {
                // sb.append(getRequestElement(request));
                // sb.append(e.getMessage());
            } catch (CannotDisseminateFormatException e) {
                sb.append(getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            } catch (NoSetHierarchyException e) {
                sb.append(getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            }
        } else {
            validParamNames = validParamNames2;
            requiredParamNames = requiredParamNames2;
            if (hasBadArguments(request, requiredParamNames.iterator(), validParamNames)) {
                sb.append(getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(new BadArgumentException().getMessage());
            } else {
                try {
                    ListErrorsMap = abstractCatalog.listErrors(oldResumptionToken);
                } catch (BadResumptionTokenException e) {
                    sb.append(getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                    sb.append(e.getMessage());
                }
            }
        }

        if (ListErrorsMap != null) {
            sb.append(getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
            if (hasBadArguments(request, requiredParamNames.iterator(), validParamNames)) {
                sb.append(new BadArgumentException().getMessage());
            } else {
                sb.append("<ListErrors>");
                Iterator errors = (Iterator) ListErrorsMap.get("errors");
                while (errors.hasNext()) {
                    sb.append((String) errors.next());
                    sb.append("\n");
                }

                Map newResumptionMap = (Map) ListErrorsMap.get("resumptionMap");
                if (newResumptionMap != null) {
                    String newResumptionToken = (String) newResumptionMap.get("resumptionToken");
                    String expirationDate = (String) newResumptionMap.get("expirationDate");
                    String completeListSize = (String) newResumptionMap.get("completeListSize");
                    String cursor = (String) newResumptionMap.get("cursor");
                    sb.append("<resumptionToken");
                    if (expirationDate != null) {
                        sb.append(" expirationDate=\"");
                        sb.append(expirationDate);
                        sb.append("\"");
                    }
                    if (completeListSize != null) {
                        sb.append(" completeListSize=\"");
                        sb.append(completeListSize);
                        sb.append("\"");
                    }
                    if (cursor != null) {
                        sb.append(" cursor=\"");
                        sb.append(cursor);
                        sb.append("\"");
                    }
                    sb.append(">");
                    sb.append(newResumptionToken);
                    sb.append("</resumptionToken>");
                } else if (oldResumptionToken != null) {
                    sb.append("<resumptionToken />");
                }
                sb.append("</ListErrors>");
            }
        }
    }
    sb.append("</OAI-PMH>");
    if (debug) {
        System.out.println("ListErrors.construct: returning: " + sb.toString());
    }
    return render(response, "text/xml; charset=UTF-8", sb.toString(), serverTransformer);
}

From source file:ORG.oclc.oai.server.verb.ListIdentifiers.java

public static String construct(final HashMap context, final HttpServletRequest request,
        final HttpServletResponse response, final Transformer serverTransformer)
        throws OAIInternalServerError, TransformerException {
    Properties properties = (Properties) context.get("OAIHandler.properties");
    AbstractCatalog abstractCatalog = (AbstractCatalog) context.get("OAIHandler.catalog");
    boolean xmlEncodeSetSpec = "true".equalsIgnoreCase(properties.getProperty("OAIHandler.xmlEncodeSetSpec"));
    boolean urlEncodeSetSpec = !"false".equalsIgnoreCase(properties.getProperty("OAIHandler.urlEncodeSetSpec"));
    String baseURL = properties.getProperty("OAIHandler.baseURL");
    if (baseURL == null) {
        try {// ww w .java  2s  .  c  o m
            baseURL = request.getRequestURL().toString();
        } catch (java.lang.NoSuchMethodError f) {
            baseURL = HttpUtils.getRequestURL(request).toString();
        }
    }
    StringBuffer sb = new StringBuffer();
    String oldResumptionToken = request.getParameter("resumptionToken");
    String metadataPrefix = request.getParameter("metadataPrefix");

    if (metadataPrefix != null && metadataPrefix.length() == 0) {
        metadataPrefix = null;
    }

    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
    String styleSheet = properties.getProperty("OAIHandler.styleSheet");
    if (styleSheet != null) {
        sb.append("<?xml-stylesheet type=\"text/xsl\" href=\"");
        sb.append(styleSheet);
        sb.append("\"?>");
    }
    sb.append("<OAI-PMH xmlns=\"http://www.openarchives.org/OAI/2.0/\"");
    sb.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
    sb.append(" xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/");
    sb.append(" http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd\">");
    sb.append("<responseDate>");
    sb.append(ServerVerb.createResponseDate(new Date()));
    sb.append("</responseDate>");
    // sb.append("<requestURL>");
    // sb.append(getRequestURL(request));
    // sb.append("</requestURL>");

    if (!abstractCatalog.isHarvestable()) {
        sb.append("<request verb=\"ListIdentifiers\">");
        sb.append(baseURL);
        sb.append("</request>");
        sb.append("<error code=\"badArgument\">Database is unavailable for harvesting</error>");
    } else {
        ArrayList validParamNames = null;
        ArrayList requiredParamNames = null;
        Map listIdentifiersMap = null;
        if (oldResumptionToken == null) {
            validParamNames = validParamNames1;
            requiredParamNames = requiredParamNames1;
            String from = StringUtils.defaultString(request.getParameter("from")).trim();
            String until = StringUtils.defaultString(request.getParameter("until")).trim();
            try {
                if (from.length() > 0 && from.length() < 10) {
                    throw new BadArgumentException();
                }
                if (until.length() > 0 && until.length() < 10) {
                    throw new BadArgumentException();
                }
                from = abstractCatalog.toFinestFrom(from);
                until = abstractCatalog.toFinestUntil(until);
                if (!StringUtils.isEmpty(from) && !StringUtils.isEmpty(until) && from.compareTo(until) > 0) {
                    throw new BadArgumentException();
                }
                String set = request.getParameter("set");
                if (set != null) {
                    if (set.length() == 0) {
                        set = null;
                    } else if (urlEncodeSetSpec) {
                        set = set.replace(' ', '+');
                    }
                }
                Crosswalks crosswalks = abstractCatalog.getCrosswalks();
                if (metadataPrefix == null) {
                    throw new BadArgumentException();
                }

                if (!crosswalks.containsValue(metadataPrefix)) {
                    throw new CannotDisseminateFormatException(metadataPrefix);
                } else {
                    listIdentifiersMap = abstractCatalog.listIdentifiers(from, until, set, metadataPrefix);
                }
            } catch (NoItemsMatchException e) {
                sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            } catch (BadArgumentException e) {
                sb.append("<request verb=\"ListIdentifiers\">");
                // sb.append(HttpUtils.getRequestURL(request));
                sb.append(baseURL);
                sb.append("</request>");
                sb.append(e.getMessage());
                // } catch (BadGranularityException e) {
                // sb.append(getRequestElement(request));
                // sb.append(e.getMessage());
            } catch (CannotDisseminateFormatException e) {
                sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            } catch (NoSetHierarchyException e) {
                sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            }
        } else {
            validParamNames = validParamNames2;
            requiredParamNames = requiredParamNames2;
            if (ServerVerb.hasBadArguments(request, requiredParamNames.iterator(), validParamNames)) {
                sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(new BadArgumentException().getMessage());
            } else {
                try {
                    listIdentifiersMap = abstractCatalog.listIdentifiers(oldResumptionToken);
                } catch (BadResumptionTokenException e) {
                    sb.append(
                            ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                    sb.append(e.getMessage());
                }
            }
        }

        if (listIdentifiersMap != null) {
            sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
            if (ServerVerb.hasBadArguments(request, requiredParamNames.iterator(), validParamNames)) {
                sb.append(new BadArgumentException().getMessage());
            } else {
                sb.append("<ListIdentifiers>");
                Iterator identifiers = (Iterator) listIdentifiersMap.get("headers");
                while (identifiers.hasNext()) {
                    sb.append((String) identifiers.next());
                }

                Map newResumptionMap = (Map) listIdentifiersMap.get("resumptionMap");
                if (newResumptionMap != null) {
                    String newResumptionToken = (String) newResumptionMap.get("resumptionToken");
                    String expirationDate = (String) newResumptionMap.get("expirationDate");
                    String completeListSize = (String) newResumptionMap.get("completeListSize");
                    String cursor = (String) newResumptionMap.get("cursor");
                    sb.append("<resumptionToken");
                    if (expirationDate != null) {
                        sb.append(" expirationDate=\"");
                        sb.append(expirationDate);
                        sb.append("\"");
                    }
                    if (completeListSize != null) {
                        sb.append(" completeListSize=\"");
                        sb.append(completeListSize);
                        sb.append("\"");
                    }
                    if (cursor != null) {
                        sb.append(" cursor=\"");
                        sb.append(cursor);
                        sb.append("\"");
                    }
                    sb.append(">");
                    sb.append(newResumptionToken);
                    sb.append("</resumptionToken>");
                } else if (oldResumptionToken != null) {
                    sb.append("<resumptionToken />");
                }
                sb.append("</ListIdentifiers>");
            }
        }
    }
    sb.append("</OAI-PMH>");
    if (debug) {
        System.out.println("ListIdentifiers.constructListIdentifiers: returning: " + sb.toString());
    }
    return ServerVerb.render(response, "text/xml; charset=UTF-8", sb.toString(), serverTransformer);
}

From source file:ORG.oclc.oai.server.verb.ListRecords.java

/**
 * Server-side method to construct an xml response to a ListRecords verb.
 *//*  w  w  w . j  a v a  2  s.c  o m*/
public static String construct(final HashMap context, final HttpServletRequest request,
        final HttpServletResponse response, final Transformer serverTransformer)
        throws OAIInternalServerError, TransformerException {
    if (debug) {
        System.out.println("ListRecords.construct: entered");
    }

    Properties properties = (Properties) context.get("OAIHandler.properties");
    AbstractCatalog abstractCatalog = (AbstractCatalog) context.get("OAIHandler.catalog");
    boolean xmlEncodeSetSpec = "true".equalsIgnoreCase(properties.getProperty("OAIHandler.xmlEncodeSetSpec"));
    boolean urlEncodeSetSpec = !"false".equalsIgnoreCase(properties.getProperty("OAIHandler.urlEncodeSetSpec"));
    String baseURL = properties.getProperty("OAIHandler.baseURL");
    if (baseURL == null) {
        try {
            baseURL = request.getRequestURL().toString();
        } catch (java.lang.NoSuchMethodError f) {
            baseURL = HttpUtils.getRequestURL(request).toString();
        }
    }
    StringBuffer sb = new StringBuffer();
    String oldResumptionToken = request.getParameter("resumptionToken");
    String metadataPrefix = request.getParameter("metadataPrefix");

    if (metadataPrefix != null && metadataPrefix.length() == 0) {
        metadataPrefix = null;
    }

    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
    String styleSheet = properties.getProperty("OAIHandler.styleSheet");
    if (styleSheet != null) {
        sb.append("<?xml-stylesheet type=\"text/xsl\" href=\"");
        sb.append(styleSheet);
        sb.append("\"?>");
    }
    sb.append("<OAI-PMH xmlns=\"http://www.openarchives.org/OAI/2.0/\"");
    sb.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
    String extraXmlns = properties.getProperty("OAIHandler.extraXmlns");
    if (extraXmlns != null) {
        sb.append(" ").append(extraXmlns);
    }
    sb.append(" xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/");
    sb.append(" http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd\">");
    sb.append("<responseDate>");
    sb.append(ServerVerb.createResponseDate(new Date()));
    sb.append("</responseDate>");
    // sb.append("<requestURL>");
    // sb.append(getRequestURL(request));
    // sb.append("</requestURL>");

    if (!abstractCatalog.isHarvestable()) {
        sb.append("<request verb=\"ListRecords\">");
        sb.append(baseURL);
        sb.append("</request>");
        sb.append("<error code=\"badArgument\">Database is unavailable for harvesting</error>");
    } else {
        // if (debug) {
        // System.gc();
        // System.gc();
        // Runtime rt = Runtime.getRuntime();
        // long freeMemoryK = rt.freeMemory() / 1024;
        // long totalMemoryK = rt.totalMemory() / 1024;
        // System.out.print("ListRecords.construct: " + oldResumptionToken);
        // System.out.print(" freeMemory=" + freeMemoryK / 1024.0 + "M");
        // System.out.print(" of " + totalMemoryK / 1024.0 + "M ");
        // System.out.println("(" + (100 * freeMemoryK) / totalMemoryK + "%)");
        // }

        Map listRecordsMap = null;

        ArrayList validParamNames = null;
        ArrayList requiredParamNames = null;
        if (oldResumptionToken == null) {
            validParamNames = validParamNames1;
            requiredParamNames = requiredParamNames1;
            String from = StringUtils.defaultString(request.getParameter("from")).trim();
            String until = StringUtils.defaultString(request.getParameter("until")).trim();
            try {
                if (from.length() > 0 && from.length() < 10) {
                    throw new BadArgumentException();
                }
                if (until.length() > 0 && until.length() < 10) {
                    throw new BadArgumentException();
                }
                from = abstractCatalog.toFinestFrom(from);
                until = abstractCatalog.toFinestUntil(until);
                if (!StringUtils.isEmpty(from) && !StringUtils.isEmpty(until) && from.compareTo(until) > 0) {
                    throw new BadArgumentException();
                }
                String set = request.getParameter("set");
                if (set != null) {
                    if (set.length() == 0) {
                        set = null;
                    } else if (urlEncodeSetSpec) {
                        set = set.replace(' ', '+');
                    }
                }
                Crosswalks crosswalks = abstractCatalog.getCrosswalks();
                if (metadataPrefix == null) {
                    throw new BadArgumentException();
                }
                if (!crosswalks.containsValue(metadataPrefix)) {
                    throw new CannotDisseminateFormatException(metadataPrefix);
                } else {
                    listRecordsMap = abstractCatalog.listRecords(from, until, set, metadataPrefix);
                }
            } catch (NoItemsMatchException e) {
                sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            } catch (BadArgumentException e) {

                sb.append("<request verb=\"ListRecords\">");
                sb.append(baseURL);
                sb.append("</request>");
                sb.append(e.getMessage());
                // } catch (BadGranularityException e) {
                // sb.append(getRequestElement(request));
                // sb.append(e.getMessage());
            } catch (CannotDisseminateFormatException e) {
                sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            } catch (NoSetHierarchyException e) {
                sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(e.getMessage());
            }
        } else {
            validParamNames = validParamNames2;
            requiredParamNames = requiredParamNames2;
            if (ServerVerb.hasBadArguments(request, requiredParamNames.iterator(), validParamNames)) {
                sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                sb.append(new BadArgumentException().getMessage());
            } else {
                try {
                    listRecordsMap = abstractCatalog.listRecords(oldResumptionToken);
                } catch (BadResumptionTokenException e) {
                    sb.append(
                            ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
                    sb.append(e.getMessage());
                }
            }
        }
        if (listRecordsMap != null) {
            sb.append(ServerVerb.getRequestElement(request, validParamNames, baseURL, xmlEncodeSetSpec));
            if (ServerVerb.hasBadArguments(request, requiredParamNames.iterator(), validParamNames)) {
                sb.append(new BadArgumentException().getMessage());
            } else {
                sb.append("<ListRecords>\n");
                Iterator records = (Iterator) listRecordsMap.get("records");
                while (records.hasNext()) {
                    sb.append((String) records.next());
                    sb.append("\n");
                }
                Map newResumptionMap = (Map) listRecordsMap.get("resumptionMap");
                if (newResumptionMap != null) {
                    String newResumptionToken = (String) newResumptionMap.get("resumptionToken");
                    String expirationDate = (String) newResumptionMap.get("expirationDate");
                    String completeListSize = (String) newResumptionMap.get("completeListSize");
                    String cursor = (String) newResumptionMap.get("cursor");
                    sb.append("<resumptionToken");
                    if (expirationDate != null) {
                        sb.append(" expirationDate=\"");
                        sb.append(expirationDate);
                        sb.append("\"");
                    }
                    if (completeListSize != null) {
                        sb.append(" completeListSize=\"");
                        sb.append(completeListSize);
                        sb.append("\"");
                    }
                    if (cursor != null) {
                        sb.append(" cursor=\"");
                        sb.append(cursor);
                        sb.append("\"");
                    }
                    sb.append(">");
                    sb.append(newResumptionToken);
                    sb.append("</resumptionToken>");
                } else if (oldResumptionToken != null) {
                    sb.append("<resumptionToken />");
                }
                sb.append("</ListRecords>");
            }
        }
    }
    sb.append("</OAI-PMH>");
    if (debug) {
        System.out.println("ListRecords.constructListRecords: returning: " + sb.toString());
    }
    return ServerVerb.render(response, "text/xml; charset=UTF-8", sb.toString(), serverTransformer);
}