javax.servlet.ServletConfig Java Examples

The following examples show how to use javax.servlet.ServletConfig. 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: GenericWebServiceServlet.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
public void init(ServletConfig sc) throws ServletException {
	// Setting this property because otherwise a file named
	// "wsdl.properties" will be read from the JRE, which is not possible
	// due to restrictive permissions
	System.setProperty("javax.wsdl.factory.WSDLFactory", "com.ibm.wsdl.factory.WSDLFactoryImpl");

	if (this.bus == null) {
		loadBus(sc);
	}
	loader = bus.getExtension(ClassLoader.class);
	ResourceManager resourceManager = bus.getExtension(ResourceManager.class);
	resourceManager.addResourceResolver(new ServletContextResourceResolver(sc.getServletContext()));

	if (destinationRegistry == null) {
		this.destinationRegistry = getDestinationRegistryFromBus(this.bus);
	}
	this.controller = createServletController(sc);

	redirectList = parseListSequence(sc.getInitParameter(REDIRECTS_PARAMETER));
	redirectQueryCheck = Boolean.valueOf(sc.getInitParameter(REDIRECT_QUERY_CHECK_PARAMETER));
	dispatcherServletName = sc.getInitParameter(REDIRECT_SERVLET_NAME_PARAMETER);
	dispatcherServletPath = sc.getInitParameter(REDIRECT_SERVLET_PATH_PARAMETER);
}
 
Example #2
Source File: ReasonableSakaiServlet.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public void init(ServletConfig config) {
	try {
		super.init(config);
		ServletContext context = getServletContext();
		Logger.log.info("ReasonableSakaiServlet starting up for context " + context.getRealPath(""));

		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(context);
		if (wac == null) {
			throw new IllegalStateException(
					"Error acquiring web application context " + "- servlet context not configured correctly");
		}
		rsacbl = (RSACBeanLocator) wac.getBean(RSACBeanLocator.RSAC_BEAN_LOCATOR_NAME);
	} catch (Throwable t) {
		Logger.log.warn("Error initialising SakaiRSF servlet: ", t);
	}
}
 
Example #3
Source File: WebAdminInterceptionServletTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterceptionServlet_noKarafEtc_forbidden() throws Exception {

	// Mocks
	HttpServletResponse resp = Mockito.mock( HttpServletResponse.class );
	HttpServletRequest req = Mockito.mock( HttpServletRequest.class );
	Mockito.when( req.getServletPath()).thenReturn( "invalid-resource" );

	ServletConfig sc = Mockito.mock( ServletConfig.class );
	ServletContext ctx = Mockito.mock( ServletContext.class );
	Mockito.when( sc.getServletContext()).thenReturn( ctx );

	// Initialization
	WebAdminInterceptionServlet servlet = new WebAdminInterceptionServlet();
	servlet.init( sc );
	servlet.karafEtc = "";

	// Execution
	servlet.doGet( req, resp );

	// Assertions
	Mockito.verify( req, Mockito.atLeast( 1 )).getServletPath();
	Mockito.verify( resp, Mockito.only()).sendError( HttpServletResponse.SC_FORBIDDEN );
}
 
Example #4
Source File: Bootstrap.java    From swagger-aem with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
  Info info = new Info()
    .title("OpenAPI Server")
    .description("Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API")
    .termsOfService("")
    .contact(new Contact()
      .email("[email protected]"))
    .license(new License()
      .name("")
      .url("http://unlicense.org"));

  ServletContext context = config.getServletContext();
  Swagger swagger = new Swagger().info(info);

  new SwaggerContextService().withServletConfig(config).updateSwagger(swagger);
}
 
Example #5
Source File: HttpServletBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create new ServletConfigPropertyValues.
 * @param config ServletConfig we'll use to take PropertyValues from
 * @param requiredProperties set of property names we need, where
 * we can't accept default values
 * @throws ServletException if any required properties are missing
 */
public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
	throws ServletException {

	Set<String> missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ?
			new HashSet<String>(requiredProperties) : null;

	Enumeration<String> en = config.getInitParameterNames();
	while (en.hasMoreElements()) {
		String property = en.nextElement();
		Object value = config.getInitParameter(property);
		addPropertyValue(new PropertyValue(property, value));
		if (missingProps != null) {
			missingProps.remove(property);
		}
	}

	// Fail if we are still missing properties.
	if (missingProps != null && missingProps.size() > 0) {
		throw new ServletException(
			"Initialization from ServletConfig for servlet '" + config.getServletName() +
			"' failed; the following required properties were missing: " +
			StringUtils.collectionToDelimitedString(missingProps, ", "));
	}
}
 
