⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ajaxservlet.java

📁 java开源的企业总线.xmlBlaster
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		}		String mimeType = (String) req.getParameter("mimeType");		String charset = (String) req.getParameter("charset");		log.info(id + " Making the request for 'plainGet' with topic='" + topic + "' mimeType='"				+ mimeType + "' charset='" + charset + "'");		res.setContentType("text/xml; charset=UTF-8");		GetKey key = new GetKey(this.glob, topic);		GetQos qos = new GetQos(this.glob);		MsgUnit[] ret = this.xmlBlasterAccess.get(key, qos);		if (ret != null && ret.length > 0) {			if (ret.length > 1)				log.warning(id + " " + ret.length						+ " entries are found but only the first will be sent back to the client");			if (mimeType == null)				mimeType = ret[0].getContentMime();			if (mimeType == null)				mimeType = "text/xml";			if (charset == null)				charset = "UTF-8";			res.setContentType(mimeType + "; charset=" + charset);			out.write(ret[0].getContentStr());		} else			log.info(id + " No entry found for topic '" + topic + "'");	}}/** * Detect when a servlet session dies (with tomcat typically after one hour). * @author Marcel Ruff xmlBlaster@marcelruff.info 2007 */class SessionTimeoutListener implements HttpSessionBindingListener {	private static Logger log = Logger.getLogger(SessionTimeoutListener.class.getName());	private BlasterInstance blasterInstance;	public SessionTimeoutListener(BlasterInstance blasterInstance) {		this.blasterInstance = blasterInstance;	}	public void valueBound(HttpSessionBindingEvent event) {		log.info("Session is bound: " + event.getSession().getId());	}	public void valueUnbound(HttpSessionBindingEvent event) {		log.info("Session is unbound: " + event.getSession().getId());		this.blasterInstance.shutdown();	}}/** * This servlet supports requests from a browser, it queries the topic given by * "gpsTopicId" configuration which needs to contain GPS coordinates (published * for example by a PDA). * * <p> * Use xmlBlaster/demo/http/gps.html to display the coordinates in a map. * </p> *  * Callback messages are send as xml to the browser: * <pre> * &lt;xmlBlasterResponse> *  &lt;update> *    &lt;qos>...&lt;/qos> *    &lt;key>...&lt;/key> *    &lt;content>...&lt;/content> *  &lt;/update> * &lt;/xmlBlasterResponse> * </pre> * @author Marcel Ruff xmlBlaster@marcelruff.info 2007 */public class AjaxServlet extends HttpServlet {	private static final long serialVersionUID = -8094289301696678030L;	private static Logger log = Logger.getLogger(AjaxServlet.class.getName());	private Properties props = new Properties();	private int maxInactiveInterval = 1800; // sec, see web.xml and javadoc of doGet() for details	/** key is the browser sessionId */	private Map/*<String, BlasterInstance>*/blasterInstanceMap;	public void init(ServletConfig conf) throws ServletException {		super.init(conf);		// Add the web.xml parameters to our environment settings:		Enumeration enumer = conf.getInitParameterNames();		while (enumer.hasMoreElements()) {			String name = (String) enumer.nextElement();			if (name != null && name.length() > 0)				props.setProperty(name, conf.getInitParameter(name));		}		String tmp = props.getProperty("maxInactiveInterval");		if (tmp != null)			this.maxInactiveInterval = Integer.valueOf(tmp).intValue();		this.blasterInstanceMap = new HashMap/*<String, BlasterInstance>*/();	}	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,			IOException {		doGet(req, res);	}	/**	 * <pre>	 * ServletSessionTimeout according to specification:	 * The default timeout period for sessions is defined by the servlet container and	 *	can be obtained via the getMaxInactiveInterval method of the HttpSession	 *	interface. This timeout can be changed by the Developer using the	 *	setMaxInactiveInterval method of the HttpSession interface. The timeout	 *	periods used by these methods are defined in seconds. By definition, if the timeout	 *	period for a session is set to -1, the session will never expire.	 * </pre>	 * <p>     * We have set the maxInactiveInterval to 1800 sec in web.xml (30 min):     * <p/>     * If no Ajax call arrives after the given timeout the servlet-session dies,     * as a browser user may choose to halt NMEA updates we must     * set this to a high enough value.     * <p/>	 * The web.xml setting &lt;session-config>     *       <session-timeout>30</session-timeout>     *       &lt;/session-config>     * is overwritten by our maxInactiveInterval	 */	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,			IOException {		String host = req.getRemoteAddr();		String ME = "AjaxServlet.doGet(" + host + "): ";		//log.info("ENTERING DOGET ....");		boolean forceLoad = req.getParameter("forceLoad") != null;		if (forceLoad)			log(ME + "forceLoad=" + forceLoad);		boolean newBrowser = false;		if (req.getSession(false) == null) {			HttpSession session = req.getSession(true);			session.setMaxInactiveInterval(this.maxInactiveInterval);			newBrowser = true;			log(ME + "new browser arrived, charset=" + req.getCharacterEncoding());		}		// set header field first		//res.setContentType("text/plain; charset=UTF-8");		// xml header don't like empty response, so send at least "<void/>		res.setContentType("text/xml; charset=UTF-8");		StringWriter out = new StringWriter();		try {			BlasterInstance blasterInstance = getBlasterInstance(req);			String actionType = (String) req.getParameter("ActionType");			if (actionType == null) {				log("Missing ActionType, ignoring request");				return;			}			// TODO: handle logout script to also destroy the session entry			if (actionType.equals("xmlScript")) {				String xmlScript64 = (String) req.getParameter("xmlScriptBase64");				String xmlScriptPlain = (String) req.getParameter("xmlScriptPlain");				byte[] raw = null;				if (xmlScript64 != null && xmlScriptPlain != null) {					String errTxt = "You can not set both 'xmlScriptBase64' and 'xmlScriptPlain'";					out.write(errTxt);					return;				}				if (xmlScript64 != null) {					// the url encoder has somewhere changed my + to blanks					// you must send this by invoking encodeURIComponent(txt) on the javascript side.					xmlScript64 = ReplaceVariable.replaceAll(xmlScript64, " ", "+");					raw = Base64.decode(xmlScript64);				} else if (xmlScriptPlain != null) {					raw = xmlScriptPlain.getBytes();				} else {					String errTxt = "You must choose one of 'xmlScriptBase64' and 'xmlScriptPlain' since you choosed 'xmlScript'";					out.write(errTxt);					return;				}				blasterInstance.execute(raw, out);				return;			}		   /* see watchee.js for an example:		   In the mode "updatePoll" this script polls every 8000 millis for update		   and the servlet returns directly if nothing is available, this is suboptimal		   as we have a delay of up to 8 seconds.		   In the mode "updatePollBlocking" we don't poll but the servlet blocks our call		   and immediately returns when update messages arrive.		   To prevent from e.g. proxy timeouts the servlet returns after 15sec and we immediately		   poll again.		   */			// "timeout" and "numEntries" is only evaluated for "updatePollBlocking"			boolean updatePoll = actionType.equals("updatePoll");			boolean updatePollBlocking = actionType.equals("updatePollBlocking");			if (updatePoll || updatePollBlocking) {				boolean onlyContent = get(req, "onlyContent", false);				long timeout = get(req, "timeout", (updatePoll) ? 0L : 15000L);				int numEntries = get(req, "numEntries", -1);				int count = blasterInstance.sendUpdates(out, onlyContent, numEntries, timeout);				if (count == 0) { // watchee hack					if (newBrowser || forceLoad) {						String initGps = (String) req.getParameter("initGps");						if (initGps != null && "true".equalsIgnoreCase(initGps.trim())) {							String tmp = blasterInstance.getStartupPos();							if (tmp.length() > 0) {								out.write(tmp);								log(ME + tmp);							}						}					}				} else					log(ME + " Sending " + count + " received update messages to browser");				return;			}			if (actionType.equals("plainGet")) {				blasterInstance.plainGet(req, res, out);			}			// log(ME+"Ignoring identical");		} catch (XmlBlasterException e) {			log.warning("newBrowser=" + newBrowser + " forceLoad=" + forceLoad + ": "					+ e.toString());			log("newBrowser=" + newBrowser + " forceLoad=" + forceLoad + ": " + e.toString());			// if (newBrowser || forceLoad)			// out.write(blasterInstance.getStartupPos());		} catch (Throwable e) {			log					.severe("newBrowser=" + newBrowser + " forceLoad=" + forceLoad + ": "							+ e.toString());			e.printStackTrace();			log("newBrowser=" + newBrowser + " forceLoad=" + forceLoad + ": " + e.toString());		} finally {			PrintWriter backToBrowser = res.getWriter();			if (out.getBuffer().length() > 0)				log.info("Sending now '" + out.getBuffer().toString() + "'");			if (out.getBuffer().length() > 0)				backToBrowser.write(out.getBuffer().toString());			else				backToBrowser.write("<void/>"); // text/xml needs at least a root tag!			backToBrowser.close();		}	}	public boolean get(HttpServletRequest req, String key, boolean defaultVal) {		String value = (String) req.getParameter(key);		if (value == null) return defaultVal;		return "true".equalsIgnoreCase(value.trim());	}	public long get(HttpServletRequest req, String key, long defaultVal) {		String value = (String) req.getParameter(key);		if (value == null) return defaultVal;		try {			return Long.parseLong(value.trim());		}		catch (NumberFormatException e) {			return defaultVal;		}	}	public int get(HttpServletRequest req, String key, int defaultVal) {		String value = (String) req.getParameter(key);		if (value == null) return defaultVal;		try {			return Integer.parseInt(value.trim());		}		catch (NumberFormatException e) {			return defaultVal;		}	}	private synchronized BlasterInstance getBlasterInstance(HttpServletRequest req)			throws XmlBlasterException {		// Map blasterInstanceMap =		// (Map)session.getAttribute("blasterInstanceMap");		BlasterInstance blasterInstance = null;		synchronized (this.blasterInstanceMap) {			blasterInstance = (BlasterInstance) this.blasterInstanceMap.get(req.getSession()					.getId());			if (blasterInstance != null)				return blasterInstance;			blasterInstance = new BlasterInstance(req, this.blasterInstanceMap);		}		blasterInstance.init(req, props);		// is done in ctor		// this.blasterInstanceMap.put(req.getSession().getId(),		// blasterInstance);		return blasterInstance;	}	public String getServletInfo() {		return "Personalized access to xmlBlaster with XmlScript";	}	public BlasterInstance[] getBlasterInstances() {		synchronized (this.blasterInstanceMap) {			return (BlasterInstance[]) this.blasterInstanceMap.values().toArray(					new BlasterInstance[this.blasterInstanceMap.size()]);		}	}	public synchronized void destroy() {		BlasterInstance[] instances = getBlasterInstances();		for (int i = 0; i < instances.length; i++) {			instances[i].shutdown();		}		synchronized (this.blasterInstanceMap) {			// is redundant, is done in instace.shutdown			this.blasterInstanceMap.clear();		}	}	public void log(String text) {		// System.err.println("ERR"+text);		// System.out.println("OUT"+text);		super.log(text);	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -