public void service(HttpServletRequest req, HttpServletResponse res) { try { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><body>"); ServletContext ctx = getServletContext(); String name = (String) ctx.getAttribute("con"); out.println("name= " + name); out.println("</html></body>"); } catch (Exception e) { } }
protected void initializeHandlerChain(PicketLinkType picketLinkType) throws Exception { SAML2HandlerChain handlerChain; // Get the chain from config if (isNullOrEmpty(samlHandlerChainClass)) { handlerChain = SAML2HandlerChainFactory.createChain(); } else { try { handlerChain = SAML2HandlerChainFactory.createChain(this.samlHandlerChainClass); } catch (ProcessingException e1) { throw new RuntimeException(e1); } } Handlers handlers = picketLinkType.getHandlers(); if (handlers == null) { // Get the handlers String handlerConfigFileName = GeneralConstants.HANDLER_CONFIG_FILE_LOCATION; handlers = ConfigurationUtil.getHandlers(servletContext.getResourceAsStream(handlerConfigFileName)); } picketLinkType.setHandlers(handlers); handlerChain.addAll(HandlerUtil.getHandlers(handlers)); populateChainConfig(picketLinkType); SAML2HandlerChainConfig handlerChainConfig = new DefaultSAML2HandlerChainConfig(chainConfigOptions); Set<SAML2Handler> samlHandlers = handlerChain.handlers(); for (SAML2Handler handler : samlHandlers) { handler.initChainConfig(handlerChainConfig); } chain = handlerChain; }
/** * @param context the Servlet context. * @deprecated Now handled in TdsContext.init(). */ public static void initContext(ServletContext context) { // setContextPath(context); if (contextPath == null) { // Servlet 2.5 allows the following. // contextPath = servletContext.getContextPath(); String tmpContextPath = context.getInitParameter("ContextPath"); // cannot be overridden in the ThreddsConfig file if (tmpContextPath == null) tmpContextPath = "thredds"; contextPath = "/" + tmpContextPath; } // setRootPath(context); if (rootPath == null) { rootPath = context.getRealPath("/"); rootPath = rootPath.replace('\\', '/'); } // setContentPath(); if (contentPath == null) { String tmpContentPath = "../../content" + getContextPath() + "/"; File cf = new File(getRootPath(), tmpContentPath); try { contentPath = cf.getCanonicalPath() + "/"; contentPath = contentPath.replace('\\', '/'); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } // initDebugging(context); initDebugging(context); }
/** Run once when servlet loaded. */ public void init(ServletConfig config) throws ServletException { super.init(config); context = config.getServletContext(); theApp = (LockssApp) context.getAttribute(ServletManager.CONTEXT_ATTR_LOCKSS_APP); servletMgr = (ServletManager) context.getAttribute(ServletManager.CONTEXT_ATTR_SERVLET_MGR); if (theApp instanceof LockssDaemon) { acctMgr = getLockssDaemon().getAccountManager(); } }
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write('\n'); out.write('\n'); out.write("\n<!DOCTYPE html>\n<html>\n<head>\n"); JspHelper.createTitle(out, request, request.getParameter("filename")); out.write("\n</head>\n<body onload=\"document.goto.dir.focus()\">\n"); Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF); generateFileChunks(out, request, conf); out.write("\n<hr>\n"); generateFileDetails(out, request, conf); out.write("\n\n<h2>Local logs</h2>\n<a href=\"/logs/\">Log</a> directory\n\n"); out.println(ServletUtil.htmlFooter()); out.write('\n'); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
public void contextInitialized(ServletContextEvent sce) { final ServletContext app = sce.getServletContext(); final Configuration conf = NutchConfiguration.get(app); LOG.info("creating new bean"); NutchBean bean = null; try { bean = new NutchBean(conf); app.setAttribute(KEY, bean); } catch (final IOException ex) { LOG.error(StringUtils.stringifyException(ex)); } }
public void init() throws ServletException { ServletContext ctx = getServletContext(); remoteHost = ctx.getInitParameter("RMI_SERVER"); // Reads the value from the <context-param> in web.xml mh = new MessageHandler(); // Instantiate message handler on service start vmh = new VigenereRequestManager( mh.getQueue(), mh.getMap(), remoteHost); // Instansiate Request manager at service start with references to same // queue and map as message handler executorService.execute(vmh); // Run the Request service daemon }
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String length = request.getParameter("primeLength"); ServletContext context = getServletContext(); synchronized (this) { if ((context.getAttribute("primeBean") == null) || (!isMissing(length))) { PrimeBean primeBean = new PrimeBean(length); context.setAttribute("primeBean", primeBean); } String address = "/WEB-INF/results/show-prime.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); } }
// fix for 4720897 // if the jar file resides in a war file, download it to a temp dir // so it can be used to generate jardiff private String getRealPath(String path) throws IOException { URL fileURL = _servletContext.getResource(path); File tempDir = (File) _servletContext.getAttribute("javax.servlet.context.tempdir"); // download file into temp dir if (fileURL != null) { File newFile = File.createTempFile("temp", ".jar", tempDir); if (download(fileURL, newFile)) { String filePath = newFile.getPath(); return filePath; } } return null; }
public File doAttachment(HttpServletRequest request) throws ServletException, IOException { File file = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<?> items = upload.parseRequest(request); Iterator<?> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { parameters .put(item.getFieldName(), item.getString("UTF-8")); } else { File tempFile = new File(item.getName()); file = new File(sc.getRealPath("/") + savePath, tempFile .getName()); item.write(file); } } } catch (Exception e) { Logger logger = Logger.getLogger(SendAttachmentMailServlet.class); logger.error("邮件发送出了异常", e); } return file; }
public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); servletContext = servletConfig.getServletContext(); try { SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance(); con = scf.createConnection(); } catch (Exception e) { logger.log(Level.SEVERE, "Unable to open a SOAPConnection", e); } InputStream in = servletContext.getResourceAsStream("/WEB-INF/address.properties"); if (in != null) { Properties props = new Properties(); try { props.load(in); to = props.getProperty("to"); data = props.getProperty("data"); } catch (IOException ex) { // Ignore } } }
/** * Add javascript to page. Normally adds a link to the script file, but can be told to include the * script directly in the page, to accomodate unit testing of individual servlets, when other * fetches won't work. */ protected void addJavaScript(Composite comp) { String include = (String) context.getAttribute(ATTR_INCLUDE_SCRIPT); if (StringUtil.isNullString(include)) { linkToJavaScript(comp); } else { includeJavaScript0(comp); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Shared Info"; out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">" + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "<UL>\n" + " <LI>Session:"); HttpSession session = request.getSession(true); Enumeration attributes = session.getAttributeNames(); out.println(getAttributeList(attributes)); out.println(" <LI>Current Servlet Context:"); ServletContext application = getServletContext(); attributes = application.getAttributeNames(); out.println(getAttributeList(attributes)); out.println(" <LI>Servlet Context of /shareTest1:"); application = application.getContext("/shareTest1"); if (application == null) { out.println("Context sharing disabled"); } else { attributes = application.getAttributeNames(); out.println(getAttributeList(attributes)); } out.println(" <LI>Cookies:<UL>"); Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { out.println(" <LI>No cookies found."); } else { Cookie cookie; for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.println(" <LI>" + cookie.getName()); } } out.println(" </UL>\n" + "</UL>\n" + "</BODY></HTML>"); }
/** Initialize JarDiff handler */ public JarDiffHandler(ServletContext servletContext, Logger log) { _jarDiffEntries = new HashMap(); _servletContext = servletContext; _log = log; _jarDiffMimeType = _servletContext.getMimeType("xyz.jardiff"); if (_jarDiffMimeType == null) _jarDiffMimeType = JARDIFF_MIMETYPE; }
public void init() { context = getServletContext(); synchronized (context) { pool = (ConnectionPool) context.getAttribute("pool"); if (pool == null) { String driverClassName = context.getInitParameter("driverClassName"); String url = context.getInitParameter("url"); String userName = context.getInitParameter("username"); String password = context.getInitParameter("password"); try { pool = new ConnectionPool(driverClassName, url, userName, password); } catch (Exception error) { Routines.writeToLog( servletName, "Unable to create connection pool : " + error, false, context); } context.setAttribute("pool", pool); } } }
public void init() throws ServletException { ServletContext context = getServletContext(); String driver = context.getInitParameter("p1"); String cs = context.getInitParameter("p2"); String username = context.getInitParameter("p3"); String password = context.getInitParameter("p4"); try { Class.forName(driver); con = DriverManager.getConnection(cs, username, password); ps = con.prepareStatement( "select * from registration1 where username=? and password=? and user_type=?"); } catch (Exception e) { e.printStackTrace(); } }
private Element getDescription(String task) { if (task != null) { if (task.equals("define")) return definer.getDescription(); if (task.equals("compare")) return comparer.getDescription(); if (task.equals("search")) return searcher.getDescription(); if (task.equals("wikify")) return wikifier.getDescription(); } Element description = doc.createElement("Description"); description.appendChild( createElement( "Details", "<p>This servlet provides a range of services for mining information from Wikipedia. Further details depend on what you want to do.</p>" + "<p>You can <a href=\"" + context.getInitParameter("service_name") + "?task=search&help\">search for pages</a>, <a href=\"" + context.getInitParameter("service_name") + "?task=compare&help\">measure how terms or articles related to each other</a>, <a href=\"" + context.getInitParameter("service_name") + "?task=define&help\">obtain short definitions from articles</a>, and <a href=\"" + context.getInitParameter("service_name") + "?task=wikify&help\">detect topics in web pages</a>.</p>")); Element paramTask = createElement( "Parameter", "Specifies what you want to do: can be <em>search</em>, <em>compare</em>, <em>define</em>, or <em>wikify</em>"); paramTask.setAttribute("name", "task"); description.appendChild(paramTask); Element paramId = doc.createElement("Parameter"); paramId.setAttribute("name", "help"); paramId.appendChild(doc.createTextNode("Specifies that you want help about the service.")); description.appendChild(paramId); return description; }
public static void initDebugging(ServletContext webapp) { if (isDebugInit) return; isDebugInit = true; String debugOn = webapp.getInitParameter("DebugOn"); if (debugOn != null) { StringTokenizer toker = new StringTokenizer(debugOn); while (toker.hasMoreTokens()) Debug.set(toker.nextToken(), true); } }
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HttpSession session = req.getSession(false); ServletContext sc = getServletContext(); RequestDispatcher rd; String strPrizeID = req.getParameter("prizeid"); if (strPrizeID != null) { DataBaseConn DelPrizeDBC = new DataBaseConn(); String sqlStr = "delete from pthwinnum where id='" + Integer.parseInt(strPrizeID) + "';"; DelPrizeDBC.execute(sqlStr); DelPrizeDBC.connCloseUpdate(); } PageInfoGet objPageInfoGet = new PageInfoGet(); String strChSql = "select id from pthwinnum"; objPageInfoGet.generInfo(req, "pthwinnum", strChSql); session.setAttribute("userpc", objPageInfoGet.getUserPageConn()); session.setAttribute("bepagshow", objPageInfoGet.getBeanPageShow()); rd = sc.getRequestDispatcher("/WEB-INF/usermanage/pth/pthprizepage.jsp"); rd.forward(req, res); }
// Added in Servlet 2.5 public String getContextPath() { try { Method getContextPathMethod = servletContext.getClass().getMethod("getContextPath", (Class<?>[]) null); // $NON-NLS-1$ return (String) getContextPathMethod.invoke(servletContext, (Object[]) null) + proxyContext.getServletPath(); } catch (Exception e) { // ignore } return null; }
/** * Initializes the servlet context, based on the servlet context. Parses all context parameters * and passes them on to the database context. * * @param sc servlet context * @throws IOException I/O exception */ static synchronized void init(final ServletContext sc) throws IOException { // skip process if context has already been initialized if (context != null) return; // set servlet path as home directory final String path = sc.getRealPath("/"); System.setProperty(Prop.PATH, path); // parse all context parameters final HashMap<String, String> map = new HashMap<String, String>(); // store default web root map.put(MainProp.HTTPPATH[0].toString(), path); final Enumeration<?> en = sc.getInitParameterNames(); while (en.hasMoreElements()) { final String key = en.nextElement().toString(); if (!key.startsWith(Prop.DBPREFIX)) continue; // only consider parameters that start with "org.basex." String val = sc.getInitParameter(key); if (eq(key, DBUSER, DBPASS, DBMODE, DBVERBOSE)) { // store servlet-specific parameters as system properties System.setProperty(key, val); } else { // prefix relative paths with absolute servlet path if (key.endsWith("path") && !new File(val).isAbsolute()) { val = path + File.separator + val; } // store remaining parameters (without project prefix) in map map.put(key.substring(Prop.DBPREFIX.length()).toUpperCase(Locale.ENGLISH), val); } } context = new Context(map); if (SERVER.equals(System.getProperty(DBMODE))) { new BaseXServer(context); } else { context.log = new Log(context); } }
/** Check to see if the configuration file has been updated so that it may be reloaded. */ private boolean configUpdated() { try { URL url = ctx.getResource(resourcesDir + XHP_CONFIG); URLConnection con; if (url == null) return false; con = url.openConnection(); long lastModified = con.getLastModified(); long XHP_LAST_MODIFIEDModified = 0; if (ctx.getAttribute(XHP_LAST_MODIFIED) != null) { XHP_LAST_MODIFIEDModified = ((Long) ctx.getAttribute(XHP_LAST_MODIFIED)).longValue(); } else { ctx.setAttribute(XHP_LAST_MODIFIED, new Long(lastModified)); return false; } if (XHP_LAST_MODIFIEDModified < lastModified) { ctx.setAttribute(XHP_LAST_MODIFIED, new Long(lastModified)); return true; } } catch (Exception ex) { getLogger().severe("XmlHttpProxyServlet error checking configuration: " + ex); } return false; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get the number of workers to run int count = this.getRequestedCount(request, 4); // get the executor service final ServletContext sc = this.getServletContext(); final ExecutorService executorService = (ExecutorService) sc.getAttribute("myExecutorService"); // create work coordinator CountDownLatch countDownLatch = new CountDownLatch(count); Long t1 = System.nanoTime(); // create the workers List<RunnableWorkUnit2> workers = new ArrayList<RunnableWorkUnit2>(); for (int i = 0; i < count; i++) { RunnableWorkUnit2 wu = new RunnableWorkUnit2("RunnableTask" + String.valueOf(i + 1), countDownLatch); workers.add(wu); } // run the workers through the executor for (RunnableWorkUnit2 wu : workers) { executorService.execute(wu); } try { System.out.println("START WAITING"); countDownLatch.await(); System.out.println("DONE WAITING"); } catch (InterruptedException ex) { ex.printStackTrace(); } Long t2 = System.nanoTime(); Writer w = response.getWriter(); w.write(String.format("\n Request processed in %dms!", (t2 - t1) / 1000000)); w.flush(); w.close(); }
/** * Initializes the database context, based on the initial servlet context. Parses all context * parameters and passes them on to the database context. * * @param sc servlet context * @throws IOException I/O exception */ public static synchronized void init(final ServletContext sc) throws IOException { // check if HTTP context has already been initialized if (init) return; init = true; // set web application path as home directory and HTTPPATH final String webapp = sc.getRealPath("/"); Options.setSystem(Prop.PATH, webapp); Options.setSystem(GlobalOptions.WEBPATH, webapp); // bind all parameters that start with "org.basex." to system properties final Enumeration<String> en = sc.getInitParameterNames(); while (en.hasMoreElements()) { final String key = en.nextElement(); if (!key.startsWith(Prop.DBPREFIX)) continue; String val = sc.getInitParameter(key); if (key.endsWith("path") && !new File(val).isAbsolute()) { // prefix relative path with absolute servlet path Util.debug(key.toUpperCase(Locale.ENGLISH) + ": " + val); val = new IOFile(webapp, val).path(); } Options.setSystem(key, val); } // create context, update options if (context == null) { context = new Context(false); } else { context.globalopts.setSystem(); context.options.setSystem(); } // start server instance if (!context.globalopts.get(GlobalOptions.HTTPLOCAL)) new BaseXServer(context); }
public static void showServletInfo(HttpServlet servlet, PrintStream out) { out.println("Servlet Info"); out.println(" getServletName(): " + servlet.getServletName()); out.println(" getRootPath(): " + getRootPath()); out.println(" Init Parameters:"); Enumeration params = servlet.getInitParameterNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); out.println(" " + name + ": " + servlet.getInitParameter(name)); } out.println(); ServletContext context = servlet.getServletContext(); out.println("Context Info"); try { out.println(" context.getResource('/'): " + context.getResource("/")); } catch (java.net.MalformedURLException e) { } // cant happen out.println(" context.getServerInfo(): " + context.getServerInfo()); out.println(" name: " + getServerInfoName(context.getServerInfo())); out.println(" version: " + getServerInfoVersion(context.getServerInfo())); out.println(" context.getInitParameterNames():"); params = context.getInitParameterNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); out.println(" " + name + ": " + context.getInitParameter(name)); } out.println(" context.getAttributeNames():"); params = context.getAttributeNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); out.println(" context.getAttribute(\"" + name + "\"): " + context.getAttribute(name)); } out.println(); }
private void getServices(HttpServletResponse res) { InputStream is = null; try { URL url = ctx.getResource(resourcesDir + XHP_CONFIG); // use classpath if not found locally. if (url == null) url = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + XHP_CONFIG); is = url.openStream(); } catch (Exception ex) { try { getLogger().severe("XmlHttpProxyServlet error loading xhp.json : " + ex); PrintWriter writer = res.getWriter(); writer.write( "XmlHttpProxyServlet Error: Error loading xhp.json. Make sure it is available in the /resources directory of your applicaton."); writer.flush(); } catch (Exception iox) { } } services = xhp.loadServices(is); }
protected void processConfiguration(FilterConfig filterConfig) { InputStream is; if (isNullOrEmpty(this.configFile)) { is = servletContext.getResourceAsStream(CONFIG_FILE_LOCATION); } else { try { is = new FileInputStream(this.configFile); } catch (FileNotFoundException e) { throw logger.samlIDPConfigurationError(e); } } PicketLinkType picketLinkType; String configurationProviderName = filterConfig.getInitParameter(CONFIGURATION_PROVIDER); if (configurationProviderName != null) { try { Class<?> clazz = SecurityActions.loadClass(getClass(), configurationProviderName); if (clazz == null) { throw new ClassNotFoundException(ErrorCodes.CLASS_NOT_LOADED + configurationProviderName); } this.configProvider = (SAMLConfigurationProvider) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException( "Could not create configuration provider [" + configurationProviderName + "].", e); } } try { // Work on the IDP Configuration if (configProvider != null) { try { if (is == null) { // Try the older version is = servletContext.getResourceAsStream( GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION); // Additionally parse the deprecated config file if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) { ((AbstractSAMLConfigurationProvider) configProvider).setConfigFile(is); } } else { // Additionally parse the consolidated config file if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) { ((AbstractSAMLConfigurationProvider) configProvider).setConsolidatedConfigFile(is); } } picketLinkType = configProvider.getPicketLinkConfiguration(); picketLinkType.setIdpOrSP(configProvider.getSPConfiguration()); } catch (ProcessingException e) { throw logger.samlSPConfigurationError(e); } catch (ParsingException e) { throw logger.samlSPConfigurationError(e); } } else { if (is != null) { try { picketLinkType = ConfigurationUtil.getConfiguration(is); } catch (ParsingException e) { logger.trace(e); throw logger.samlSPConfigurationError(e); } } else { is = servletContext.getResourceAsStream(GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION); if (is == null) { throw logger.configurationFileMissing(configFile); } picketLinkType = new PicketLinkType(); picketLinkType.setIdpOrSP(ConfigurationUtil.getSPConfiguration(is)); } } // Close the InputStream as we no longer need it if (is != null) { try { is.close(); } catch (IOException e) { // ignore } } Boolean enableAudit = picketLinkType.isEnableAudit(); // See if we have the system property enabled if (!enableAudit) { String sysProp = SecurityActions.getSystemProperty(GeneralConstants.AUDIT_ENABLE, "NULL"); if (!"NULL".equals(sysProp)) { enableAudit = Boolean.parseBoolean(sysProp); } } if (enableAudit) { if (auditHelper == null) { String securityDomainName = PicketLinkAuditHelper.getSecurityDomainName(servletContext); auditHelper = new PicketLinkAuditHelper(securityDomainName); } } SPType spConfiguration = (SPType) picketLinkType.getIdpOrSP(); processIdPMetadata(spConfiguration); this.serviceURL = spConfiguration.getServiceURL(); this.canonicalizationMethod = spConfiguration.getCanonicalizationMethod(); this.picketLinkConfiguration = picketLinkType; this.issuerID = filterConfig.getInitParameter(ISSUER_ID); this.characterEncoding = filterConfig.getInitParameter(CHARACTER_ENCODING); this.samlHandlerChainClass = filterConfig.getInitParameter(SAML_HANDLER_CHAIN_CLASS); logger.samlSPSettingCanonicalizationMethod(canonicalizationMethod); XMLSignatureUtil.setCanonicalizationMethodType(canonicalizationMethod); try { this.initKeyProvider(); this.initializeHandlerChain(picketLinkType); } catch (Exception e) { throw new RuntimeException(e); } logger.trace("Identity Provider URL=" + getConfiguration().getIdentityURL()); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Returns the cached instance in the servlet context. * * @see NutchBeanConstructor */ public static NutchBean get(ServletContext app, Configuration conf) throws IOException { final NutchBean bean = (NutchBean) app.getAttribute(KEY); return bean; }
public void init(ServletConfig config) throws ServletException { super.init(config); ctx = config.getServletContext(); // set the response content type if (ctx.getInitParameter("responseContentType") != null) { responseContentType = ctx.getInitParameter("responseContentType"); } // allow for resources dir over-ride at the xhp level otherwise allow // for the jmaki level resources if (ctx.getInitParameter("jmaki-xhp-resources") != null) { resourcesDir = ctx.getInitParameter("jmaki-xhp-resources"); } else if (ctx.getInitParameter("jmaki-resources") != null) { resourcesDir = ctx.getInitParameter("jmaki-resources"); } // allow for resources dir over-ride if (ctx.getInitParameter("jmaki-classpath-resources") != null) { classpathResourcesDir = ctx.getInitParameter("jmaki-classpath-resources"); } String requireSessionString = ctx.getInitParameter("requireSession"); if (requireSessionString != null) { if ("false".equals(requireSessionString)) { requireSession = false; getLogger().severe("XmlHttpProxyServlet: intialization. Session requirement disabled."); } else if ("true".equals(requireSessionString)) { requireSession = true; getLogger().severe("XmlHttpProxyServlet: intialization. Session requirement enabled."); } } String xdomainString = ctx.getInitParameter("allowXDomain"); if (xdomainString != null) { if ("true".equals(xdomainString)) { allowXDomain = true; getLogger().severe("XmlHttpProxyServlet: intialization. xDomain access is enabled."); } else if ("false".equals(xdomainString)) { allowXDomain = false; getLogger().severe("XmlHttpProxyServlet: intialization. xDomain access is disabled."); } } // if there is a proxyHost and proxyPort specified create an HttpClient with the proxy String proxyHost = ctx.getInitParameter("proxyHost"); String proxyPortString = ctx.getInitParameter("proxyPort"); if (proxyHost != null && proxyPortString != null) { int proxyPort = 8080; try { proxyPort = new Integer(proxyPortString).intValue(); xhp = new XmlHttpProxy(proxyHost, proxyPort); } catch (NumberFormatException nfe) { getLogger() .severe("XmlHttpProxyServlet: intialization error. The proxyPort must be a number"); throw new ServletException( "XmlHttpProxyServlet: intialization error. The proxyPort must be a number"); } } else { xhp = new XmlHttpProxy(); } }
public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) { StringBuffer bodyContent = null; OutputStream out = null; PrintWriter writer = null; String serviceKey = null; try { BufferedReader in = req.getReader(); String line = null; while ((line = in.readLine()) != null) { if (bodyContent == null) bodyContent = new StringBuffer(); bodyContent.append(line); } } catch (Exception e) { } try { if (requireSession) { // check to see if there was a session created for this request // if not assume it was from another domain and blow up // Wrap this to prevent Portlet exeptions HttpSession session = req.getSession(false); if (session == null) { res.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } serviceKey = req.getParameter("id"); // only to preven regressions - Remove before 1.0 if (serviceKey == null) serviceKey = req.getParameter("key"); // check if the services have been loaded or if they need to be reloaded if (services == null || configUpdated()) { getServices(res); } String urlString = null; String xslURLString = null; String userName = null; String password = null; String format = "json"; String callback = req.getParameter("callback"); String urlParams = req.getParameter("urlparams"); String countString = req.getParameter("count"); // encode the url to prevent spaces from being passed along if (urlParams != null) { urlParams = urlParams.replace(' ', '+'); } try { if (services.has(serviceKey)) { JSONObject service = services.getJSONObject(serviceKey); // default to the service default if no url parameters are specified if (urlParams == null && service.has("defaultURLParams")) { urlParams = service.getString("defaultURLParams"); } String serviceURL = service.getString("url"); // build the URL if (urlParams != null && serviceURL.indexOf("?") == -1) { serviceURL += "?"; } else if (urlParams != null) { serviceURL += "&"; } String apikey = ""; if (service.has("username")) userName = service.getString("username"); if (service.has("password")) password = service.getString("password"); if (service.has("apikey")) apikey = service.getString("apikey"); urlString = serviceURL + apikey; if (urlParams != null) urlString += "&" + urlParams; if (service.has("xslStyleSheet")) { xslURLString = service.getString("xslStyleSheet"); } } // code for passing the url directly through instead of using configuration file else if (req.getParameter("url") != null) { String serviceURL = req.getParameter("url"); // build the URL if (urlParams != null && serviceURL.indexOf("?") == -1) { serviceURL += "?"; } else if (urlParams != null) { serviceURL += "&"; } urlString = serviceURL; if (urlParams != null) urlString += urlParams; } else { writer = res.getWriter(); if (serviceKey == null) writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required."); else writer.write( "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not found."); writer.flush(); return; } } catch (Exception ex) { getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex); } Map paramsMap = new HashMap(); paramsMap.put("format", format); // do not allow for xdomain unless the context level setting is enabled. if (callback != null && allowXDomain) { paramsMap.put("callback", callback); } if (countString != null) { paramsMap.put("count", countString); } InputStream xslInputStream = null; if (urlString == null) { writer = res.getWriter(); writer.write( "XmlHttpProxyServlet parameters: id[Required] urlparams[Optional] format[Optional] callback[Optional]"); writer.flush(); return; } // default to JSON res.setContentType(responseContentType); out = res.getOutputStream(); // get the stream for the xsl stylesheet if (xslURLString != null) { // check the web root for the resource URL xslURL = null; xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString); // if not in the web root check the classpath if (xslURL == null) { xslURL = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString); } if (xslURL != null) { xslInputStream = xslURL.openStream(); } else { String message = "Could not locate the XSL stylesheet provided for service id " + serviceKey + ". Please check the XMLHttpProxy configuration."; getLogger().severe(message); try { out.write(message.getBytes()); out.flush(); return; } catch (java.io.IOException iox) { } } } if (!isPost) { xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password); } else { if (bodyContent == null) getLogger() .info( "XmlHttpProxyServlet attempting to post to url " + urlString + " with no body content"); xhp.doPost( urlString, out, xslInputStream, paramsMap, bodyContent.toString(), req.getContentType(), userName, password); } } catch (Exception iox) { iox.printStackTrace(); getLogger().severe("XmlHttpProxyServlet: caught " + iox); try { writer = res.getWriter(); writer.write(iox.toString()); writer.flush(); } catch (java.io.IOException ix) { ix.printStackTrace(); } return; } finally { try { if (out != null) out.close(); if (writer != null) writer.close(); } catch (java.io.IOException iox) { } } }