Example #6
Source File: GlowrootServlet.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    try {
        File centralDir = getCentralDir();
        File propFile = new File(centralDir, "glowroot-central.properties");
        if (!propFile.exists()) {
            Files.copy(config.getServletContext().getResourceAsStream(
                    "/META-INF/glowroot-central.properties"), propFile.toPath());
        }
        centralModule =
                CentralModule.createForServletContainer(centralDir, config.getServletContext());
        commonHandler = centralModule.getCommonHandler();
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
 
Example #7
Source File: PerThreadTagHandlerPool.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
protected void init(ServletConfig config) {
    maxSize = Constants.MAX_POOL_SIZE;
    String maxSizeS = getOption(config, OPTION_MAXSIZE, null);
    if (maxSizeS != null) {
        maxSize = Integer.parseInt(maxSizeS);
        if (maxSize < 0) {
            maxSize = Constants.MAX_POOL_SIZE;
        }
    }

    perThread = new ThreadLocal<PerThreadData>() {
        @Override
        protected PerThreadData initialValue() {
            PerThreadData ptd = new PerThreadData();
            ptd.handlers = new Tag[maxSize];
            ptd.current = -1;
            perThreadDataVector.addElement(ptd);
            return ptd;
        }
    };
}
 
Example #8
Source File: PlacesProxyServlet.java    From webmvc with Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws ServletException {
	super.init();
	ServletConfig config = getServletConfig();
       placesUrl = config.getInitParameter("PlacesUrl");
       apiKey = config.getInitParameter("GoogleApiKey");
       // Allow override with system property
       try {
       	placesUrl = System.getProperty("PlacesUrl", placesUrl);
       	apiKey = System.getProperty("GoogleApiKey", apiKey);
       } catch (SecurityException e) {
       }
       if (null == placesUrl) {
       	placesUrl = "https://maps.googleapis.com/maps/api/place/search/json";
       }
}
 
Example #9
Source File: ApiApi.java    From swaggy-jenkins with MIT License 6 votes vote down vote up
public ApiApi(@Context ServletConfig servletContext) {
   ApiApiService delegate = null;

   if (servletContext != null) {
      String implClass = servletContext.getInitParameter("ApiApi.implementation");
      if (implClass != null && !"".equals(implClass.trim())) {
         try {
            delegate = (ApiApiService) Class.forName(implClass).newInstance();
         } catch (Exception e) {
            throw new RuntimeException(e);
         }
      } 
   }

   if (delegate == null) {
      delegate = ApiApiServiceFactory.getApiApi();
   }

   this.delegate = delegate;
}
 
Example #10
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public FakeApi(@Context ServletConfig servletContext) {
   FakeApiService delegate = null;

   if (servletContext != null) {
      String implClass = servletContext.getInitParameter("FakeApi.implementation");
      if (implClass != null && !"".equals(implClass.trim())) {
         try {
            delegate = (FakeApiService) Class.forName(implClass).newInstance();
         } catch (Exception e) {
            throw new RuntimeException(e);
         }
      } 
   }

   if (delegate == null) {
      delegate = FakeApiServiceFactory.getFakeApi();
   }

   this.delegate = delegate;
}
 
Example #11
Source File: MessageForumsFilePickerServlet.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Initialize the servlet.
 * 
 * @param config
 *        The servlet config.
 * @throws ServletException
 */
public void init(ServletConfig config) throws ServletException {
  super.init(config);
  
  try {
    //load service level dependecies from the ComponentManager
    siteService = (SiteService) ComponentManager.get("org.sakaiproject.site.api.SiteService");
    accessProviderManager = (HttpServletAccessProviderManager) ComponentManager
      .get("org.sakaiproject.entitybroker.access.HttpServletAccessProviderManager");
    forumManager = (DiscussionForumManager) ComponentManager
      .get("org.sakaiproject.api.app.messageforums.ui.DiscussionForumManager");
    
    //register forum Entity prefixes for direct servlet request handling
    if (accessProviderManager != null) {
      accessProviderManager.registerProvider("forum_topic", this);
      accessProviderManager.registerProvider("forum", this);
      accessProviderManager.registerProvider("forum_message", this);
    }
    //mark initialization of dependecies as complete
    if (siteService != null && forumManager != null)
      initComplete = true;
  } catch (Exception e) {
    log.error(e.getMessage(), e);
  }
}
 
Example #12
Source File: AbstractRestServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig servletConfig) throws ServletException {
  // First try the servlet context init-param.
  String source = "InitParameter";
  key = servletConfig.getInitParameter(APPKEY);
  if (key == null || key.startsWith("${")) {
    source = "System Property";
    key = System.getProperty(APPKEY);
  }
  if (key == null || key.startsWith("${")) {
    source = "Environment Variable";
    key = System.getenv(APPKEY_ENV);
  }
  if (key == null) {
    throw new UnavailableException("Places App Key not set");
  }
  if (key.startsWith("${")) {
    throw new UnavailableException("Places App Key not expanded from " + source);
  }
}
 
