Search in sources :

Example 66 with ServletConfig

use of javax.servlet.ServletConfig in project atmosphere by Atmosphere.

the class AtmosphereFrameworkTest method testAtmosphereFrameworkListener.

@Test
public void testAtmosphereFrameworkListener() throws ServletException {
    AtmosphereServlet s = new MyAtmosphereServlet();
    final AtomicInteger count = new AtomicInteger();
    s.framework().frameworkListener(new AtmosphereFrameworkListener() {

        @Override
        public void onPreInit(AtmosphereFramework f) {
            count.incrementAndGet();
        }

        @Override
        public void onPostInit(AtmosphereFramework f) {
            count.incrementAndGet();
        }

        @Override
        public void onPreDestroy(AtmosphereFramework f) {
            count.incrementAndGet();
        }

        @Override
        public void onPostDestroy(AtmosphereFramework f) {
            count.incrementAndGet();
        }
    });
    s.init(new ServletConfig() {

        @Override
        public String getServletName() {
            return "void";
        }

        @Override
        public ServletContext getServletContext() {
            return mock(ServletContext.class);
        }

        @Override
        public String getInitParameter(String name) {
            return null;
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return null;
        }
    });
    s.destroy();
    assertEquals(count.get(), 4);
}
Also used : Enumeration(java.util.Enumeration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServletConfig(javax.servlet.ServletConfig) ServletContext(javax.servlet.ServletContext) Test(org.testng.annotations.Test)

Example 67 with ServletConfig

use of javax.servlet.ServletConfig in project atmosphere by Atmosphere.

the class AtmosphereHandlerTest method create.

@BeforeMethod
public void create() throws Throwable {
    framework = new AtmosphereFramework();
    framework.setAsyncSupport(new AsynchronousProcessor(framework.getAtmosphereConfig()) {

        @Override
        public Action service(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
            return suspended(req, res);
        }

        public void action(AtmosphereResourceImpl r) {
            try {
                resumed(r.getRequest(), r.getResponse());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
    }).init(new ServletConfig() {

        @Override
        public String getServletName() {
            return "void";
        }

        @Override
        public ServletContext getServletContext() {
            return mock(ServletContext.class);
        }

        @Override
        public String getInitParameter(String name) {
            return null;
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return null;
        }
    });
}
Also used : ServletException(javax.servlet.ServletException) Enumeration(java.util.Enumeration) ServletConfig(javax.servlet.ServletConfig) ServletContext(javax.servlet.ServletContext) IOException(java.io.IOException) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 68 with ServletConfig

use of javax.servlet.ServletConfig in project zm-mailbox by Zimbra.

the class ZimletResources method service.

@Override
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    if (flushCache(request)) {
        return;
    }
    ZimbraLog.clearContext();
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String uri = req.getRequestURI();
    String pathInfo = req.getPathInfo();
    if (pathInfo == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    @SuppressWarnings("unchecked") Set<String> zimletNames = (Set<String>) req.getAttribute(ZimletFilter.ALLOWED_ZIMLETS);
    Set<String> allZimletNames = (Set<String>) req.getAttribute(ZimletFilter.ALL_ZIMLETS);
    if (!pathInfo.startsWith(RESOURCE_PATH)) {
        // handle requests for individual files included in zimlet in case dev=1 is set.
        ServletContext targetContext = getServletConfig().getServletContext().getContext("/zimlet");
        if (targetContext == null) {
            throw new ServletException("Could not forward the request to zimlet webapp, possible misconfiguration.");
        }
        RequestDispatcher dispatcher = targetContext.getRequestDispatcher(pathInfo);
        dispatcher.forward(req, resp);
        return;
    }
    String contentType = getContentType(uri);
    String type = contentType.replaceAll("^.*/", "");
    boolean debug = req.getParameter(P_DEBUG) != null;
    boolean compress = !debug && supportsGzip && uri.endsWith(COMPRESSED_EXT);
    String cacheId = getCacheId(req, type, zimletNames, allZimletNames);
    if (ZimbraLog.zimlet.isDebugEnabled()) {
        ZimbraLog.zimlet.debug("DEBUG: uri=" + uri);
        ZimbraLog.zimlet.debug("DEBUG: cacheId=" + cacheId);
        ZimbraLog.zimlet.debug("DEBUG: contentType=" + contentType);
        ZimbraLog.zimlet.debug("DEBUG: type=" + type);
    }
    // generate buffer
    File file = !debug ? getCacheFile(cacheId) : null;
    String text = null;
    if (file == null || !file.exists()) {
        StringWriter writer = new StringWriter();
        PrintWriter printer = new PrintWriter(writer);
        // zimlet messages
        if (type.equals(T_JAVASCRIPT)) {
            ServletConfig config = this.getServletConfig();
            ServletContext baseContext = config.getServletContext();
            RequestDispatcher dispatcher = baseContext.getRequestDispatcher(RESOURCE_PATH);
            // NOTE: descriptions can be translated.
            for (String zimletName : allZimletNames) {
                RequestWrapper wrappedReq = new RequestWrapper(req, RESOURCE_PATH + zimletName);
                ResponseWrapper wrappedResp = new ResponseWrapper(resp, printer);
                // bug 45922: avoid cached messages
                wrappedReq.setParameter("debug", "1");
                //this will activate ZimletProps2JsServlet
                dispatcher.include(wrappedReq, wrappedResp);
            }
        }
        // zimlet resources
        if (ZimbraLog.zimlet.isDebugEnabled()) {
            ZimbraLog.zimlet.debug("DEBUG: generating buffer");
        }
        generate(zimletNames, type, printer);
        text = writer.toString();
        // minimize css
        if (type.equals(T_CSS) && !debug) {
            CssCompressor compressor = new CssCompressor(new StringReader(text));
            StringWriter out = new StringWriter();
            compressor.compress(out, 0);
            text = out.toString();
        }
        if (type.equals(T_JAVASCRIPT) && !debug) {
            // compress JS code
            text = text.replaceAll("(^|\n)\\s*DBG\\.\\w+\\(.*\\);\\s*(\n|$)", "\n");
            JavaScriptCompressor compressor = new JavaScriptCompressor(new StringReader(text), new ErrorReporter() {

                @Override
                public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) {
                    if (line < 0) {
                        ZimbraLog.zimlet.warn("\n" + message);
                    } else {
                        ZimbraLog.zimlet.warn("\n" + line + ':' + lineOffset + ':' + message);
                    }
                }

                @Override
                public void error(String message, String sourceName, int line, String lineSource, int lineOffset) {
                    if (line < 0) {
                        ZimbraLog.zimlet.error("\n" + message);
                    } else {
                        ZimbraLog.zimlet.error("\n" + line + ':' + lineOffset + ':' + message);
                    }
                }

                @Override
                public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) {
                    error(message, sourceName, line, lineSource, lineOffset);
                    return new EvaluatorException(message);
                }
            });
            StringWriter out = new StringWriter();
            compressor.compress(out, 0, true, false, false, false);
            String mintext = out.toString();
            if (mintext == null) {
                ZimbraLog.zimlet.info("unable to minimize zimlet JS source");
            } else {
                text = mintext;
            }
        }
        // store buffer
        if (!debug) {
            // NOTE: This assumes that the cacheId will *end* with the compressed
            // NOTE: extension. Therefore, make sure to keep getCacheId in sync.
            String uncompressedCacheId = compress ? cacheId.substring(0, cacheId.length() - COMPRESSED_EXT.length()) : cacheId;
            // store uncompressed file in cache
            file = createCacheFile(uncompressedCacheId, type);
            if (ZimbraLog.zimlet.isDebugEnabled()) {
                ZimbraLog.zimlet.debug("DEBUG: buffer file: " + file);
            }
            copy(text, file);
            putCacheFile(uncompressedCacheId, file);
            // store compressed file in cache
            if (compress) {
                String compressedCacheId = cacheId;
                File gzfile = createCacheFile(compressedCacheId, type + DiskCacheServlet.EXT_COMPRESSED);
                if (ZimbraLog.zimlet.isDebugEnabled()) {
                    ZimbraLog.zimlet.debug("DEBUG: buffer file: " + gzfile);
                }
                file = compress(file, gzfile);
                putCacheFile(compressedCacheId, file);
            }
        }
    } else {
        if (ZimbraLog.zimlet.isDebugEnabled()) {
            ZimbraLog.zimlet.debug("DEBUG: using previous buffer");
        }
    }
    // write buffer
    try {
        // We browser sniff so need to make sure any caches do the same.
        resp.addHeader("Vary", "User-Agent");
        if (file == null || req.getProtocol().endsWith("1.0")) {
            // Bug 20626: We're no longer caching zimlets
            // Set to expire far in the past.
            resp.setHeader("Expires", "Tue, 24 Jan 2000 17:46:50 GMT");
            // Set standard HTTP/1.1 no-cache headers.
            resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
            // Set standard HTTP/1.0 no-cache header.
            resp.setHeader("Pragma", "no-cache");
        } else {
            // force cache revalidation but allow client cache
            resp.setHeader("Cache-Control", "must-revalidate, max-age=0");
            if (file.lastModified() <= req.getDateHeader("If-Modified-Since")) {
                resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
            resp.setDateHeader("Last-Modified", file.lastModified());
        }
        resp.setContentType(contentType);
        if (compress && file != null) {
            resp.setHeader("Content-Encoding", "gzip");
        }
        // NOTE: the contents of the generated file to the stream.
        if (!compress || file != null) {
            resp.setContentLength(file != null ? (int) file.length() : text.getBytes("UTF-8").length);
        }
    } catch (IllegalStateException e) {
        // ignore -- thrown if called from including JSP
        ZimbraLog.zimlet.debug("zimletres: " + cacheId);
        ZimbraLog.zimlet.debug("zimletres: " + e.getMessage());
    }
    if (file != null) {
        // NOTE: If we saved the buffer to a file and compression is
        // NOTE: enabled then the file has *already* been compressed
        // NOTE: and the Content-Encoding header has been added.
        copy(file, resp, false);
    } else {
        copy(text, resp, compress);
    }
}
Also used : Set(java.util.Set) ServletConfig(javax.servlet.ServletConfig) CssCompressor(com.yahoo.platform.yui.compressor.CssCompressor) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) JavaScriptCompressor(com.yahoo.platform.yui.compressor.JavaScriptCompressor) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ErrorReporter(org.mozilla.javascript.ErrorReporter) StringWriter(java.io.StringWriter) EvaluatorException(org.mozilla.javascript.EvaluatorException) StringReader(java.io.StringReader) ServletContext(javax.servlet.ServletContext) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 69 with ServletConfig

use of javax.servlet.ServletConfig in project sling by apache.

the class RequestDataTest method setup.

@Before
public void setup() throws Exception {
    context = new Mockery() {

        {
            setImposteriser(ClassImposteriser.INSTANCE);
        }
    };
    req = context.mock(HttpServletRequest.class);
    resp = context.mock(HttpServletResponse.class);
    final ContentData contentData = context.mock(ContentData.class);
    final Servlet servlet = context.mock(Servlet.class);
    final ServletConfig servletConfig = context.mock(ServletConfig.class);
    context.checking(new Expectations() {

        {
            allowing(req).getServletPath();
            will(returnValue("/"));
            allowing(req).getPathInfo();
            will(returnValue(""));
            allowing(req).getMethod();
            will(returnValue("GET"));
            allowing(req).setAttribute(with(any(String.class)), with(any(Object.class)));
            allowing(req).setAttribute(with(any(String.class)), with(aNull(Object.class)));
            allowing(contentData).getServlet();
            will(returnValue(servlet));
            allowing(servlet).getServletConfig();
            will(returnValue(servletConfig));
            allowing(servlet).service(with(any(ServletRequest.class)), with(any(ServletResponse.class)));
            allowing(servletConfig).getServletName();
            will(returnValue("SERVLET_NAME"));
            allowing(req).getAttribute(RequestProgressTracker.class.getName());
            will(returnValue(null));
        }
    });
    requestData = new RequestData(null, req, resp) {

        @Override
        public ContentData getContentData() {
            return contentData;
        }
    };
    slingRequest = new SlingHttpServletRequestImpl(requestData, req);
    slingResponse = new SlingHttpServletResponseImpl(requestData, resp);
    RequestData.setMaxCallCounter(2);
}
Also used : Expectations(org.jmock.Expectations) ServletRequest(javax.servlet.ServletRequest) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) SlingHttpServletResponse(org.apache.sling.api.SlingHttpServletResponse) ServletResponse(javax.servlet.ServletResponse) SlingHttpServletResponseImpl(org.apache.sling.engine.impl.SlingHttpServletResponseImpl) ServletConfig(javax.servlet.ServletConfig) HttpServletResponse(javax.servlet.http.HttpServletResponse) SlingHttpServletResponse(org.apache.sling.api.SlingHttpServletResponse) Mockery(org.jmock.Mockery) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) SlingHttpServletRequestImpl(org.apache.sling.engine.impl.SlingHttpServletRequestImpl) Servlet(javax.servlet.Servlet) Before(org.junit.Before)

Aggregations

ServletConfig (javax.servlet.ServletConfig)69 ServletContext (javax.servlet.ServletContext)52 Enumeration (java.util.Enumeration)37 BeforeMethod (org.testng.annotations.BeforeMethod)21 ServletException (javax.servlet.ServletException)20 Test (org.junit.Test)15 IOException (java.io.IOException)12 BlockingIOCometSupport (org.atmosphere.container.BlockingIOCometSupport)9 MockServletConfig (org.springframework.mock.web.test.MockServletConfig)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 MockServletContext (org.springframework.mock.web.test.MockServletContext)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 AtmosphereFramework (org.atmosphere.runtime.AtmosphereFramework)6 ServletContextAwareProcessor (org.springframework.web.context.support.ServletContextAwareProcessor)6 HttpServlet (javax.servlet.http.HttpServlet)5 SimpleBroadcaster (org.atmosphere.util.SimpleBroadcaster)5 UnavailableException (javax.servlet.UnavailableException)4 PrintWriter (java.io.PrintWriter)3 AsynchronousProcessor (org.atmosphere.runtime.AsynchronousProcessor)3 AtmosphereRequest (org.atmosphere.runtime.AtmosphereRequest)3