Example usage for javax.servlet.http HttpServlet service

List of usage examples for javax.servlet.http HttpServlet service

Introduction

In this page you can find the example usage for javax.servlet.http HttpServlet service.

Prototype

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException 

Source Link

Document

Dispatches client requests to the protected service method.

Usage

From source file:fi.okm.mpass.idp.authn.impl.SocialUserOpenIdConnectStartServletTest.java

/**
 * Runs the given servlet with given request and response objects.
 * @param httpServlet/*from   w  ww.ja  v  a 2 s.  c o m*/
 * @param httpRequest
 * @param httpResponse
 * @return True if {@link ServletException} is thrown, false otherwise.
 * @throws IOException
 */
protected static boolean runService(HttpServlet httpServlet, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) throws IOException {
    boolean catched = false;
    try {
        httpServlet.service(httpRequest, httpResponse);
    } catch (ServletException e) {
        catched = true;
    }
    return catched;
}

From source file:cc.kune.core.server.rack.filters.servlet.ServletServiceFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    log.debug("SERVICE: " + RackHelper.getURI(request) + " - " + servletClass.getSimpleName());
    final HttpServlet servlet = getInstance(servletClass);
    servlet.service(request, response);
}

From source file:edu.mayo.cts2.framework.webapp.rest.osgi.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    HttpServlet dispatcher = (HttpServlet) this.tracker.getService();
    if (dispatcher != null) {
        dispatcher.service(req, res);
    } else {//from   w w  w. j a va  2  s .c  o  m
        res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
}

From source file:info.magnolia.module.templating.renderers.ServletTemplateRenderer.java

/**
 * @see JspTemplateRenderer#renderTemplate(Template, HttpServletRequest, HttpServletResponse)
 *///  w  w w. ja v  a  2  s. c  o  m
public void renderTemplate(Template template, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String className = template.getParameter("className");

    if (className == null) {
        // className not set, simply use path and forward this request
        super.renderTemplate(template, request, response);
        return;
    }

    // use className
    HttpServlet servlet;
    try {
        servlet = (HttpServlet) Class.forName(className).newInstance();
    } catch (Exception e) {
        // simply retrow to the client for now...
        throw new NestableRuntimeException(e);
    }

    servlet.service(request, response);

}

From source file:com.qwazr.webapps.transaction.ControllerManager.java

private void handleJavaClass(WebappTransaction transaction, String className) throws IOException,
        InterruptedException, ScriptException, ReflectiveOperationException, ServletException {
    final Class<? extends HttpServlet> servletClass = ClassLoaderUtils.findClass(ClassLoaderManager.classLoader,
            className);/*from w w w  . j a  v  a 2  s.c om*/
    Objects.requireNonNull(servletClass, "Class not found: " + className);
    final ServletInfo servletInfo = new ServletInfo(className, servletClass);
    servletInfo.getInstanceFactory().createInstance();
    HttpServlet servlet = servletMap.getOrCreate(servletClass, new Supplier() {
        @Override
        public HttpServlet get() {
            try {
                HttpServlet servlet = servletClass.newInstance();
                WebServlet webServlet = AnnotationsUtils.getFirstAnnotation(servletClass, WebServlet.class);
                servlet.init(new ServletConfigImpl(servletInfo, transaction.getRequest().getServletContext()));
                LibraryManager.inject(servlet);
                return servlet;
            } catch (InstantiationException | IllegalAccessException | ServletException e) {
                throw new RuntimeException(e);
            }
        }
    });
    servlet.service(transaction.getRequest(), transaction.getResponse());
}

