javax.servlet.Servlet Java Examples

The following examples show how to use javax.servlet.Servlet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpWebConnectionTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void emptyPut() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/test", EmptyPutServlet.class);
    startWebServer("./", null, servlets);

    final String[] expectedAlerts = {"1"};
    final WebClient client = getWebClient();
    client.setAjaxController(new NicelyResynchronizingAjaxController());
    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    assertEquals(0, client.getCookieManager().getCookies().size());
    client.getPage(URL_FIRST + "test");
    assertEquals(expectedAlerts, collectedAlerts);
    assertEquals(1, client.getCookieManager().getCookies().size());
}
 
Example #2
Source File: HttpServletProtocol.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
/**
 * Destruction servlet
 */
protected void destroyServlet(){
    Map<String, ServletRegistration> servletRegistrationMap = servletContext.getServletRegistrations();
    for(ServletRegistration registration : servletRegistrationMap.values()){
        Servlet servlet = registration.getServlet();
        if(servlet == null) {
            continue;
        }
        if(registration.isInitServlet()){
            try {
                servlet.destroy();
            }catch (Exception e){
                logger.error("destroyServlet error={},servlet={}",e.toString(),servlet,e);
            }
        }
    }
}
 
Example #3
Source File: ServletHolderBuilder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new Guice aware {@link ServletHolder servlet holder} instance.
 *
 * @param clazz
 *            the class of the servlet to instantiate.
 * @return the Guice aware servlet holder.
 */
public ServletHolder build(final Class<? extends Servlet> clazz) {
	ServletHolder servletHolder = new ServletHolder(clazz) {
		@Override
		protected Servlet newInstance() throws ServletException, IllegalAccessException, InstantiationException {
			try {
				Servlet servlet = super.newInstance();
				Injector injector = injectedInjector;
				injector.injectMembers(servlet);
				return servlet;
			} catch (Exception e) {
				LOGGER.error("Error while creating servlet for class: " + clazz + ";", e);
				throw new RuntimeException(e);
			}
		}
	};
	return servletHolder;
}
 
