/** Deserializes the object from XML */ public Serializable fromXml(XmppStreamReader in) throws IOException, XMLStreamException { boolean isFinest = log.isLoggable(Level.FINEST); String type = in.getAttributeValue(null, "type"); DataForm form = new DataForm(type); ArrayList<DataField> fieldList = new ArrayList<DataField>(); ArrayList<DataItem> itemList = new ArrayList<DataItem>(); ArrayList<DataInstructions> instructionsList = new ArrayList<DataInstructions>(); int tag = in.nextTag(); while (tag > 0) { if (isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { form.setFieldList(fieldList); form.setItemList(itemList); form.setInstructionsList(instructionsList); return form; } if (XMLStreamReader.START_ELEMENT == tag && "field".equals(in.getLocalName())) { fieldList.add(parseField(in)); } else if (XMLStreamReader.START_ELEMENT == tag && "item".equals(in.getLocalName())) { itemList.add(parseItem(in)); } else if (XMLStreamReader.START_ELEMENT == tag && "reported".equals(in.getLocalName())) { form.setReported(parseReported(in)); } else if (XMLStreamReader.START_ELEMENT == tag && "title".equals(in.getLocalName())) { String title = in.getElementText(); form.setTitle(title); skipToEnd(in, "title"); } else if (XMLStreamReader.START_ELEMENT == tag && "instructions".equals(in.getLocalName())) { String value = in.getElementText(); instructionsList.add(new DataInstructions(value)); skipToEnd(in, "instructions"); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } return null; }
/** * Returns true if the user represented by the current request plays the named role. * * @param role the named role to test. * @return true if the user plays the role. */ public boolean isUserInRole(String role) { ServletInvocation invocation = getInvocation(); if (invocation == null) { if (getRequest() != null) return getRequest().isUserInRole(role); else return false; } HashMap<String, String> roleMap = invocation.getSecurityRoleMap(); if (roleMap != null) { String linkRole = roleMap.get(role); if (linkRole != null) role = linkRole; } String runAs = getRunAs(); if (runAs != null) return runAs.equals(role); WebApp webApp = getWebApp(); Principal user = getUserPrincipal(); if (user == null) { if (log.isLoggable(Level.FINE)) log.fine(this + " no user for isUserInRole"); return false; } RoleMapManager roleManager = webApp != null ? webApp.getRoleMapManager() : null; if (roleManager != null) { Boolean result = roleManager.isUserInRole(role, user); if (result != null) { if (log.isLoggable(Level.FINE)) log.fine(this + " userInRole(" + role + ")->" + result); return result; } } Login login = webApp == null ? null : webApp.getLogin(); boolean inRole = login != null && login.isUserInRole(user, role); if (log.isLoggable(Level.FINE)) { if (login == null) log.fine(this + " no Login for isUserInRole"); else if (user == null) log.fine(this + " no user for isUserInRole"); else if (inRole) log.fine(this + " " + user + " is in role: " + role); else log.fine(this + " failed " + user + " in role: " + role); } return inRole; }
private void initDriverList() { try { Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver"); while (iter.hasMoreElements()) { URL url = (URL) iter.nextElement(); ReadStream is = null; try { is = Vfs.lookup(url.toString()).openRead(); String filename; while ((filename = is.readLine()) != null) { int p = filename.indexOf('#'); if (p >= 0) filename = filename.substring(0, p); filename = filename.trim(); if (filename.length() == 0) continue; try { Class cl = Class.forName(filename, false, loader); Driver driver = null; if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance(); if (driver != null) { log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName())); _driverList.add(driver); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } finally { if (is != null) is.close(); } } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } }
/** Deserializes the object from XML */ public DataReported parseReported(XMLStreamReader in) throws IOException, XMLStreamException { DataReported reported = new DataReported(); ArrayList<DataField> fieldList = new ArrayList<DataField>(); int tag = in.nextTag(); while (tag > 0) { if (_isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { reported.setFieldList(fieldList); return reported; } if (XMLStreamReader.START_ELEMENT == tag && "field".equals(in.getLocalName())) { fieldList.add(parseField(in)); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } skipToEnd(in, "reported"); return reported; }
@Override public boolean login(boolean isFail) { try { WebApp webApp = getWebApp(); if (webApp == null) { if (log.isLoggable(Level.FINE)) log.finer("authentication failed, no web-app found"); getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return false; } // If the authenticator can find the user, return it. Login login = webApp.getLogin(); if (login != null) { Principal user = login.login(this, getResponse(), isFail); return user != null; /* if (user == null) return false; setAttribute(AbstractLogin.LOGIN_NAME, user); return true; */ } else if (isFail) { if (log.isLoggable(Level.FINE)) log.finer("authentication failed, no login module found for " + webApp); getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return false; } else { // if a non-failure, then missing login is fine return false; } } catch (IOException e) { log.log(Level.FINE, e.toString(), e); return false; } }
/** Deserializes the object from XML */ public DataField parseField(XMLStreamReader in) throws IOException, XMLStreamException { String label = in.getAttributeValue(null, "label"); String type = in.getAttributeValue(null, "type"); String var = in.getAttributeValue(null, "var"); DataField field = new DataField(type, var, label); ArrayList<DataValue> valueList = new ArrayList<DataValue>(); ArrayList<DataOption> optionList = new ArrayList<DataOption>(); int tag = in.nextTag(); while (tag > 0) { if (_isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { field.setValueList(valueList); field.setOptionList(optionList); return field; } if (XMLStreamReader.START_ELEMENT == tag && "desc".equals(in.getLocalName())) { String desc = in.getElementText(); field.setDesc(desc); skipToEnd(in, "desc"); } else if (XMLStreamReader.START_ELEMENT == tag && "option".equals(in.getLocalName())) { optionList.add(parseOption(in)); } else if (XMLStreamReader.START_ELEMENT == tag && "required".equals(in.getLocalName())) { field.setRequired(true); skipToEnd(in, "required"); } else if (XMLStreamReader.START_ELEMENT == tag && "value".equals(in.getLocalName())) { String value = in.getElementText(); valueList.add(new DataValue(value)); skipToEnd(in, "value"); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } skipToEnd(in, "field"); return field; }
private String findDriverByUrlImpl(String url) { for (int i = 0; i < _driverList.size(); i++) { try { Driver driver = (Driver) _driverList.get(i); if (driver.acceptsURL(url)) return driver.getClass().getName(); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } return null; }
/** Deserializes the object from XML */ public DataOption parseOption(XMLStreamReader in) throws IOException, XMLStreamException { String label = in.getAttributeValue(null, "label"); DataOption option = new DataOption(label); ArrayList<DataValue> valueList = new ArrayList<DataValue>(); int tag = in.nextTag(); while (tag > 0) { if (_isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { option.setValueList(valueList); return option; } if (XMLStreamReader.START_ELEMENT == tag && "value".equals(in.getLocalName())) { String value = in.getElementText(); valueList.add(new DataValue(value)); skipToEnd(in, "value"); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } skipToEnd(in, "option"); return option; }
/** * DataForm * * <p>XEP-0004: http://www.xmpp.org/extensions/xep-0004.html <code><pre> * namespace = jabber:x:data * * element x { * attribute type, * * instructions*, * title?, * field*, * reported?, * item* * } * * element field { * attribute label?, * attribute type?, * attribute var?, * * desc?, * required?, * value*, * option*, * } * * element item { * field+ * } * * element option { * attribute label?, * * value* * } * * element reported { * field+ * } * * element value { * string * } * </pre></code> */ public class XmppDataFormMarshal extends AbstractXmppMarshal { private static final Logger log = Logger.getLogger(XmppDataFormMarshal.class.getName()); private static final boolean _isFinest = log.isLoggable(Level.FINEST); /** Returns the namespace uri for the XMPP stanza value */ public String getNamespaceURI() { return "jabber:x:data"; } /** Returns the local name for the XMPP stanza value */ public String getLocalName() { return "x"; } /** Returns the java classname of the object */ public String getClassName() { return DataForm.class.getName(); } /** Serializes the object to XML */ public void toXml(XmppStreamWriter out, Serializable object) throws IOException, XMLStreamException { DataForm form = (DataForm) object; out.writeStartElement("", getLocalName(), getNamespaceURI()); out.writeNamespace("", getNamespaceURI()); if (form.getType() != null) out.writeAttribute("type", form.getType()); if (form.getTitle() != null) { out.writeStartElement("title"); out.writeCharacters(form.getTitle()); out.writeEndElement(); // </title> } DataInstructions[] instructions = form.getInstructions(); if (instructions != null) { for (DataInstructions instruction : instructions) { toXml(out, instruction); } } DataField[] fields = form.getField(); if (fields != null) { for (DataField field : fields) { toXml(out, field); } } if (form.getReported() != null) toXml(out, form.getReported()); DataItem[] items = form.getItem(); if (items != null) { for (DataItem item : items) { toXml(out, item); } } out.writeEndElement(); // </form> } private void toXml(XmppStreamWriter out, DataField field) throws IOException, XMLStreamException { out.writeStartElement("field"); if (field.getLabel() != null) out.writeAttribute("label", field.getLabel()); if (field.getType() != null) out.writeAttribute("type", field.getType()); if (field.getVar() != null) out.writeAttribute("var", field.getVar()); if (field.getDesc() != null) { out.writeStartElement("desc"); out.writeCharacters(field.getDesc()); out.writeEndElement(); // </desc> } if (field.isRequired()) { out.writeStartElement("required"); out.writeEndElement(); // </required> } DataValue[] values = field.getValue(); if (values != null) { for (int i = 0; i < values.length; i++) { DataValue value = values[i]; out.writeStartElement("value"); out.writeCharacters(value.getValue()); out.writeEndElement(); // </value> } } DataOption[] options = field.getOption(); if (options != null) { for (int i = 0; i < options.length; i++) { toXml(out, options[i]); } } out.writeEndElement(); // </field> } private void toXml(XmppStreamWriter out, DataOption option) throws IOException, XMLStreamException { out.writeStartElement("option"); if (option.getLabel() != null) out.writeAttribute("label", option.getLabel()); DataValue[] values = option.getValue(); if (values != null) { for (int i = 0; i < values.length; i++) { DataValue value = values[i]; out.writeStartElement("value"); out.writeCharacters(value.getValue()); out.writeEndElement(); // </value> } } out.writeEndElement(); // </option> } private void toXml(XmppStreamWriter out, DataItem item) throws IOException, XMLStreamException { out.writeStartElement("item"); DataField[] fields = item.getField(); if (fields != null) { for (int i = 0; i < fields.length; i++) { toXml(out, fields[i]); } } out.writeEndElement(); // </item> } private void toXml(XmppStreamWriter out, DataReported reported) throws IOException, XMLStreamException { out.writeStartElement("reported"); DataField[] fields = reported.getField(); if (fields != null) { for (int i = 0; i < fields.length; i++) { toXml(out, fields[i]); } } out.writeEndElement(); // </reported> } private void toXml(XmppStreamWriter out, DataInstructions instructions) throws IOException, XMLStreamException { out.writeStartElement("instructions"); if (instructions.getValue() != null) out.writeCharacters(instructions.getValue()); out.writeEndElement(); // </instructions> } /** Deserializes the object from XML */ public Serializable fromXml(XmppStreamReader in) throws IOException, XMLStreamException { boolean isFinest = log.isLoggable(Level.FINEST); String type = in.getAttributeValue(null, "type"); DataForm form = new DataForm(type); ArrayList<DataField> fieldList = new ArrayList<DataField>(); ArrayList<DataItem> itemList = new ArrayList<DataItem>(); ArrayList<DataInstructions> instructionsList = new ArrayList<DataInstructions>(); int tag = in.nextTag(); while (tag > 0) { if (isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { form.setFieldList(fieldList); form.setItemList(itemList); form.setInstructionsList(instructionsList); return form; } if (XMLStreamReader.START_ELEMENT == tag && "field".equals(in.getLocalName())) { fieldList.add(parseField(in)); } else if (XMLStreamReader.START_ELEMENT == tag && "item".equals(in.getLocalName())) { itemList.add(parseItem(in)); } else if (XMLStreamReader.START_ELEMENT == tag && "reported".equals(in.getLocalName())) { form.setReported(parseReported(in)); } else if (XMLStreamReader.START_ELEMENT == tag && "title".equals(in.getLocalName())) { String title = in.getElementText(); form.setTitle(title); skipToEnd(in, "title"); } else if (XMLStreamReader.START_ELEMENT == tag && "instructions".equals(in.getLocalName())) { String value = in.getElementText(); instructionsList.add(new DataInstructions(value)); skipToEnd(in, "instructions"); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } return null; } /** Deserializes the object from XML */ public DataField parseField(XMLStreamReader in) throws IOException, XMLStreamException { String label = in.getAttributeValue(null, "label"); String type = in.getAttributeValue(null, "type"); String var = in.getAttributeValue(null, "var"); DataField field = new DataField(type, var, label); ArrayList<DataValue> valueList = new ArrayList<DataValue>(); ArrayList<DataOption> optionList = new ArrayList<DataOption>(); int tag = in.nextTag(); while (tag > 0) { if (_isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { field.setValueList(valueList); field.setOptionList(optionList); return field; } if (XMLStreamReader.START_ELEMENT == tag && "desc".equals(in.getLocalName())) { String desc = in.getElementText(); field.setDesc(desc); skipToEnd(in, "desc"); } else if (XMLStreamReader.START_ELEMENT == tag && "option".equals(in.getLocalName())) { optionList.add(parseOption(in)); } else if (XMLStreamReader.START_ELEMENT == tag && "required".equals(in.getLocalName())) { field.setRequired(true); skipToEnd(in, "required"); } else if (XMLStreamReader.START_ELEMENT == tag && "value".equals(in.getLocalName())) { String value = in.getElementText(); valueList.add(new DataValue(value)); skipToEnd(in, "value"); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } skipToEnd(in, "field"); return field; } /** Deserializes the object from XML */ public DataItem parseItem(XMLStreamReader in) throws IOException, XMLStreamException { DataItem item = new DataItem(); ArrayList<DataField> fieldList = new ArrayList<DataField>(); int tag = in.nextTag(); while (tag > 0) { if (_isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { item.setFieldList(fieldList); return item; } if (XMLStreamReader.START_ELEMENT == tag && "field".equals(in.getLocalName())) { fieldList.add(parseField(in)); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } skipToEnd(in, "item"); return item; } /** Deserializes the object from XML */ public DataReported parseReported(XMLStreamReader in) throws IOException, XMLStreamException { DataReported reported = new DataReported(); ArrayList<DataField> fieldList = new ArrayList<DataField>(); int tag = in.nextTag(); while (tag > 0) { if (_isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { reported.setFieldList(fieldList); return reported; } if (XMLStreamReader.START_ELEMENT == tag && "field".equals(in.getLocalName())) { fieldList.add(parseField(in)); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } skipToEnd(in, "reported"); return reported; } /** Deserializes the object from XML */ public DataOption parseOption(XMLStreamReader in) throws IOException, XMLStreamException { String label = in.getAttributeValue(null, "label"); DataOption option = new DataOption(label); ArrayList<DataValue> valueList = new ArrayList<DataValue>(); int tag = in.nextTag(); while (tag > 0) { if (_isFinest) debug(in); if (XMLStreamReader.END_ELEMENT == tag) { option.setValueList(valueList); return option; } if (XMLStreamReader.START_ELEMENT == tag && "value".equals(in.getLocalName())) { String value = in.getElementText(); valueList.add(new DataValue(value)); skipToEnd(in, "value"); } else if (XMLStreamReader.START_ELEMENT == tag) { log.finer(this + " <" + in.getLocalName() + "> is an unknown tag"); skipToEnd(in, in.getLocalName()); } tag = in.nextTag(); } skipToEnd(in, "option"); return option; } }
public String readAsXmlString() throws IOException, XMLStreamException { StringBuilder sb = new StringBuilder(); int depth = 0; while (true) { if (XMLStreamReader.START_ELEMENT == getEventType()) { depth++; String prefix = getPrefix(); sb.append("<"); if (!"".equals(prefix)) { sb.append(prefix); sb.append(":"); } sb.append(getLocalName()); if (getNamespaceURI() != null) { if ("".equals(prefix)) sb.append(" xmlns"); else sb.append(" xmlns:").append(prefix); sb.append("=\""); sb.append(getNamespaceURI()).append("\""); } for (int i = 0; i < getAttributeCount(); i++) { sb.append(" "); sb.append(getAttributeLocalName(i)); sb.append("=\""); sb.append(getAttributeValue(i)); sb.append("\""); } sb.append(">"); log.finest(this + " " + sb); } else if (XMLStreamReader.END_ELEMENT == getEventType()) { depth--; sb.append("</"); String prefix = getPrefix(); if (!"".equals(prefix)) sb.append(prefix).append(":"); sb.append(getLocalName()); sb.append(">"); if (depth == 0) return sb.toString(); } else if (XMLStreamReader.CHARACTERS == getEventType()) { sb.append(getText()); } else { log.finer(this + " tag=" + getEventType()); return sb.toString(); } if (next() < 0) { log.finer(this + " unexpected end of file"); return sb.toString(); } } }
/** Marshals from an xmpp request to and from a serialized class */ public class XmppStreamReaderImpl extends XMLStreamReaderImpl implements XmppStreamReader { private static final L10N L = new L10N(XmppStreamReaderImpl.class); private static final Logger log = Logger.getLogger(XmppStreamReaderImpl.class.getName()); private XmppMarshalFactory _marshalFactory; XmppStreamReaderImpl(ReadStream is, XmppMarshalFactory factory) throws XMLStreamException { super(is); _marshalFactory = factory; } public Serializable readValue() throws IOException, XMLStreamException { QName name = getName(); Serializable query = null; XmppMarshal marshal = _marshalFactory.getUnserialize(name); if (marshal != null) return marshal.fromXml(this); else return readAsXmlString(); } public String readAsXmlString() throws IOException, XMLStreamException { StringBuilder sb = new StringBuilder(); int depth = 0; while (true) { if (XMLStreamReader.START_ELEMENT == getEventType()) { depth++; String prefix = getPrefix(); sb.append("<"); if (!"".equals(prefix)) { sb.append(prefix); sb.append(":"); } sb.append(getLocalName()); if (getNamespaceURI() != null) { if ("".equals(prefix)) sb.append(" xmlns"); else sb.append(" xmlns:").append(prefix); sb.append("=\""); sb.append(getNamespaceURI()).append("\""); } for (int i = 0; i < getAttributeCount(); i++) { sb.append(" "); sb.append(getAttributeLocalName(i)); sb.append("=\""); sb.append(getAttributeValue(i)); sb.append("\""); } sb.append(">"); log.finest(this + " " + sb); } else if (XMLStreamReader.END_ELEMENT == getEventType()) { depth--; sb.append("</"); String prefix = getPrefix(); if (!"".equals(prefix)) sb.append(prefix).append(":"); sb.append(getLocalName()); sb.append(">"); if (depth == 0) return sb.toString(); } else if (XMLStreamReader.CHARACTERS == getEventType()) { sb.append(getText()); } else { log.finer(this + " tag=" + getEventType()); return sb.toString(); } if (next() < 0) { log.finer(this + " unexpected end of file"); return sb.toString(); } } } }
public abstract class AbstractCauchoRequest implements CauchoRequest { private static final L10N L = new L10N(AbstractCauchoRequest.class); private static final Logger log = Logger.getLogger(AbstractCauchoRequest.class.getName()); private int _sessionGroup = -1; private boolean _sessionIsLoaded; private SessionImpl _session; public abstract CauchoResponse getResponse(); public RequestDispatcher getRequestDispatcher(String path) { if (path == null || path.length() == 0) return null; else if (path.charAt(0) == '/') return getWebApp().getRequestDispatcher(path); else { CharBuffer cb = new CharBuffer(); WebApp webApp = getWebApp(); String servletPath = getPageServletPath(); if (servletPath != null) cb.append(servletPath); String pathInfo = getPagePathInfo(); if (pathInfo != null) cb.append(pathInfo); int p = cb.lastIndexOf('/'); if (p >= 0) cb.setLength(p); cb.append('/'); cb.append(path); if (webApp != null) return webApp.getRequestDispatcher(cb.toString()); return null; } } public String getRealPath(String uri) { WebApp webApp = getWebApp(); return webApp.getRealPath(uri); } /** Returns the URL for the request */ public StringBuffer getRequestURL() { StringBuffer sb = new StringBuffer(); sb.append(getScheme()); sb.append("://"); sb.append(getServerName()); int port = getServerPort(); if (port > 0 && port != 80 && port != 443) { sb.append(":"); sb.append(port); } sb.append(getRequestURI()); return sb; } /** Returns the real path of pathInfo. */ public String getPathTranslated() { // server/106w String pathInfo = getPathInfo(); if (pathInfo == null) return null; else return getRealPath(pathInfo); } public boolean isTop() { return false; } // // session management // public abstract boolean isSessionIdFromCookie(); public abstract String getSessionId(); public abstract void setSessionId(String sessionId); /** Returns the memory session. */ public HttpSession getMemorySession() { if (_session != null && _session.isValid()) return _session; else return null; } /** * Returns the current session, creating one if necessary. Sessions are a convenience for keeping * user state across requests. */ public HttpSession getSession() { return getSession(true); } /** * Returns the current session. * * @param create true if a new session should be created * @return the current session */ public HttpSession getSession(boolean create) { if (_session != null) { if (_session.isValid()) return _session; } else if (!create && _sessionIsLoaded) return null; _sessionIsLoaded = true; _session = createSession(create); return _session; } /** * Returns the current session. * * @return the current session */ public HttpSession getLoadedSession() { if (_session != null && _session.isValid()) return _session; else return null; } /** Returns true if the HTTP request's session id refers to a valid session. */ public boolean isRequestedSessionIdValid() { String id = getRequestedSessionId(); if (id == null) return false; SessionImpl session = _session; if (session == null) session = (SessionImpl) getSession(false); return session != null && session.isValid() && session.getId().equals(id); } /** * Returns the current session. * * <p>XXX: duplicated in RequestAdapter * * @param create true if a new session should be created * @return the current session */ private SessionImpl createSession(boolean create) { SessionManager manager = getSessionManager(); if (manager == null) return null; String id = getSessionId(); long now = Alarm.getCurrentTime(); SessionImpl session = manager.createSession(create, this, id, now, isSessionIdFromCookie()); if (session != null && (id == null || !session.getId().equals(id)) && manager.enableSessionCookies()) { setSessionId(session.getId()); } // server/0123 vs TCK /* if (session != null) session.setAccessTime(now); */ return session; } /** Returns the session manager. */ protected final SessionManager getSessionManager() { WebApp webApp = getWebApp(); if (webApp != null) return webApp.getSessionManager(); else return null; } /** Returns the session cookie. */ protected final String getSessionCookie(SessionManager manager) { if (isSecure()) return manager.getSSLCookieName(); else return manager.getCookieName(); } public int getSessionGroup() { return _sessionGroup; } void saveSession() { SessionImpl session = _session; if (session != null) session.save(); } // // security // protected String getRunAs() { return null; } protected ServletInvocation getInvocation() { return null; } /** Returns the next request in a chain. */ protected HttpServletRequest getRequest() { return null; } /** @since Servlet 3.0 */ @Override public void login(String username, String password) throws ServletException { WebApp webApp = getWebApp(); Authenticator auth = webApp.getConfiguredAuthenticator(); if (auth == null) throw new ServletException( L.l("No authentication mechanism is configured for '{0}'", getWebApp())); // server/1aj0 Login login = webApp.getLogin(); if (login == null) throw new ServletException(L.l("No login mechanism is configured for '{0}'", getWebApp())); if (!login.isPasswordBased()) throw new ServletException( L.l("Authentication mechanism '{0}' does not support password authentication", login)); removeAttribute(Login.LOGIN_USER); removeAttribute(Login.LOGIN_PASSWORD); Principal principal = login.getUserPrincipal(this); if (principal != null) throw new ServletException(L.l("UserPrincipal object has already been established")); setAttribute(Login.LOGIN_USER, username); setAttribute(Login.LOGIN_PASSWORD, password); try { login.login(this, getResponse(), false); } finally { removeAttribute(Login.LOGIN_USER); removeAttribute(Login.LOGIN_PASSWORD); } principal = login.getUserPrincipal(this); if (principal == null) throw new ServletException("can't authenticate a user"); } @Override public boolean login(boolean isFail) { try { WebApp webApp = getWebApp(); if (webApp == null) { if (log.isLoggable(Level.FINE)) log.finer("authentication failed, no web-app found"); getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return false; } // If the authenticator can find the user, return it. Login login = webApp.getLogin(); if (login != null) { Principal user = login.login(this, getResponse(), isFail); return user != null; /* if (user == null) return false; setAttribute(AbstractLogin.LOGIN_NAME, user); return true; */ } else if (isFail) { if (log.isLoggable(Level.FINE)) log.finer("authentication failed, no login module found for " + webApp); getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return false; } else { // if a non-failure, then missing login is fine return false; } } catch (IOException e) { log.log(Level.FINE, e.toString(), e); return false; } } /** Returns true if any authentication is requested */ public abstract boolean isLoginRequested(); public abstract void requestLogin(); /** @since Servlet 3.0 */ @Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { WebApp webApp = getWebApp(); if (webApp == null) throw new ServletException( L.l("No authentication mechanism is configured for '{0}'", getWebApp())); // server/1aj{0,1} Authenticator auth = webApp.getConfiguredAuthenticator(); if (auth == null) throw new ServletException( L.l("No authentication mechanism is configured for '{0}'", getWebApp())); Login login = webApp.getLogin(); if (login == null) throw new ServletException( L.l("No authentication mechanism is configured for '{0}'", getWebApp())); Principal principal = login.login(this, response, true); if (principal != null) return true; return false; } /** Returns the Principal representing the logged in user. */ public Principal getUserPrincipal() { requestLogin(); Principal user; user = (Principal) getAttribute(AbstractLogin.LOGIN_NAME); if (user != null) return user; WebApp webApp = getWebApp(); if (webApp == null) return null; // If the authenticator can find the user, return it. Login login = webApp.getLogin(); if (login != null) { user = login.getUserPrincipal(this); if (user != null) { getResponse().setPrivateCache(true); } else { // server/123h, server/1920 // distinguishes between setPrivateCache and setPrivateOrResinCache // _response.setPrivateOrResinCache(true); } } return user; } /** * Returns true if the user represented by the current request plays the named role. * * @param role the named role to test. * @return true if the user plays the role. */ public boolean isUserInRole(String role) { ServletInvocation invocation = getInvocation(); if (invocation == null) { if (getRequest() != null) return getRequest().isUserInRole(role); else return false; } HashMap<String, String> roleMap = invocation.getSecurityRoleMap(); if (roleMap != null) { String linkRole = roleMap.get(role); if (linkRole != null) role = linkRole; } String runAs = getRunAs(); if (runAs != null) return runAs.equals(role); WebApp webApp = getWebApp(); Principal user = getUserPrincipal(); if (user == null) { if (log.isLoggable(Level.FINE)) log.fine(this + " no user for isUserInRole"); return false; } RoleMapManager roleManager = webApp != null ? webApp.getRoleMapManager() : null; if (roleManager != null) { Boolean result = roleManager.isUserInRole(role, user); if (result != null) { if (log.isLoggable(Level.FINE)) log.fine(this + " userInRole(" + role + ")->" + result); return result; } } Login login = webApp == null ? null : webApp.getLogin(); boolean inRole = login != null && login.isUserInRole(user, role); if (log.isLoggable(Level.FINE)) { if (login == null) log.fine(this + " no Login for isUserInRole"); else if (user == null) log.fine(this + " no user for isUserInRole"); else if (inRole) log.fine(this + " " + user + " is in role: " + role); else log.fine(this + " failed " + user + " in role: " + role); } return inRole; } // // lifecycle // protected void finishRequest() throws IOException { SessionImpl session = _session; // if (session == null && getSessionId() != null) session = (SessionImpl) getSession(false); if (session != null) session.finishRequest(); } @Override public String toString() { return getClass().getSimpleName() + "[]"; } }
/** Manages databases in a local environment, e.g. for PHP dynamic database lookup. */ public class DatabaseManager { protected static final Logger log = Logger.getLogger(DatabaseManager.class.getName()); private static final L10N L = new L10N(DatabaseManager.class); private static final EnvironmentLocal<DatabaseManager> _localManager = new EnvironmentLocal<DatabaseManager>(); private final HashMap<String, DBPool> _databaseMap = new HashMap<String, DBPool>(); private final ArrayList<Driver> _driverList = new ArrayList<Driver>(); private int _gId; /** The manager is never instantiated. */ private DatabaseManager() { initDriverList(); } /** Returns the database manager for the local environment. */ private static DatabaseManager getLocalManager() { synchronized (_localManager) { DatabaseManager manager = _localManager.getLevel(); if (manager == null) { manager = new DatabaseManager(); _localManager.set(manager); } return manager; } } /** Returns a matching dbpool. */ public static DataSource findDatabase(String url) throws SQLException { String driver = findDriverByUrl(url); return getLocalManager().findDatabaseImpl(url, driver); } /** Returns a matching dbpool. */ public static DataSource findDatabase(String url, String driver) throws SQLException { return getLocalManager().findDatabaseImpl(url, driver); } /** Looks up the local database, creating if necessary. */ private DataSource findDatabaseImpl(String url, String driverName) throws SQLException { try { synchronized (_databaseMap) { DBPool db = _databaseMap.get(url); if (db == null) { db = new DBPool(); db.setVar(url + "-" + _gId++); DriverConfig driver = db.createDriver(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class driverClass = Class.forName(driverName, false, loader); driver.setType(driverClass); driver.setURL(url); db.init(); _databaseMap.put(url, db); } return db; } } catch (RuntimeException e) { throw e; } catch (SQLException e) { throw e; } catch (Exception e) { throw ConfigException.create(e); } } public static String findDriverByUrl(String url) { return getLocalManager().findDriverByUrlImpl(url); } private String findDriverByUrlImpl(String url) { for (int i = 0; i < _driverList.size(); i++) { try { Driver driver = (Driver) _driverList.get(i); if (driver.acceptsURL(url)) return driver.getClass().getName(); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } return null; } private void initDriverList() { try { Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver"); while (iter.hasMoreElements()) { URL url = (URL) iter.nextElement(); ReadStream is = null; try { is = Vfs.lookup(url.toString()).openRead(); String filename; while ((filename = is.readLine()) != null) { int p = filename.indexOf('#'); if (p >= 0) filename = filename.substring(0, p); filename = filename.trim(); if (filename.length() == 0) continue; try { Class cl = Class.forName(filename, false, loader); Driver driver = null; if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance(); if (driver != null) { log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName())); _driverList.add(driver); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } finally { if (is != null) is.close(); } } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } static class DatabaseKey { private String _url; private String _catalog; DatabaseKey(String url, String catalog) { _url = url; _catalog = catalog; } public int hashCode() { int hash = 37; hash = 65521 * hash + _url.hashCode(); if (_catalog != null) hash = 65521 * hash + _catalog.hashCode(); return hash; } public boolean equals(Object o) { if (!(o instanceof DatabaseKey)) return false; DatabaseKey key = (DatabaseKey) o; if (!_url.equals(key._url)) return false; return (_catalog == key._catalog || _catalog != null && _catalog.equals(key._catalog)); } } }