From source file:com.google.gwt.dev.shell.GWTShellServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    TreeLogger logger = getLogger();//from   w  w  w .j a  v a  2s.c  o  m
    int id = allocateRequestId();
    if (logger.isLoggable(TreeLogger.TRACE)) {
        StringBuffer url = request.getRequestURL();

        // Branch the logger in case we decide to log more below.
        logger = logger.branch(TreeLogger.TRACE, "Request " + id + ": " + url, null);
    }

    String servletClassName = null;
    ModuleDef moduleDef = null;

    try {
        // Attempt to split the URL into module/path, which we'll use to see
        // if we can map the request to a module's servlet.
        RequestParts parts = new RequestParts(request);

        if ("favicon.ico".equalsIgnoreCase(parts.moduleName)) {
            sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND, "Icon not available");
            return;
        }

        // See if the request references a module we know.
        moduleDef = getModuleDef(logger, parts.moduleName);
        if (moduleDef != null) {
            // Okay, we know this module. Do we know this servlet path?
            // It is right to prepend the slash because (1) ModuleDefSchema requires
            // every servlet path to begin with a slash and (2) RequestParts always
            // rips off the leading slash.
            String servletPath = "/" + parts.partialPath;
            servletClassName = moduleDef.findServletForPath(servletPath);

            // Fall-through below, where we check servletClassName.
        } else {
            // Fall-through below, where we check servletClassName.
        }
    } catch (UnableToCompleteException e) {
        // Do nothing, since it was speculative anyway.
    }

    // BEGIN BACKWARD COMPATIBILITY
    if (servletClassName == null) {
        // Try to map a bare path that isn't preceded by the module name.
        // This is no longer the recommended practice, so we warn.
        String path = request.getPathInfo();
        moduleDef = modulesByServletPath.get(path);
        if (moduleDef != null) {
            // See if there is a servlet we can delegate to for the given url.
            servletClassName = moduleDef.findServletForPath(path);

            if (servletClassName != null) {
                TreeLogger branch = logger.branch(TreeLogger.WARN,
                        "Use of deprecated hosted mode servlet path mapping", null);
                branch.log(TreeLogger.WARN,
                        "The client code is invoking the servlet with a URL that is not module-relative: "
                                + path,
                        null);
                branch.log(TreeLogger.WARN,
                        "Prepend GWT.getModuleBaseURL() to the URL in client code to create a module-relative URL: /"
                                + moduleDef.getName() + path,
                        null);
                branch.log(TreeLogger.WARN,
                        "Using module-relative URLs ensures correct URL-independent behavior in external servlet containers",
                        null);
            }

            // Fall-through below, where we check servletClassName.
        } else {
            // Fall-through below, where we check servletClassName.
        }
    }
    // END BACKWARD COMPATIBILITY

    // Load/get the servlet if we found one.
    if (servletClassName != null) {
        HttpServlet delegatee = tryGetOrLoadServlet(logger, moduleDef, servletClassName);
        if (delegatee == null) {
            logger.log(TreeLogger.ERROR, "Unable to dispatch request", null);
            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Unable to find/load mapped servlet class '" + servletClassName + "'");
            return;
        }

        // Delegate everything to the downstream servlet and we're done.
        delegatee.service(request, response);
    } else {
        // Use normal default processing on this request, since we couldn't
        // recognize it as anything special.
        super.service(request, response);
    }
}

From source file:net.jawr.web.bundle.processor.BundleProcessor.java

/**
 * Create the bundle file// w  w  w .  j  av  a  2 s. c  o  m
 * 
 * @param servlet
 *            the servlet
 * @param response
 *            the response
 * @param request
 *            the request
 * @param path
 *            the path
 * @param destFile
 *            the destination file
 * @param mapping
 *            the mapping
 * @throws IOException
 *             if an IO exception occurs
 * @throws ServletException
 *             if an exception occurs
 */
protected void createBundleFile(HttpServlet servlet, MockServletResponse response, MockServletRequest request,
        String path, File destFile, String mapping) throws IOException, ServletException {

    request.setRequestPath(mapping, path);

    // Create the parent directory of the destination file
    if (!destFile.getParentFile().exists()) {
        boolean dirsCreated = destFile.getParentFile().mkdirs();
        if (!dirsCreated) {
            throw new IOException(
                    "The directory '" + destFile.getParentFile().getCanonicalPath() + "' can't be created.");
        }
    }

    // Set the response mock to write in the destination file
    try {
        response.setOutputStream(new FileOutputStream(destFile));
        servlet.service(request, response);
    } finally {
        response.close();
    }

    if (destFile.length() == 0) {
        logger.warn("No content retrieved for file '" + destFile.getAbsolutePath()
                + "', which is associated to the path : " + path);
        System.out.println("No content retrieved for file '" + destFile.getAbsolutePath()
                + "', which is associated to the path : " + path);
    }
}

From source file:com.web.server.WebServer.java

/**
 * This method obtains the content executor which executes the executor services
 * @param deployDirectory//w w w.  j av a  2s  . co m
 * @param resource
 * @param httpHeaderClient
 * @param serverdigester
 * @return byte[]
 */