Example #4
Source File: HttpServiceImpl.java    From fuchsia with Apache License 2.0 6 votes vote down vote up
public void registerServlet(String context, Servlet servlet, Dictionary dictionary, HttpContext httpContext) throws ServletException, NamespaceException {

        ContextHandlerCollection contexts = new ContextHandlerCollection();
        server.setHandler(contexts);
        ServletContextHandler root = new ServletContextHandler(contexts, "/",
                ServletContextHandler.SESSIONS);
        ServletHolder servletHolder = new ServletHolder(servlet);
        root.addServlet(servletHolder, context);

        if (!server.getServer().getState().equals(server.STARTED)) {
            try {
                server.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
 
Example #5
Source File: ServletInfo.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public ServletInfo(final String name, final Class<? extends Servlet> servletClass) {
    if (name == null) {
        throw UndertowServletMessages.MESSAGES.paramCannotBeNull("name");
    }
    if (servletClass == null) {
        throw UndertowServletMessages.MESSAGES.paramCannotBeNull("servletClass", "Servlet", name);
    }
    if (!Servlet.class.isAssignableFrom(servletClass)) {
        throw UndertowServletMessages.MESSAGES.servletMustImplementServlet(name, servletClass);
    }
    try {
        final Constructor<? extends Servlet> ctor = servletClass.getDeclaredConstructor();
        ctor.setAccessible(true);
        this.instanceFactory = new ConstructorInstanceFactory(ctor);
        this.name = name;
        this.servletClass = servletClass;
    } catch (NoSuchMethodException e) {
        throw UndertowServletMessages.MESSAGES.componentMustHaveDefaultConstructor("Servlet", servletClass);
    }
}
 
Example #6
Source File: MCP.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void main(String[] args) {
    // initialize environment variables
    System.setProperty("java.awt.headless", "true"); // no awt used here so we can switch off that stuff

    // start server
    List<Class<? extends Servlet>> services = new ArrayList<>();
    services.addAll(Arrays.asList(MCP_SERVICES));
    Service.initEnvironment(MCP_SERVICE, services, DATA_PATH, true);

    // start listener
    BrokerListener brokerListener = new IndexListener(INDEXER_SERVICE);
    new Thread(brokerListener).start();

    // start server
    Data.logger.info("started MCP");
    Data.logger.info("Grid Name: " + Data.config.get("grid.name"));
    Data.logger.info(new GitTool().toString());
    Data.logger.info("you can now search using the query api, i.e.:");
    Data.logger.info("curl http://127.0.0.1:8100/yacy/grid/mcp/index/yacysearch.json?query=test");
    Service.runService(null);

    // this line is reached if the server was shut down
    brokerListener.terminate();
}
 
Example #7
Source File: MockFilterChainTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void doFilterWithServletAndFilters() throws Exception {
	Servlet servlet = mock(Servlet.class);

	MockFilter filter2 = new MockFilter(servlet);
	MockFilter filter1 = new MockFilter(null);
	MockFilterChain chain = new MockFilterChain(servlet, filter1, filter2);

	chain.doFilter(this.request, this.response);

	assertTrue(filter1.invoked);
	assertTrue(filter2.invoked);

	verify(servlet).service(this.request, this.response);

	try {
		chain.doFilter(this.request, this.response);
		fail("Expected Exception");
	}
	catch (IllegalStateException ex) {
		assertEquals("This FilterChain has already been called!", ex.getMessage());
	}
}
 
Example #8
Source File: SpringBootTomcatPlusIT.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * onServletStop
 * 
 * @param args
 */
@Override
public void onServletStop(Object... args) {

    StandardWrapper sw = (StandardWrapper) args[0];
    Servlet servlet = (Servlet) args[1];
    InterceptSupport iSupport = InterceptSupport.instance();
    InterceptContext context = iSupport.createInterceptContext(Event.BEFORE_SERVLET_DESTROY);
    context.put(InterceptConstants.SERVLET_INSTANCE, servlet);
    /**
     * NOTE: spring boot rewrite the tomcat webappclassloader, makes the addURL for nothing, then we can't do
     * anything on this we may use its webappclassloader's parent as the classloader
     */
    context.put(InterceptConstants.WEBAPPLOADER, Thread.currentThread().getContextClassLoader().getParent());

    context.put(InterceptConstants.CONTEXTPATH, sw.getServletContext().getContextPath());
    iSupport.doIntercept(context);
}
 
Example #9
Source File: JspFactoryImpl.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
public PageContext getPageContext(Servlet servlet,
			      ServletRequest request,
                                     ServletResponse response,
                                     String errorPageURL,                    
                                     boolean needsSession,
			      int bufferSize,
                                     boolean autoflush) {

if (Constants.IS_SECURITY_ENABLED) {
    PrivilegedGetPageContext dp =
                   new PrivilegedGetPageContext(
	        this, servlet, request, response, errorPageURL,
                       needsSession, bufferSize, autoflush);
    return AccessController.doPrivileged(dp);
} else {
    return internalGetPageContext(servlet, request, response,
				  errorPageURL, needsSession,
				  bufferSize, autoflush);
}
   }
 
Example #10
Source File: TestServletConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractConfiguration getConfiguration()
{
    final MockServletConfig config = new MockServletConfig();
    config.setInitParameter("key1", "value1");
    config.setInitParameter("key2", "value2");
    config.setInitParameter("list", "value1, value2");
    config.setInitParameter("listesc", "value1\\,value2");

    final Servlet servlet = new HttpServlet() {
        /**
         * Serial version UID.
         */
        private static final long serialVersionUID = 1L;

        @Override
        public ServletConfig getServletConfig()
        {
            return config;
        }
    };

    final ServletConfiguration servletConfiguration = new ServletConfiguration(servlet);
    servletConfiguration.setListDelimiterHandler(new DefaultListDelimiterHandler(','));
    return servletConfiguration;
}
 
Example #11
Source File: FacesServletAutoConfigurationTest.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
public void testServletContextAttributes_added() {
	this.webApplicationContextRunner
			.run(context -> {
				ServletRegistrationBean<FacesServlet> facesServletRegistrationBean = (ServletRegistrationBean<FacesServlet>) context.getBean("facesServletRegistrationBean");

				ServletContext servletContext = mock(ServletContext.class);

				when(servletContext.addServlet(anyString(), any(Servlet.class))).thenReturn(mock(ServletRegistration.Dynamic.class));

				facesServletRegistrationBean.onStartup(servletContext);

				verify(servletContext, times(2)).setAttribute(any(), any());
			});
}
 
Example #12
Source File: JspFactoryImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
PrivilegedGetPageContext(JspFactoryImpl factory, Servlet servlet,
        ServletRequest request, ServletResponse response, String errorPageURL,
        boolean needsSession, int bufferSize, boolean autoflush) {
    this.factory = factory;
    this.servlet = servlet;
    this.request = request;
    this.response = response;
    this.errorPageURL = errorPageURL;
    this.needsSession = needsSession;
    this.bufferSize = bufferSize;
    this.autoflush = autoflush;
}
 
Example #13
Source File: WebConfigurerTest.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
public void setup() {
	servletContext = spy(new MockServletContext());
	doReturn(mock(FilterRegistration.Dynamic.class))
		.when(servletContext).addFilter(anyString(), any(Filter.class));
	doReturn(mock(ServletRegistration.Dynamic.class))
		.when(servletContext).addServlet(anyString(), any(Servlet.class));

	env = new MockEnvironment();
	props = new ApplicationProperties();

	webConfigurer = new WebConfigurer(env, props);
}
 
Example #14
Source File: DispatcherServletInitializerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
	servlets.put(servletName, servlet);
	MockServletRegistration registration = new MockServletRegistration();
	registrations.put(servletName, registration);
	return registration;
}
 
Example #15
Source File: ServletFactory.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
protected Servlet createServlet() throws ServletException {
    // Init paramameters - optional
    //HashMap<String, String> params = new HashMap<String, String>();
    //params.put("MyParam", "myValue");
    Servlet servlet = (Servlet)module.createServlet(servletClass,servletName, null /*params*/);
    return servlet;
}
 
Example #16
Source File: WebServer.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
public Collection<Holder> addServlets(@NotNull Map<String, Servlet> servletMap) {
  List<Holder> servletInfos = new ArrayList<>();
  for (Map.Entry<String, Servlet> entry : servletMap.entrySet()) {
    log.info("Registered servlet for path: {}", entry.getKey());
    final Holder servletInfo = new Holder(entry.getKey(), entry.getValue());
    servletInfos.add(servletInfo);
  }
  servlets.addAll(servletInfos);
  updateServlets();
  return servletInfos;
}
 
Example #17
Source File: TestStandardContext.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    // Register and map servlet
    Servlet s = new Bug50015Servlet();
    ServletRegistration.Dynamic sr = ctx.addServlet("bug50015", s);
    sr.addMapping("/bug50015");

    // Limit access to users in the Tomcat role
    HttpConstraintElement hce = new HttpConstraintElement(
            TransportGuarantee.NONE, "tomcat");
    ServletSecurityElement sse = new ServletSecurityElement(hce);
    sr.setServletSecurity(sse);
}
 
Example #18
Source File: InstanceSupport.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Notify all lifecycle event listeners that a particular event has
 * occurred for this Container.  The default implementation performs
 * this notification synchronously using the calling thread.
 *
 * @param type Event type
 * @param servlet The relevant Servlet for this event
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 */
public void fireInstanceEvent(String type, Servlet servlet,
                              ServletRequest request,
                              ServletResponse response) {

    if (listeners.length == 0)
        return;

    InstanceEvent event = new InstanceEvent(wrapper, servlet, type,
                                            request, response);
    InstanceListener interested[] = listeners;
    for (int i = 0; i < interested.length; i++)
        interested[i].instanceEvent(event);

}
 
Example #19
Source File: ManagedServlet.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public InstanceHandle<? extends Servlet> getServlet() throws ServletException {
    final InstanceHandle<? extends Servlet> instanceHandle;
    final Servlet instance;
    //TODO: pooling
    try {
        instanceHandle = factory.createInstance();
    } catch (Exception e) {
        throw UndertowServletMessages.MESSAGES.couldNotInstantiateComponent(servletInfo.getName(), e);
    }
    instance = instanceHandle.getInstance();
    new LifecyleInterceptorInvocation(servletContext.getDeployment().getDeploymentInfo().getLifecycleInterceptors(), servletInfo, instance, new ServletConfigImpl(servletInfo, servletContext)).proceed();

    return new InstanceHandle<Servlet>() {
        @Override
        public Servlet getInstance() {
            return instance;
        }

        @Override
        public void release() {
            try {
                instance.destroy();
            } catch (Throwable t) {
                UndertowServletLogger.REQUEST_LOGGER.failedToDestroy(instance, t);
            }
            instanceHandle.release();
        }
    };

}
 
Example #20
Source File: BinaryPageTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void chunkedBigContent() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/bigChunked", ChunkedBigContentServlet.class);
    startWebServer("./", null, servlets);

    final WebClient client = getWebClient();

    final Page page = client.getPage(URL_FIRST + "bigChunked");
    assertTrue(page instanceof UnexpectedPage);
}
 