Example #13
Source File: CmsMediaServlet.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    this.useCacheDefault = UtilMisc.booleanValue(config.getInitParameter("useCache"), true);
    String useCacheParam = config.getInitParameter("useCacheParam");
    if (useCacheParam != null && !"true".equals(useCacheParam)) {
        if (useCacheParam.isEmpty() || "false".equals(useCacheParam)) {
            this.useCacheParam = null;
        } else {
            this.useCacheParam = useCacheParam;
        }
    }
    if (Debug.infoOn()) {
        Debug.logInfo("Cms: Media servlet settings for servlet '" + config.getServletName() + "' of webapp '"
                + config.getServletContext().getContextPath() + "': [" 
                + "useCache=" + this.useCacheDefault + ", useCacheParam="
                + (this.useCacheParam != null ? this.useCacheParam : "(disabled)")+ "]", module);
    }
}
 
Example #14
Source File: CXFNonSpringJaxrsServlet.java    From JaxRSProviders with Apache License 2.0 6 votes vote down vote up
protected Map<Class<?>, ResourceProvider> getResourceProviders(ServletConfig servletConfig,
        Map<Class<?>, Map<String, List<String>>> resourceClasses) throws ServletException {
    String scope = servletConfig.getInitParameter(SERVICE_SCOPE_PARAM);
    if (scope != null && !SERVICE_SCOPE_SINGLETON.equals(scope)
        && !SERVICE_SCOPE_REQUEST.equals(scope)) {
        throw new ServletException("Only singleton and prototype scopes are supported");
    }
    boolean isPrototype = SERVICE_SCOPE_REQUEST.equals(scope);
    Map<Class<?>, ResourceProvider> map = new HashMap<>();
    for (Map.Entry<Class<?>, Map<String, List<String>>> entry : resourceClasses.entrySet()) {
        Class<?> c = entry.getKey();
        map.put(c, isPrototype ? new PerRequestResourceProvider(c)
                               : new SingletonResourceProvider(
                                     createSingletonInstance(c, entry.getValue(), servletConfig),
                                     true));
    }
    return map;
}
 
Example #15
Source File: TagHandlerPool.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
protected void init(ServletConfig config) {
    int maxSize = -1;
    String maxSizeS = getOption(config, OPTION_MAXSIZE, null);
    if (maxSizeS != null) {
        try {
            maxSize = Integer.parseInt(maxSizeS);
        } catch (Exception ex) {
            maxSize = -1;
        }
    }
    if (maxSize < 0) {
        maxSize = Constants.MAX_POOL_SIZE;
    }
    this.handlers = new Tag[maxSize];
    this.current = -1;
    instanceManager = InstanceManagerFactory.getInstanceManager(config);
}
 
Example #16
Source File: VelocityDispatchServlet.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException
{
	super.init(config);
	ServletContext context = config.getServletContext();
	inlineDispatcher = new VelocityInlineDispatcher();
	inlineDispatcher.init(context);
}
 
Example #17
Source File: PingJDBCRead.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
/**
 * called when the class is loaded to initialize the servlet
 *
 * @param config
 *            ServletConfig:
 **/
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    hitCount = 0;
    initTime = new java.util.Date().toString();
}
 
Example #18
Source File: DispatchServlet.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    __servletContext = config.getServletContext();
    //
    IWebMvcModuleCfg _moduleCfg = WebMVC.get().getModuleCfg();
    __dispatcher = new Dispatcher(_moduleCfg.getDefaultCharsetEncoding(), _moduleCfg.getDefaultContentType(), _moduleCfg.getRequestMethodParam());
    __requestPrefix = _moduleCfg.getRequestPrefix();
}
 
Example #19
Source File: GenericService.java    From jvm-sandbox-repeater with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the service instance.
 */
public void init(ServletConfig config)
  throws ServletException
{
  this.config = config;

  init();
}
 
Example #20
Source File: UpdatePublicServlet.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ApplicationContext context = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (context == null) {
        throw new ServletException("init failed");
    }
    this.cacheConfigTypeService = context.getBean(CacheConfigTypeService.class);
    this.filePublicStatusDao = context.getBean(FilePublicStatusDao.class);
    Preconditions.checkNotNull(this.cacheConfigTypeService);
}
 
Example #21
Source File: PentahoServlet.java    From pentaho-8-reporting-for-java-developers with Apache License 2.0 5 votes vote down vote up
@Override
public void init(
  ServletConfig config) 
  throws ServletException 
{

  super.init(config);
  ClassicEngineBoot.getInstance().start();

}
 
