List of usage examples for javax.servlet ServletConfig getServletName
public String getServletName();
From source file:org.danann.cernunnos.runtime.web.CernunnosServlet.java
@SuppressWarnings("unchecked") @Override/*from w ww.j a v a 2s .c om*/ public void init() throws ServletException { ServletConfig config = getServletConfig(); // Load the context, if present... try { // Bootstrap the servlet Grammar instance... final Grammar root = XmlGrammar.getMainGrammar(); final InputStream inpt = CernunnosServlet.class.getResourceAsStream("servlet.grammar"); // Can't rely on classpath:// protocol handler... final Document doc = new SAXReader().read(inpt); final Task k = new ScriptRunner(root).compileTask(doc.getRootElement()); final RuntimeRequestResponse req = new RuntimeRequestResponse(); final ReturnValueImpl rslt = new ReturnValueImpl(); req.setAttribute(Attributes.RETURN_VALUE, rslt); k.perform(req, new RuntimeRequestResponse()); Grammar g = (Grammar) rslt.getValue(); runner = new ScriptRunner(g); // Choose a context location & load it if it exists... String defaultLoc = "/WEB-INF/" + config.getServletName() + "-portlet.xml"; URL defaultUrl = getServletConfig().getServletContext().getResource(defaultLoc); URL u = Settings.locateContextConfig( getServletConfig().getServletContext().getResource("/").toExternalForm(), config.getInitParameter(CONFIG_LOCATION_PARAM), defaultUrl); if (u != null) { // There *is* a resource mapped to this path name... spring_context = new FileSystemXmlApplicationContext(u.toExternalForm()); } if (log.isDebugEnabled()) { log.debug("Location of spring context (null means none): " + u); } // Load the Settings... Map<String, String> settingsMap = new HashMap<String, String>(); // default... if (spring_context != null && spring_context.containsBean("settings")) { settingsMap = (Map<String, String>) spring_context.getBean("settings"); } settings = Settings.load(settingsMap); } catch (Throwable t) { String msg = "Failure in CernunnosServlet.init()"; throw new ServletException(msg, t); } }
From source file:lucee.runtime.engine.CFMLEngineImpl.java
@Override public void cli(Map<String, String> config, ServletConfig servletConfig) throws IOException, JspException, ServletException { ServletContext servletContext = servletConfig.getServletContext(); HTTPServletImpl servlet = new HTTPServletImpl(servletConfig, servletContext, servletConfig.getServletName()); // webroot/*from w w w . j a v a2 s . com*/ String strWebroot = config.get("webroot"); if (StringUtil.isEmpty(strWebroot, true)) throw new IOException("missing webroot configuration"); Resource root = ResourcesImpl.getFileResourceProvider().getResource(strWebroot); root.mkdirs(); // serverName String serverName = config.get("server-name"); if (StringUtil.isEmpty(serverName, true)) serverName = "localhost"; // uri String strUri = config.get("uri"); if (StringUtil.isEmpty(strUri, true)) throw new IOException("missing uri configuration"); URI uri; try { uri = lucee.commons.net.HTTPUtil.toURI(strUri); } catch (URISyntaxException e) { throw Caster.toPageException(e); } // cookie Cookie[] cookies; String strCookie = config.get("cookie"); if (StringUtil.isEmpty(strCookie, true)) cookies = new Cookie[0]; else { Map<String, String> mapCookies = HTTPUtil.parseParameterList(strCookie, false, null); int index = 0; cookies = new Cookie[mapCookies.size()]; Entry<String, String> entry; Iterator<Entry<String, String>> it = mapCookies.entrySet().iterator(); Cookie c; while (it.hasNext()) { entry = it.next(); c = ReqRspUtil.toCookie(entry.getKey(), entry.getValue(), null); if (c != null) cookies[index++] = c; else throw new IOException("cookie name [" + entry.getKey() + "] is invalid"); } } // header Pair[] headers = new Pair[0]; // parameters Pair[] parameters = new Pair[0]; // attributes StructImpl attributes = new StructImpl(); ByteArrayOutputStream os = new ByteArrayOutputStream(); HttpServletRequestDummy req = new HttpServletRequestDummy(root, serverName, uri.getPath(), uri.getQuery(), cookies, headers, parameters, attributes, null); req.setProtocol("CLI/1.0"); HttpServletResponse rsp = new HttpServletResponseDummy(os); serviceCFML(servlet, req, rsp); String res = os.toString(ReqRspUtil.getCharacterEncoding(null, rsp).name()); System.out.println(res); }
From source file:com.sonicle.webtop.core.app.JaxRsServiceApplication.java
private void configureServiceApis(WebTopApp wta, ServletConfig servletConfig) { ServiceManager svcMgr = wta.getServiceManager(); String serviceId = servletConfig.getInitParameter(RestApi.INIT_PARAM_WEBTOP_SERVICE_ID); if (StringUtils.isBlank(serviceId)) throw new WTRuntimeException( "Invalid servlet init parameter [" + RestApi.INIT_PARAM_WEBTOP_SERVICE_ID + "]"); ServiceDescriptor desc = svcMgr.getDescriptor(serviceId); if (desc == null) throw new WTRuntimeException("Service descriptor not found [{0}]", serviceId); if (desc.hasOpenApiDefinitions()) { for (ServiceDescriptor.OpenApiDefinition apiDefinition : desc.getOpenApiDefinitions()) { // Register resources for (Class clazz : apiDefinition.resourceClasses) { javax.ws.rs.Path pathAnnotation = (javax.ws.rs.Path) ClassHelper .getClassAnnotation(clazz.getSuperclass(), javax.ws.rs.Path.class); String resourcePath = "/" + PathUtils.concatPathParts(apiDefinition.context, pathAnnotation.value()); logger.debug("[{}] Registering JaxRs resource [{}] -> [{}]", servletConfig.getServletName(), clazz.toString(), resourcePath); registerResources(Resource.builder(clazz).path(resourcePath).build()); }/*from w ww . j a v a2 s . co m*/ // Configure OpenApi listing OpenAPI oa = new OpenAPI(); oa.info(desc.buildOpenApiInfo(apiDefinition)); SwaggerConfiguration oaConfig = new SwaggerConfiguration().openAPI(oa).prettyPrint(true) .resourcePackages(Stream.of(apiDefinition.implPackage).collect(Collectors.toSet())); try { new JaxrsOpenApiContextBuilder().servletConfig(servletConfig).application(this) .ctxId(apiDefinition.context).openApiConfiguration(oaConfig).buildContext(true); } catch (OpenApiConfigurationException ex) { logger.error("Unable to init swagger", ex); } } } }
From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java
private String configureServletMapping(ServletConfig servletConfig) { Collection<String> mappings = servletConfig.getServletContext() .getServletRegistration(servletConfig.getServletName()).getMappings(); if (mappings.isEmpty()) { throw new KurentoException("There is no mapping for servlet " + RepositoryHttpServlet.class.getName()); }/*from w ww . j a va2 s.c om*/ String mapping = mappings.iterator().next(); // TODO: Document this. We assume a mapping starting with / and ending // with /* mapping = mapping.substring(0, mapping.length() - 1); repoHttpManager.setServletPath(mapping); return mapping; }
From source file:m.c.m.proxyma.ProxymaServlet.java
/** * Initialize the servlet and the proxyma environment. *//* w ww. java 2 s . c om*/ @Override public void init() { try { //Obtain configuration parameters.. ServletConfig config = this.getServletConfig(); String proxymaConfigFile = this.getInitParameter("ProxymaConfigurationFile"); String proxymaContextName = this.getInitParameter("ProxymaContextName"); String proxymaLogsDirectory = this.getInitParameter("ProxymaLogsDir"); //if the config file init-parameter is notspecified use the default configuration if (proxymaConfigFile == null) proxymaConfigFile = config.getServletContext().getRealPath("/WEB-INF/proxyma-config.xml"); //Hack to get the servlet path reading it directly from the deployment descriptor. //Valid until apache will put a getServletMappings() method into the ServletConfig class. XMLConfiguration deploymentDescriptor = null; try { deploymentDescriptor = new XMLConfiguration(); deploymentDescriptor.setFile(new File(config.getServletContext().getRealPath("/WEB-INF/web.xml"))); deploymentDescriptor.setValidating(false); deploymentDescriptor.load(); } catch (ConfigurationException ex) { Logger.getLogger("").log(Level.SEVERE, "Unable to load web.xml", ex); } deploymentDescriptor.setExpressionEngine(new XPathExpressionEngine()); String servletPath = deploymentDescriptor .getString("servlet-mapping[servlet-name='" + config.getServletName() + "']/url-pattern"); String proxymaServletContext = config.getServletContext().getContextPath() + servletPath.replaceFirst("/\\*$", GlobalConstants.EMPTY_STRING); //Check if the logs directory init-parameter ends with "/" if (!proxymaLogsDirectory.endsWith("/")) { proxymaLogsDirectory = proxymaLogsDirectory + "/"; } //Create a new proxyma facade this.proxyma = new ProxymaFacade(); //Create a new proxyma context this.proxymaContext = proxyma.createNewContext(proxymaContextName, proxymaServletContext, proxymaConfigFile, proxymaLogsDirectory); //Create a reverse proxy engine for this servlet thread this.proxymaEngine = proxyma.createNewProxyEngine(proxymaContext); } catch (IllegalAccessException ex) { ex.printStackTrace(); } }
From source file:net.ontopia.topicmaps.db2tm.SynchronizationServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); log.info("Initializing synchronization servlet."); try {/*from w ww .ja v a2 s .c o m*/ // no default starttime Date time = null; long delay = 180 * 1000; String timeval = config.getInitParameter("start-time"); if (timeval != null) { Date d = df.parse(timeval); Calendar c0 = Calendar.getInstance(); Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 1); c.set(Calendar.MINUTE, 0); c.add(Calendar.MILLISECOND, (int) d.getTime()); if (c.before(c0)) c.add(Calendar.HOUR_OF_DAY, 24); time = c.getTime(); log.info("Setting synchronization start time to {} ms.", time); } else { // default delay is 180 sec. delay = getLongProperty(config, "delay", delay); log.info("Setting synchronization delay to {} ms.", delay); } // default interval is 24 hours. long interval = getLongProperty(config, "interval", 1000 * 60 * 60 * 24); log.info("Setting synchronization interval to {} ms.", interval); // load relation mapping file String mapping = config.getInitParameter("mapping"); if (mapping == null) throw new OntopiaRuntimeException("Servlet init-param 'mapping' must be specified."); // get relation names (comma separated) Collection<String> relnames = null; String relations = config.getInitParameter("relations"); if (relations != null) relnames = Arrays.asList(StringUtils.split(relations, ",")); // get hold of the topic map String tmid = config.getInitParameter("topicmap"); if (tmid == null) throw new OntopiaRuntimeException("Servlet init-param 'topicmap' must be specified."); TopicMapRepositoryIF rep = NavigatorUtils.getTopicMapRepository(config.getServletContext()); TopicMapReferenceIF ref = rep.getReferenceByKey(tmid); // make sure delay is at least 10 seconds to make sure that it doesn't // start too early if (time == null) task = new SynchronizationTask(config.getServletName(), (delay < 10000 ? 10000 : delay), interval); else task = new SynchronizationTask(config.getServletName(), time, interval); task.setRelationMappingFile(mapping); task.setRelationNames(relnames); task.setTopicMapReference(ref); task.setBaseLocator(null); } catch (Exception e) { throw new ServletException(e); } }
From source file:org.amplafi.jawr.maven.JawrMojo.java
private void setupJawrConfig(ServletConfig config, ServletContext context, final Map<String, Object> attributes, final Response respData) { expect(config.getServletContext()).andReturn(context).anyTimes(); expect(config.getServletName()).andReturn("maven-jawr-plugin").anyTimes(); context.log(isA(String.class)); expectLastCall().anyTimes();/*from w ww . j a v a 2s.c o m*/ expect(context.getResourcePaths(isA(String.class))).andAnswer(new IAnswer<Set>() { public Set<String> answer() throws Throwable { final Set<String> set = new HashSet<String>(); // hack to disallow orphan bundles Exception e = new Exception(); for (StackTraceElement trace : e.getStackTrace()) { if (trace.getClassName().endsWith("OrphanResourceBundlesMapper")) { return set; } } String path = (String) EasyMock.getCurrentArguments()[0]; File file = new File(getRootPath() + path); if (file.exists() && file.isDirectory()) { for (String one : file.list()) { set.add(path + one); } } return set; } }).anyTimes(); expect(context.getResourceAsStream(isA(String.class))).andAnswer(new IAnswer<InputStream>() { public InputStream answer() throws Throwable { String path = (String) EasyMock.getCurrentArguments()[0]; File file = new File(getRootPath(), path); return new FileInputStream(file); } }).anyTimes(); expect(context.getAttribute(isA(String.class))).andAnswer(new IAnswer<Object>() { public Object answer() throws Throwable { return attributes.get(EasyMock.getCurrentArguments()[0]); } }).anyTimes(); context.setAttribute(isA(String.class), isA(Object.class)); expectLastCall().andAnswer(new IAnswer<Object>() { public Object answer() throws Throwable { String key = (String) EasyMock.getCurrentArguments()[0]; Object value = EasyMock.getCurrentArguments()[1]; attributes.put(key, value); return null; } }).anyTimes(); expect(config.getInitParameterNames()).andReturn(new Enumeration<String>() { public boolean hasMoreElements() { return false; } public String nextElement() { return null; } }).anyTimes(); expect(config.getInitParameter(JawrConstant.TYPE_INIT_PARAMETER)).andAnswer(new IAnswer<String>() { public String answer() throws Throwable { return respData == null ? null : respData.getType(); } }).anyTimes(); expect(config.getInitParameter("configLocation")).andReturn(getConfigLocation()).anyTimes(); expect(config.getInitParameter("configPropertiesSourceClass")).andReturn(null).anyTimes(); }
From source file:org.apache.camel.component.servlet.CamelHttpTransportServlet.java
public void init(ServletConfig config) throws ServletException { super.init(config); servletName = config.getServletName(); // parser the servlet init parameters CAMEL_SERVLET_MAP.put(servletName, this); String contextConfigLocation = config.getInitParameter("contextConfigLocation"); if (contextConfigLocation != null) { //Create a spring application context for it applicationContext = new ClassPathXmlApplicationContext(contextConfigLocation.split(",")); LOG.info("Started the application context rightly"); }// w w w .j a v a 2 s. c o m }
From source file:org.apache.jetspeed.services.resources.JetspeedResourceService.java
public synchronized void init(ServletConfig config) throws InitializationException { String propsDir = null;//from w ww .j a v a 2 s. c o m String appName = config.getServletName(); String deployFilename = appName + ".properties"; String torqueFilename = appName + "_torque.properties"; super.init(config); // Display product information //System.out.println("Jetspeed Services: Starting servlet: [" + appName +"]"); String version = getString(JetspeedResources.JETSPEED_VERSION_KEY); String name = getString(JetspeedResources.JETSPEED_NAME_KEY); if (version != null && name != null) { System.out.println(""); System.out.println("Starting " + name + "/" + version); System.out.println(""); } try { propsDir = System.getProperty("jetspeed.conf.dir", null); if (null == propsDir) { // no deploy-time directory defined to find properties, return return; } String torqueProps = makeFileNamePath(propsDir, torqueFilename); String deployProps = makeFileNamePath(propsDir, deployFilename); System.out.println("torque props = " + torqueProps); System.out.println("deploy props = " + deployProps); File deployFile = new File(deployProps); if (deployFile.exists()) { FileInputStream is = new FileInputStream(deployProps); Properties props = new Properties(); props.load(is); Iterator it = props.entrySet().iterator(); while (it.hasNext()) { Entry entry = (Entry) it.next(); //if (entry.getValue() != null && ((String)entry.getValue()).length() > 0) this.setProperty((String) entry.getKey(), (String) entry.getValue()); System.out.println("setting key/value: " + entry.getKey() + ":" + entry.getValue()); } } else { String msg = "Failed to find Deploy properties: " + deployProps; System.err.println(msg); } File torqueFile = new File(torqueProps); if (torqueFile.exists()) { this.setProperty("component.torque.config", torqueProps); FileInputStream tis = new FileInputStream(torqueProps); Properties tprops = new Properties(); tprops.load(tis); System.out.println("Connecting to: " + tprops.getProperty("database.default.url")); System.out.println("Database Username: " + tprops.getProperty("database.default.username")); } } catch (IOException e) { StringBuffer msg = new StringBuffer("Error reading properties for appName: "); msg.append(appName); msg.append(", props Dir: " + propsDir); System.err.println("Exception in loading properties: " + propsDir); e.printStackTrace(); } }