Example #21
Source File: XMLHttpRequest2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = {"<xml><content>blah</content></xml>", "text/xml;charset=utf-8", "gzip", "45"},
        IE = {"<xml><content>blah</content></xml>", "text/xml;charset=utf-8", "null", "null"})
@NotYetImplemented(IE)
public void encodedXml() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/test", EncodedXmlServlet.class);

    final String html =
            "<html>\n"
                    + "  <head>\n"
                    + "    <title>XMLHttpRequest Test</title>\n"
                    + "    <script>\n"
                    + "      var request;\n"
                    + "      function testBasicAuth() {\n"
                    + "        var request = new XMLHttpRequest();\n"
                    + "        request.open('GET', '/test', false, null, null);\n"
                    + "        request.send();\n"
                    + "        alert(request.responseText);\n"
                    + "        alert(request.getResponseHeader('content-type'));\n"
                    + "        alert(request.getResponseHeader('content-encoding'));\n"
                    + "        alert(request.getResponseHeader('content-length'));\n"
                    + "      }\n"
                    + "    </script>\n"
                    + "  </head>\n"
                    + "  <body onload='testBasicAuth()'>\n"
                    + "  </body>\n"
                    + "</html>";

    loadPageWithAlerts2(html, servlets);
}
 
Example #22
Source File: SecurityUtil.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Perform work as a particular </code>Subject</code>. Here the work
 * will be granted to a <code>null</code> subject.
 *
 * @param methodName the method to apply the security restriction
 * @param targetObject the <code>Servlet</code> on which the method will
 * be called.
 * @param targetType <code>Class</code> array used to instantiate a
 * <code>Method</code> object.
 * @param targetArguments <code>Object</code> array contains the runtime
 * parameters instance.
 */