Example #22
Source File: JAXWSCXFNonSpringServlet.java    From xdocreport.samples with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void init( ServletConfig sc )
    throws ServletException
{
    super.init( sc );
    
    // Registered by CustomWebAppResourcesServiceListener
    ResourcesService  service = ResourcesServicesRegistry.getRegistry().getServices().get( 0 );
    String address = "/resources";
    Endpoint e = javax.xml.ws.Endpoint.publish( address,
                                   new JAXWSResourcesServiceImpl(service) );
    System.err.println(e);

}
 
Example #23
Source File: ReportServlet.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void init(ServletConfig config) {
	this.servletConfig = config;
	httpAuth = new HttpAuth();
	LOG.debug("JavaMelody report servlet initialized");
}
 
Example #24
Source File: PingServlet2DB.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
/**
 * called when the class is loaded to initialize the servlet
 *
 * @param config
 *            ServletConfig:
 **/
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    hitCount = 0;
    initTime = new java.util.Date().toString();
}
 
Example #25
Source File: MockPageContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create new MockServletConfig.
 * @param servletContext the ServletContext that the JSP page runs in
 * @param request the current HttpServletRequest
 * @param response the current HttpServletResponse
 * @param servletConfig the ServletConfig (hardly ever accessed from within a tag)
 */
public MockPageContext(@Nullable ServletContext servletContext, @Nullable HttpServletRequest request,
		@Nullable HttpServletResponse response, @Nullable ServletConfig servletConfig) {

	this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
	this.request = (request != null ? request : new MockHttpServletRequest(servletContext));
	this.response = (response != null ? response : new MockHttpServletResponse());
	this.servletConfig = (servletConfig != null ? servletConfig : new MockServletConfig(servletContext));
}
 
Example #26
Source File: ServletHttpHandlerAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
private String getServletPath(ServletConfig config) {
	String name = config.getServletName();
	ServletRegistration registration = config.getServletContext().getServletRegistration(name);
	if (registration == null) {
		throw new IllegalStateException("ServletRegistration not found for Servlet '" + name + "'");
	}

	Collection<String> mappings = registration.getMappings();
	if (mappings.size() == 1) {
		String mapping = mappings.iterator().next();
		if (mapping.equals("/")) {
			return "";
		}
		if (mapping.endsWith("/*")) {
			String path = mapping.substring(0, mapping.length() - 2);
			if (!path.isEmpty() && logger.isDebugEnabled()) {
				logger.debug("Found servlet mapping prefix '" + path + "' for '" + name + "'");
			}
			return path;
		}
	}

	throw new IllegalArgumentException("Expected a single Servlet mapping: " +
			"either the default Servlet mapping (i.e. '/'), " +
			"or a path based mapping (e.g. '/*', '/foo/*'). " +
			"Actual mappings: " + mappings + " for Servlet '" + name + "'");
}
 
Example #27
Source File: H2ConsoleWebServlet.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    ServletConfigFacade servletConfigFacade = new ServletConfigFacade(config);
    // http://h2database.com/html/features.html#connection_modes
    // http://h2database.com/html/features.html#auto_mixed_mode
    servletConfigFacade.setInitParameter("url", "jdbc:h2:mem:lts_admin;DB_CLOSE_DELAY=-1");
    servletConfigFacade.setInitParameter("user", "lts");
    servletConfigFacade.setInitParameter("password", "lts");
    servletConfigFacade.setInitParameter("webAllowOthers", "true");

    super.init(servletConfigFacade);
}
 
Example #28
Source File: CompilePojoServlet.java    From steam with GNU Affero General Public License v3.0 5 votes vote down vote up
public void init(ServletConfig servletConfig) throws ServletException {
  super.init(servletConfig);
  try {
    servletPath = new File(servletConfig.getServletContext().getResource("/").getPath());
    if (VERBOSE) logger.info("servletPath = {}", servletPath);
  }
  catch (MalformedURLException e) {
    logger.error("init failed", e);
  }
}
 
Example #29
Source File: LifecyleInterceptorInvocation.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
LifecyleInterceptorInvocation(List<LifecycleInterceptor> list, ServletInfo servletInfo, Servlet servlet,  ServletConfig servletConfig) {
    this.list = list;
    this.servletInfo = servletInfo;
    this.servlet = servlet;
    this.servletConfig = servletConfig;
    this.filter = null;
    this.filterConfig = null;
    this.filterInfo = null;
    i = list.size();
}
 
Example #30
Source File: EntryPointV2Servlet.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    ApplicationContext context = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (context == null) {
        throw new ServletException("init failed");
    }

    entryPointService = context.getBean(EntryPointService.class);
    Preconditions.checkNotNull(entryPointService);
}