public byte[] ObtainContentExecutor(String deployDirectory, String resource, HttpHeaderClient httpHeaderClient,
        Digester serverdigester, Hashtable urlClassLoaderMap, ConcurrentHashMap servletMapping,
        com.web.server.HttpSessionServer session) {
    //System.out.println("In content Executor");
    String[] resourcepath = resource.split("/");
    //System.out.println("createDigester1");
    Method method = null;
    //System.out.println("createDigester2");
    ////System.out.println();
    com.web.server.Executors serverconfig;
    if (resourcepath.length > 1) {
        ////System.out.println(resource);

        try {
            ClassLoader oldCL = null;
            String urlresource = ObtainUrlFromResource(resourcepath);
            try {
                //System.out.println(servletMapping);
                //System.out.println(deployDirectory+"/"+resourcepath[1]);
                HttpSessionServer httpSession;
                logger.info(deployDirectory + "/" + resourcepath[1] + " "
                        + servletMapping.get(deployDirectory + "/" + resourcepath[1]));
                if (servletMapping.get(deployDirectory + "/" + resourcepath[1]) != null) {
                    WebAppConfig webAppConfig = (WebAppConfig) servletMapping
                            .get(deployDirectory + "/" + resourcepath[1]);
                    webAppConfig = webAppConfig.clone();
                    webAppConfig.setWebApplicationAbsolutePath(deployDirectory + "/" + resourcepath[1]);
                    WebClassLoader customClassLoader = null;
                    Class customClass = null;
                    customClassLoader = (WebClassLoader) urlClassLoaderMap
                            .get(deployDirectory + "/" + resourcepath[1]);
                    oldCL = Thread.currentThread().getContextClassLoader();
                    Thread.currentThread().setContextClassLoader(customClassLoader);
                    ConcurrentHashMap servletMappingsURL = webAppConfig.getServletMappingURL();
                    Enumeration urlPattern = servletMappingsURL.keys();
                    while (urlPattern.hasMoreElements()) {
                        String pattern = (String) urlPattern.nextElement();
                        Pattern r = Pattern.compile(pattern.replace("*", "(.*)"));
                        Matcher m = r.matcher(urlresource);
                        if (m.find()) {
                            urlresource = pattern;
                            break;
                        }
                    }
                    LinkedHashMap<String, Vector<FilterMapping>> filterMappings = webAppConfig
                            .getFilterMappingURL();
                    Set<String> filterMappingKeys = filterMappings.keySet();
                    Iterator<String> filterMappingRoller = filterMappingKeys.iterator();
                    Vector<FilterMapping> filterMapping = null;
                    while (filterMappingRoller.hasNext()) {
                        String pattern = (String) filterMappingRoller.next();
                        Pattern r = Pattern.compile(pattern.replace("*", "(.*)"));
                        Matcher m = r.matcher(urlresource);
                        if (m.find()) {
                            filterMapping = filterMappings.get(pattern);
                            break;
                        }
                    }
                    if (servletMappingsURL.get(urlresource) != null) {
                        ServletMapping servletMappings = (ServletMapping) servletMappingsURL.get(urlresource);
                        ConcurrentHashMap servlets = webAppConfig.getServlets();
                        Servlets servlet = (Servlets) servlets.get(servletMappings.getServletName());

                        HttpServlet httpServlet = null;
                        System.out.println("Session " + session);
                        if (session.getAttribute("SERVLETNAME:" + deployDirectory + "/" + resourcepath[1]
                                + servletMappings.getServletName()) != null) {
                            httpServlet = (HttpServlet) session.getAttribute("SERVLETNAME:" + deployDirectory
                                    + "/" + resourcepath[1] + servletMappings.getServletName());
                            httpServlet.init();
                        } else {
                            Class servletClass = customClassLoader.loadClass(servlet.getServletClass());
                            httpServlet = (HttpServlet) servletClass.newInstance();
                            httpServlet.init(new WebServletConfig(servlet.getServletName().trim(), webAppConfig,
                                    customClassLoader));
                            httpServlet.init();
                            session.setAttribute("SERVLETNAME:" + deployDirectory + "/" + resourcepath[1]
                                    + servletMappings.getServletName(), httpServlet);
                            //ClassLoaderUtil.closeClassLoader(customClassLoader);
                        }
                        if (httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("GET")
                                || httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("POST")) {
                            Response response = new Response(httpHeaderClient);
                            StringBuffer servletPath = new StringBuffer();
                            if (resourcepath.length > 1) {
                                int pathcount = 0;
                                for (String servPath : resourcepath) {
                                    if (pathcount > 1) {
                                        servletPath.append("/");
                                        servletPath.append(servPath);
                                    }
                                    pathcount++;
                                }
                            }
                            String servletpath = servletPath.toString();
                            if (servletpath.length() == 0)
                                servletpath = "/";
                            Request request = new Request(httpHeaderClient, session, servletpath,
                                    customClassLoader);
                            if (filterMapping != null) {
                                WebFilterChain webFilterChain = new WebFilterChain(httpServlet, webAppConfig,
                                        filterMapping, customClassLoader);
                                webFilterChain.doFilter(request, response);
                            } else {
                                httpServlet.service(request, response);
                            }

                            //System.out.println("RESPONSE="+new String(response.getResponse()));
                            //httpServlet.destroy();
                            response.flushBuffer();
                            return response.getResponse();
                        }

                        //httpServlet.destroy();
                    } else {
                        if (customClassLoader != null) {
                            Map map = customClassLoader.classMap;
                            if (map.get(urlresource) != null) {
                                Class jspBaseCls = customClassLoader.loadClass((String) map.get(urlresource));
                                HttpJspBase jspBase = (HttpJspBase) jspBaseCls.newInstance();
                                WebServletConfig servletConfig = new WebServletConfig();
                                servletConfig.getServletContext().setAttribute(
                                        "org.apache.tomcat.InstanceManager",
                                        new WebInstanceManager(urlresource));
                                //servletConfig.getServletContext().setAttribute(org.apache.tomcat.InstanceManager, arg1);
                                jspBase.init(servletConfig);
                                jspBase._jspInit();
                                Response response = new Response(httpHeaderClient);
                                StringBuffer servletPath = new StringBuffer();
                                if (resourcepath.length > 1) {
                                    int pathcount = 0;
                                    for (String servPath : resourcepath) {
                                        if (pathcount > 1) {
                                            servletPath.append("/");
                                            servletPath.append(servPath);
                                        }
                                        pathcount++;
                                    }
                                }
                                String servletpath = servletPath.toString();
                                if (servletpath.length() == 0)
                                    servletpath = "/";
                                jspBase._jspService(
                                        new Request(httpHeaderClient, session, servletpath, customClassLoader),
                                        response);
                                jspBase.destroy();
                                response.flushBuffer();
                                return response.getResponse();
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();

            } finally {
                if (oldCL != null) {
                    Thread.currentThread().setContextClassLoader(oldCL);
                }
            }
            File file = new File(deployDirectory + "/" + resourcepath[1] + "/WEB-INF/executor-config.xml");
            if (!file.exists()) {
                return null;
            }
            WebClassLoader customClassLoader = (WebClassLoader) urlClassLoaderMap
                    .get(deployDirectory + "/" + resourcepath[1]);
            Class customClass = null;
            if ((file.isFile() && file.exists())) {
                synchronized (serverdigester) {
                    serverconfig = (com.web.server.Executors) serverdigester.parse(file);
                }
                ConcurrentHashMap urlMap = serverconfig.getExecutorMap();
                //System.out.println("ObtainUrlFromResource1");

                //logger.info("urlresource"+urlresource);
                Executor executor = (Executor) urlMap.get(urlresource);

                //System.out.println("ObtainUrlFromResource2"+executor);
                //System.out.println("custom class Loader1"+urlClassLoaderMap);
                //System.out.println("custom class Loader2"+customClassLoader);                     //System.out.println("CUSTOM CLASS lOADER path"+deployDirectory+"/"+resourcepath[1]);
                ////System.out.println("custom class loader" +customClassLoader);                
                if (executor != null && customClassLoader != null) {
                    customClass = customClassLoader.loadClass(executor.getExecutorclass());
                    ExecutorInterface executorInstance = (ExecutorInterface) customClass.newInstance();
                    Object buffer = null;
                    if (httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("GET")) {
                        buffer = executorInstance.doGet(httpHeaderClient);
                    } else if (httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("POST")) {
                        buffer = executorInstance.doPost(httpHeaderClient);
                    }
                    if (executor.getResponseResource() != null) {
                        httpHeaderClient.setExecutorBuffer(buffer);
                        //System.out.println("Method:"+httpHeaderClient.getHttpMethod());
                        String resourceClass = (String) customClassLoader.getClassMap()
                                .get(executor.getResponseResource().trim());
                        customClass = customClassLoader.loadClass(resourceClass);
                        HttpJspBase jspBase = (HttpJspBase) customClass.newInstance();
                        WebServletConfig servletConfig = new WebServletConfig();
                        servletConfig.getServletContext().setAttribute("org.apache.tomcat.InstanceManager",
                                new WebInstanceManager(urlresource));
                        //servletConfig.getServletContext().setAttribute(org.apache.tomcat.InstanceManager, arg1);
                        jspBase.init(servletConfig);
                        jspBase._jspInit();
                        Response response = new Response(httpHeaderClient);
                        jspBase._jspService(new Request(httpHeaderClient, session, null, customClassLoader),
                                response);
                        jspBase.destroy();
                        response.flushBuffer();
                        return response.getResponse();
                    }
                    return buffer.toString().getBytes();
                }
            } else if (customClassLoader != null) {
                //System.out.println("url resource"+urlresource);
                String resourceClass = (String) customClassLoader.getClassMap().get(urlresource);
                //System.out.println(resourceClass);
                //System.out.println(customClassLoader.getClassMap());
                if (resourceClass == null)
                    return null;
                customClass = customClassLoader.loadClass(resourceClass);
                ExecutorInterface executorInstance = (ExecutorInterface) customClass.newInstance();
                Object buffer = executorInstance.doGet(httpHeaderClient);
                return buffer.toString().getBytes();
            }
            ////System.out.println("executor resource 1");
            //Object buffer = method.invoke(customClass.newInstance(), new Object[]{httpHeaderClient});

            // //logger.info(buffer.toString());

        } catch (IOException | SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } /*catch (InvocationTargetException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          } catch (NoSuchMethodException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          } */catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return null;
}

From source file:org.apache.commons.jci.examples.serverpages.ServerPageServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log("Request " + request.getRequestURI());

    final CompilationResult result = jspListener.getCompilationResult();
    final CompilationProblem[] errors = result.getErrors();

    if (errors.length > 0) {

        // if there are errors we provide the compilation errors instead of the jsp page

        final PrintWriter out = response.getWriter();

        out.append("<html><body>");

        for (CompilationProblem problem : errors) {
            out.append(problem.toString()).append("<br/>").append('\n');
        }//from  w ww  . j a v  a 2  s.  c o m

        out.append("</body></html>");

        out.flush();
        out.close();
        return;
    }

    final String servletClassname = convertRequestToServletClassname(request);

    log("Checking for serverpage " + servletClassname);

    final HttpServlet servlet = servletsByClassname.get(servletClassname);

    if (servlet == null) {
        log("No servlet  for " + request.getRequestURI());
        response.sendError(404);
        return;
    }

    log("Delegating request to " + servletClassname);

    servlet.service(request, response);
}

From source file:org.commoncrawl.server.ServletLauncher.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    ServletRegistry theRegistry = null;// w w w.  j  a  v  a2 s  .c  o  m
    synchronized (this) {
        theRegistry = registry;
        if (theRegistry == null) {
            LOG.info("Querying for Registry");
            String registryClass = getInitParameter(SERVLET_REGISTRY_KEY);
            LOG.info("Registry Class is:" + registryClass);
            if (registryClass != null) {
                try {
                    LOG.info("Loading Registry Class");
                    Class<ServletRegistry> classObject = (Class<ServletRegistry>) Thread.currentThread()
                            .getContextClassLoader().loadClass(registryClass);
                    LOG.info("Instantiating Registry Class");
                    registry = classObject.newInstance();
                    theRegistry = registry;
                } catch (ClassNotFoundException e) {
                    LOG.error(StringUtils.stringifyException(e));
                } catch (InstantiationException e) {
                    LOG.error(StringUtils.stringifyException(e));
                } catch (IllegalAccessException e) {
                    LOG.error(StringUtils.stringifyException(e));
                }

                if (registry == null) {
                    LOG.error("Failed to instantiate reigstry!");
                }
            }
        }
    }

    if (theRegistry != null) {
        HttpServlet servlet = theRegistry.getServletForURI(req.getRequestURI());
        if (servlet != null) {
            LOG.info("Dispatching to servlet:" + servlet.getClass().getCanonicalName());
            servlet.service(req, resp);
        } else {
            Request baseRequest = (Request) req;
            baseRequest.setHandled(false);
            // super.service(req, resp);
        }
    }
}