public static void doAsPrivilege(final String methodName,
                                 final Servlet targetObject,
                                 final Class<?>[] targetType,
                                 final Object[] targetArguments)
    throws java.lang.Exception{

     doAsPrivilege(methodName,
                   targetObject,
                   targetType,
                   targetArguments,
                   null);
}
 
Example #23
Source File: TesterServletContainerInitializer1.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    Servlet s = new TesterServlet();
    ServletRegistration.Dynamic r = ctx.addServlet("TesterServlet1", s);
    r.addMapping("/TesterServlet1");
}
 
Example #24
Source File: XMLHttpRequestCORSTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails.
 */
@Test
@Alerts(DEFAULT = {"4", "200", "options_headers", "x-ping,x-pong"},
        IE = {"4", "200", "options_headers", "null"})
public void preflight_many_header_values() throws Exception {
    expandExpectedAlertsVariables(new URL("http://localhost:" + PORT));

    final String html = "<html><head>\n"
            + "<script>\n"
            + "var xhr = new XMLHttpRequest();\n"
            + "function test() {\n"
            + "  try {\n"
            + "    var url = 'http://' + window.location.hostname + ':" + PORT2 + "/preflight2';\n"
            + "    xhr.open('GET', url, false);\n"
            + "    xhr.setRequestHeader('X-PING', 'ping');\n"
            + "    xhr.setRequestHeader('X-PONG', 'pong');\n"
            + "    xhr.send();\n"
            + "  } catch(e) { alert('exception') }\n"
            + "  alert(xhr.readyState);\n"
            + "  alert(xhr.status);\n"
            + "  alert(xhr.responseXML.firstChild.childNodes[3].tagName);\n"
            + "  alert(xhr.responseXML.firstChild.childNodes[3].firstChild.nodeValue);\n"
            + "}\n"
            + "</script>\n"
            + "</head>\n"
            + "<body onload='test()'></body></html>";

    PreflightServerServlet.ACCESS_CONTROL_ALLOW_ORIGIN_ = "http://localhost:" + PORT;
    PreflightServerServlet.ACCESS_CONTROL_ALLOW_METHODS_ = "POST, GET, OPTIONS";
    PreflightServerServlet.ACCESS_CONTROL_ALLOW_HEADERS_ = "X-PING, X-PONG";
    final Map<String, Class<? extends Servlet>> servlets2 = new HashMap<>();
    servlets2.put("/preflight2", PreflightServerServlet.class);
    startWebServer2(".", null, servlets2);

    loadPageWithAlerts2(html, new URL(URL_FIRST, "/preflight1"));
}
 
Example #25
Source File: UndertowTestServer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public InstanceHandle<Servlet> createInstance() throws InstantiationException {
	return new InstanceHandle<Servlet>() {
		@Override
		public Servlet getInstance() {
			return new DispatcherServlet(wac);
		}
		@Override
		public void release() {
		}
	};
}
 
Example #26
Source File: TestContextConfig.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    Servlet s = new CustomDefaultServlet();
    ServletRegistration.Dynamic r = ctx.addServlet(servletName, s);
    r.addMapping("/");
}
 
Example #27
Source File: ApplicationContextFacade.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public ServletRegistration.Dynamic addServlet(String servletName,
        Servlet servlet) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return (ServletRegistration.Dynamic) doPrivileged("addServlet",
                new Class[]{String.class, Servlet.class},
                new Object[]{servletName, servlet});
    } else {
        return context.addServlet(servletName, servlet);
    }
}
 
Example #28
Source File: InstanceEvent.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new InstanceEvent with the specified parameters.  This
 * constructor is used for processing servlet lifecycle events.
 *
 * @param wrapper Wrapper managing this servlet instance
 * @param servlet Servlet instance for which this event occurred
 * @param type Event type (required)
 * @param exception Exception that occurred
 */
public InstanceEvent(Wrapper wrapper, Servlet servlet, String type,
                     Throwable exception) {

  super(wrapper);
  this.filter = null;
  this.servlet = servlet;
  this.type = type;
  this.exception = exception;

}
 
Example #29
Source File: TestHelpers.java    From jobson with Apache License 2.0 5 votes vote down vote up
public static AuthenticationBootstrap createTypicalAuthBootstrap() {
    final UserDAO userDAO = mock(UserDAO.class);
    final Server s = new Server(0);
    final Servlet se = new ServletContainer();
    final JerseyEnvironment env = new JerseyEnvironment(new JerseyContainerHolder(se), new DropwizardResourceConfig());

    return new AuthenticationBootstrap(env, userDAO);
}
 
Example #30
Source File: JettyAppServer.java    From selenium with Apache License 2.0 5 votes vote down vote up
public void addServlet(
    ServletContextHandler context,
    String url,
    Class<? extends Servlet> servletClass) {
  try {
    context.addServlet(new ServletHolder(servletClass), url);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}