List of usage examples for org.w3c.dom Element getAttributeNS
public String getAttributeNS(String namespaceURI, String localName) throws DOMException;
From source file:de.betterform.xml.xforms.model.Model.java
private void loadInlineSchemas(List list) throws XFormsException { String schemaId = null;// w w w . j a v a2s . com try { NodeList children = this.element.getChildNodes(); for (int index = 0; index < children.getLength(); index++) { Node child = children.item(index); if (Node.ELEMENT_NODE == child.getNodeType() && NamespaceConstants.XMLSCHEMA_NS.equals(child.getNamespaceURI())) { Element element = (Element) child; schemaId = element.hasAttributeNS(null, "id") ? element.getAttributeNS(null, "id") : element.getNodeName(); XSModel schema = loadSchema(element); if (schema == null) { throw new NullPointerException("resource not found"); } list.add(schema); } } } catch (Exception e) { throw new XFormsLinkException("could not load inline schema", e, this.target, schemaId); } }
From source file:com.silverwrist.venice.std.TrackbackManager.java
/** * Loads the HTTP content at the specified URL, scans it for RDF description blocks, and adds those blocks * as {@link com.silverwrist.venice.std.TrackbackItem TrackbackItem}s to our internal cache. Uses modification * detection to keep from reloading a page unless necessary. * * @param url The URL of the resource to be loaded. * @param attrs The attributes of the specified page; if this is <code>null</code>, we'll check the page * cache for the right attributes. * @return <code>true</code> if the page data was loaded and scanned for trackback items; <code>false</code> * if no data was loaded (because it was not modified since the last time we loaded it, for instance). * @exception com.silverwrist.venice.except.TrackbackException If there was an error loading or interpreting * the page data.//from w w w. ja v a 2 s . com */ private synchronized boolean load(URL url, PageAttributes attrs) throws TrackbackException { if (attrs == null) attrs = (PageAttributes) (m_page_cache.get(url)); // Create the GET method and set its headers. String s = url.toString(); int x = s.lastIndexOf('#'); if (x >= 0) s = s.substring(0, x); GetMethod getter = new GetMethod(s); HttpMethodParams params = getter.getParams(); getter.setDoAuthentication(false); getter.setFollowRedirects(true); getter.setRequestHeader("User-Agent", USER_AGENT); getter.setRequestHeader("Accept", "text/*"); getter.setRequestHeader("Accept-Encoding", "identity"); params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); getter.setParams(params); boolean get_resp = false; PageAttributes newattrs = null; ContentType ctype = null; byte[] rawdata = null; try { // set the Last-Modified date as an If-Modified-Since header on the request java.util.Date lmod = null; if (attrs != null) lmod = attrs.getLastModified(); if (lmod != null) getter.setRequestHeader("If-Modified-Since", s_httpdate_format.format(lmod)); // execute the Get method! int rc = m_http_client.executeMethod(getter); get_resp = true; if ((lmod != null) && (rc == HttpStatus.SC_NOT_MODIFIED)) return false; // we were not modified if (rc == HttpStatus.SC_NO_CONTENT) return false; // there's no content there if (rc != HttpStatus.SC_OK) // this is farked! throw new TrackbackException("GET of " + url + " returned " + rc); // Get the new page attributes and save them off. newattrs = new PageAttributes(getter); m_page_cache.put(url, newattrs); // Get the Content-Type header and see if it's valid. Header hdr = getter.getResponseHeader("Content-Type"); if (hdr != null) s = hdr.getValue(); else s = "text/plain"; // necessary assumption ctype = new ContentType(s); if (!(ctype.getPrimaryType().equals("text"))) throw new TrackbackException("URL " + url + " does not point to a text-based resource"); // Load the resource in as byte data; we will determine the right character set for it later. rawdata = getter.getResponseBody(); get_resp = false; } // end try catch (IOException e) { // IO error getting the page throw new TrackbackException("I/O error retrieving " + url + ": " + e.getMessage(), e); } // end catch catch (javax.mail.internet.ParseException e) { // translate into TrackbackException throw new TrackbackException("invalid Content-Type received for URL " + url, e); } // end catch finally { // release the connection if possible try { // need to get the message body if (get_resp) getter.getResponseBody(); } // end try catch (IOException e) { // ignore these } // end catch getter.releaseConnection(); } // end finally // make a first guess at the charset from the HTTP header Content-Type String cset = ctype.getParameter("charset"); if (cset == null) cset = "US-ASCII"; String content = null; try { // interpret the content content = new String(rawdata, cset); } // end try catch (UnsupportedEncodingException e) { // fall back and try just using US-ASCII cset = null; try { // interpret the content content = new String(rawdata, "US-ASCII"); } // end try catch (UnsupportedEncodingException e2) { // can't happen logger.debug("WTF? US-ASCII should damn well be a supported character set!", e2); } // end catch } // end catch // Look for <META HTTP-EQUIV=...> tags in the content. Map http_attrs = extractHttpEquivTags(content); // Try to get a Content-Type attribute from there. s = (String) (http_attrs.get("CONTENT-TYPE")); String cset2 = null; if (s != null) { // look for the content type try { // parse into Content-Type ContentType c = new ContentType(s); if (c.getPrimaryType().equals("text")) cset2 = c.getParameter("charset"); } // end try catch (javax.mail.internet.ParseException e) { // can't get a second Content-Type logger.debug("parse of Content-Type from META tags failed", e); cset2 = null; } // end catch } // end if if ((cset == null) && (cset2 == null)) throw new TrackbackException("unable to determine character set for " + url); if ((cset2 != null) && ((cset == null) || !(cset.equalsIgnoreCase(cset2)))) { // reinterpret content in new character set try { // reinterpret content in new character set s = new String(rawdata, cset2); content = s; // the contents of the HTTP-EQUIV tags may have changed as a result http_attrs = extractHttpEquivTags(content); } // end try catch (UnsupportedEncodingException e) { // just use original character set if (cset == null) throw new TrackbackException("unable to determine character set for " + url); } // end catch } // end if newattrs.updateFromPage(http_attrs); // update the page attributes from the META tag data // Search the page content for RDF blocks. RE m = new RE(s_rdf_start, RE.MATCH_NORMAL); int pos = 0; while (m.match(content, pos)) { // look for the end of this RDF block RE m2 = new RE(getEndRecognizer(m.getParen(1)), RE.MATCH_NORMAL); if (m2.match(content, m.getParenEnd(0))) { // we now have a block to feed to the XML parser try { // run the block through the XML parser InputSource isrc = new InputSource( new StringReader(content.substring(m.getParenStart(0), m2.getParenEnd(0)))); Document doc = m_rdf_parser.parse(isrc); // examine topmost element, which should be rdf:RDF Element root = doc.getDocumentElement(); if (NS_RDF.equals(root.getNamespaceURI()) && (root.getLocalName() != null) && root.getLocalName().equals("RDF")) { // this is most definitely an rdf:RDF node...look for rdf:Description nodes under it NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { // check each node in the list Node n = nl.item(i); if ((n.getNodeType() == Node.ELEMENT_NODE) && NS_RDF.equals(n.getNamespaceURI()) && (n.getLocalName() != null) && n.getLocalName().equals("Description")) { // we've got an rdf:Description node...extract the attributes from it Element elt = (Element) n; try { // look for the item and trackback URLs URL item = null, trackback = null; s = elt.getAttributeNS(NS_DC, "identifier"); if ((s != null) && (s.length() > 0)) item = new URL(s); s = elt.getAttributeNS(NS_TRACKBACK, "ping"); if ((s != null) && (s.length() > 0)) trackback = new URL(s); if ((item != null) && (trackback != null)) { // create the item s = elt.getAttributeNS(NS_DC, "title"); m_item_cache.put(item, new MyTrackbackItem(item, trackback, s, newattrs)); } // end if } // end try catch (MalformedURLException e) { // this means skip this item logger.warn("URL parse failure", e); } // end catch } // end if } // end for } // end if } // end try catch (IOException e) { // disregard this block logger.warn("RDF block parse failure", e); } // end catch catch (SAXException e) { // disregard this block logger.warn("RDF block parse failure", e); } // end catch } // end if // else ignore this possible block pos = m.getParenEnd(0); } // end while return true; }
From source file:de.mpg.mpdl.inge.exportmanager.Export.java
/** * Walk around the itemList XML, fetch all files from components via URIs and put them into the * archive {@link OutputStream} aos/* w w w. ja v a 2 s . c om*/ * * @param aos - array {@link OutputStream} * @param itemList - XML with the files to be fetched, see NS: * http://www.escidoc.de/schemas/components/0.7 * @throws ExportManagerException */ private void fetchComponentsDo(OutputStream aos, String itemList) throws ExportManagerException { Document doc = parseDocument(itemList); NodeIterator ni = getFilteredNodes(new ComponentNodeFilter(), doc); // login only once String userHandle; try { userHandle = AdminHelper.loginUser(USER_ID, PASSWORD); } catch (Exception e) { throw new ExportManagerException("Cannot login", e); } String fileName; Node n; while ((n = ni.nextNode()) != null) { Element componentElement = (Element) n; NodeList nl = componentElement.getElementsByTagNameNS(COMPONENTS_NS, "content"); Element contentElement = (Element) nl.item(0); if (contentElement == null) { throw new ExportManagerException( "Wrong item XML: {" + COMPONENTS_NS + "}component element doesn't contain content element. " + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href")); } String href = contentElement.getAttributeNS(XLINK_NS, "href"); String storageStatus = contentElement.getAttribute("storage"); // get file name if ("internal-managed".equals(storageStatus)) { NodeIterator nif = ((DocumentTraversal) doc).createNodeIterator(componentElement, NodeFilter.SHOW_ELEMENT, new FileNameNodeFilter(), true); Node nf; if ((nf = nif.nextNode()) != null) { fileName = ((Element) nf).getTextContent(); // names of files for Matcher m = Pattern.compile("^([\\w.]+?)(\\s+|$)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL) .matcher(fileName); m.find(); fileName = m.group(1); } else { throw new ExportManagerException("Missed file property: {" + COMPONENTS_NS + "}component element doesn't contain file-name element (md-records/md-record/file:file/dc:title). " + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href")); } } // TODO: the external-managed will be processed later else { throw new ExportManagerException("Missed internal-managed file in {" + COMPONENTS_NS + "}component: components/component/content[@storage=\"internal-managed\"]" + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href")); } logger.info("link to the content: " + href); logger.info("storage status: " + storageStatus); logger.info("fileName: " + fileName); // get file via URI String url; try { url = PropertyReader.getFrameworkUrl() + href; } catch (Exception e) { throw new ExportManagerException("Cannot get framework url", e); } logger.info("url=" + url); GetMethod method = new GetMethod(url); method.setFollowRedirects(false); method.setRequestHeader("Cookie", "escidocCookie=" + userHandle); // Execute the method with HttpClient. HttpClient client = new HttpClient(); try { ProxyHelper.executeMethod(client, method); } catch (Exception e) { throw new ExportManagerException("Cannot execute HttpMethod", e); } int status = method.getStatusCode(); logger.info("Status=" + status); if (status != 200) fileName += ".error" + status; byte[] responseBody; try { responseBody = method.getResponseBody(); } catch (Exception e) { throw new ExportManagerException("Cannot get Response Body", e); } InputStream bis = new BufferedInputStream(new ByteArrayInputStream(responseBody)); if (aos instanceof ZipOutputStream) { ZipEntry ze = new ZipEntry(fileName); ze.setSize(responseBody.length); try { ((ZipOutputStream) aos).putNextEntry(ze); writeFromStreamToStream(bis, aos); ((ZipOutputStream) aos).closeEntry(); } catch (Exception e) { throw new ExportManagerException("zip2stream generation problem", e); } } else if (aos instanceof TarOutputStream) { TarEntry te = new TarEntry(fileName); te.setSize(responseBody.length); try { ((TarOutputStream) aos).putNextEntry(te); writeFromStreamToStream(bis, aos); ((TarOutputStream) aos).closeEntry(); } catch (Exception e) { throw new ExportManagerException("tar2stream generation problem", e); } } else { throw new ExportManagerException("Unsupported archive output stream: " + aos.getClass()); } try { bis.close(); } catch (Exception e) { throw new ExportManagerException("Cannot close InputStream", e); } } }
From source file:de.mpg.escidoc.services.exportmanager.Export.java
/** * Walk around the itemList XML, fetch all files from components via URIs * and put them into the archive {@link OutputStream} aos * //from w w w. j av a 2s. co m * @param aos * - array {@link OutputStream} * @param itemList * - XML with the files to be fetched, see NS: * http://www.escidoc.de/schemas/components/0.7 * @throws ExportManagerException */ private void fetchComponentsDo(OutputStream aos, String itemList) throws ExportManagerException { Document doc = parseDocument(itemList); NodeIterator ni = getFilteredNodes(new ComponentNodeFilter(), doc); // login only once String userHandle; try { userHandle = AdminHelper.loginUser(USER_ID, PASSWORD); } catch (Exception e) { throw new ExportManagerException("Cannot login", e); } String fileName; Node n; while ((n = ni.nextNode()) != null) { Element componentElement = (Element) n; NodeList nl = componentElement.getElementsByTagNameNS(COMPONENTS_NS, "content"); Element contentElement = (Element) nl.item(0); if (contentElement == null) { throw new ExportManagerException( "Wrong item XML: {" + COMPONENTS_NS + "}component element doesn't contain content element. " + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href")); } String href = contentElement.getAttributeNS(XLINK_NS, "href"); String storageStatus = contentElement.getAttribute("storage"); // get file name if ("internal-managed".equals(storageStatus)) { NodeIterator nif = ((DocumentTraversal) doc).createNodeIterator(componentElement, NodeFilter.SHOW_ELEMENT, new FileNameNodeFilter(), true); Node nf; if ((nf = nif.nextNode()) != null) { fileName = ((Element) nf).getTextContent(); // names of files for Matcher m = Pattern.compile("^([\\w.]+?)(\\s+|$)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL) .matcher(fileName); m.find(); fileName = m.group(1); } else { throw new ExportManagerException("Missed file property: {" + COMPONENTS_NS + "}component element doesn't contain file-name element (md-records/md-record/file:file/dc:title). " + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href")); } } // TODO: the external-managed will be processed later else { throw new ExportManagerException("Missed internal-managed file in {" + COMPONENTS_NS + "}component: components/component/content[@storage=\"internal-managed\"]" + "Component id: " + componentElement.getAttributeNS(XLINK_NS, "href")); } logger.info("link to the content: " + href); logger.info("storage status: " + storageStatus); logger.info("fileName: " + fileName); // get file via URI String url; try { url = ServiceLocator.getFrameworkUrl() + href; } catch (Exception e) { throw new ExportManagerException("Cannot get framework url", e); } logger.info("url=" + url); GetMethod method = new GetMethod(url); method.setFollowRedirects(false); method.setRequestHeader("Cookie", "escidocCookie=" + userHandle); // Execute the method with HttpClient. HttpClient client = new HttpClient(); try { ProxyHelper.executeMethod(client, method); } catch (Exception e) { throw new ExportManagerException("Cannot execute HttpMethod", e); } int status = method.getStatusCode(); logger.info("Status=" + status); if (status != 200) fileName += ".error" + status; byte[] responseBody; try { responseBody = method.getResponseBody(); } catch (Exception e) { throw new ExportManagerException("Cannot get Response Body", e); } InputStream bis = new BufferedInputStream(new ByteArrayInputStream(responseBody)); if (aos instanceof ZipOutputStream) { ZipEntry ze = new ZipEntry(fileName); ze.setSize(responseBody.length); try { ((ZipOutputStream) aos).putNextEntry(ze); writeFromStreamToStream(bis, aos); ((ZipOutputStream) aos).closeEntry(); } catch (Exception e) { throw new ExportManagerException("zip2stream generation problem", e); } } else if (aos instanceof TarOutputStream) { TarEntry te = new TarEntry(fileName); te.setSize(responseBody.length); try { ((TarOutputStream) aos).putNextEntry(te); writeFromStreamToStream(bis, aos); ((TarOutputStream) aos).closeEntry(); } catch (Exception e) { throw new ExportManagerException("tar2stream generation problem", e); } } else { throw new ExportManagerException("Unsupported archive output stream: " + aos.getClass()); } try { bis.close(); } catch (Exception e) { throw new ExportManagerException("Cannot close InputStream", e); } } }
From source file:net.shibboleth.idp.profile.spring.relyingparty.metadata.impl.HTTPMetadataProviderParser.java
/** {@inheritDoc} */ // Checkstyle: CyclomaticComplexity OFF @Override/* w w w. j a v a 2 s . c o m*/ protected void doNativeParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { super.doNativeParse(element, parserContext, builder); if (element.hasAttributeNS(null, "cacheDuration")) { log.error("{}: cacheDuration is not supported", parserContext.getReaderContext().getResource().getDescription()); throw new BeanDefinitionParsingException(new Problem("cacheDuration is not supported", new Location(parserContext.getReaderContext().getResource()))); } if (element.hasAttributeNS(null, "maintainExpiredMetadata")) { log.error("{}: maintainExpiredMetadata is not supported", parserContext.getReaderContext().getResource().getDescription()); throw new BeanDefinitionParsingException(new Problem("maintainExpiredMetadata is not supported", new Location(parserContext.getReaderContext().getResource()))); } boolean haveTLSTrustEngine = false; if (element.hasAttributeNS(null, "tlsTrustEngineRef")) { builder.addPropertyReference("tLSTrustEngine", StringSupport.trimOrNull(element.getAttributeNS(null, "tlsTrustEngineRef"))); haveTLSTrustEngine = true; } else { BeanDefinition tlsTrustEngine = parseTLSTrustEngine(element, parserContext); if (tlsTrustEngine != null) { builder.addPropertyValue("tLSTrustEngine", tlsTrustEngine); haveTLSTrustEngine = true; } } if (element.hasAttributeNS(null, "httpClientRef")) { builder.addConstructorArgReference( StringSupport.trimOrNull(element.getAttributeNS(null, "httpClientRef"))); if (element.hasAttributeNS(null, "requestTimeout") || element.hasAttributeNS(null, "disregardSslCertificate") || element.hasAttributeNS(null, "disregardTLSCertificate") || element.hasAttributeNS(null, "proxyHost") || element.hasAttributeNS(null, "proxyPort") || element.hasAttributeNS(null, "proxyUser") || element.hasAttributeNS(null, "proxyPassword")) { log.warn("httpClientRef overrides settings for requestTimeout, disregardSslCertificate, " + "disregardTLSCertificate, proxyHost, proxyPort, proxyUser and proxyPassword"); } } else { builder.addConstructorArgValue(buildHttpClient(element, parserContext, haveTLSTrustEngine)); } builder.addConstructorArgValue(StringSupport.trimOrNull(element.getAttributeNS(null, METADATA_URL))); if (element.hasAttributeNS(null, BASIC_AUTH_USER) || element.hasAttributeNS(null, BASIC_AUTH_PASSWORD)) { builder.addPropertyValue("basicCredentials", buildBasicCredentials(element)); } }
From source file:de.betterform.xml.xforms.action.LoadAction.java
private void handleEmbedding(String absoluteURI, HashMap map, boolean includeCSS, boolean includeScript) throws XFormsException { // if(this.targetAttribute == null) return; //todo: handle multiple params if (absoluteURI.indexOf("?") > 0) { String name = absoluteURI.substring(absoluteURI.indexOf("?") + 1); String value = name.substring(name.indexOf("=") + 1, name.length()); name = name.substring(0, name.indexOf("=")); this.container.getProcessor().setContextParam(name, value); }//from w ww . java 2s. c om if (this.targetAttribute == null) { map.put("uri", absoluteURI); map.put("show", this.showAttribute); // dispatch internal betterform event this.container.dispatch(this.target, BetterFormEventNames.LOAD_URI, map); return; } if (!("embed".equals(this.showAttribute))) { throw new XFormsException("@show must be 'embed' if @target is given but was: '" + this.showAttribute + "' on Element " + DOMUtil.getCanonicalPath(this.element)); } //todo: dirty dirty dirty String evaluatedTarget = evalAttributeValueTemplates(this.targetAttribute, this.element); if (LOGGER.isDebugEnabled()) { LOGGER.debug("targetid evaluated to: " + evaluatedTarget); } Node embed = getEmbeddedDocument(absoluteURI); if (embed == null) { //todo: review: context info params containing a '-' fail during access in javascript! //todo: the following property should have been 'resource-uri' according to spec map.put("resourceUri", absoluteURI); this.container.dispatch(this.target, XFormsEventNames.LINK_EXCEPTION, map); return; } // Check for 'ClientSide' events (DOMFocusIN / DOMFocusOUT / xforms-select) String utilizedEvents = this.getEventsInSubform(embed); // fetch CSS / JavaScript String inlineCssRules = ""; String externalCssRules = ""; String inlineJavaScript = ""; String externalJavaScript = ""; if (includeCSS) { inlineCssRules = getInlineCSS(embed); externalCssRules = getExternalCSS(embed); } if (includeScript) { inlineJavaScript = getInlineJavaScript(embed); externalJavaScript = getExternalJavaScript(embed); } if (Config.getInstance().getProperty("webprocessor.doIncludes", "false").equals("true")) { embed = doIncludes(embed, absoluteURI); } embed = extractFragment(absoluteURI, embed); if (LOGGER.isDebugEnabled()) { DOMUtil.prettyPrintDOM(embed); } Element embeddedNode; Element targetElem = getTargetElement(evaluatedTarget); //Test if targetElem exist. if (targetElem != null) { // destroy existing embedded form within targetNode if (targetElem.hasChildNodes()) { destroyembeddedModels(targetElem); Initializer.disposeUIElements(targetElem); } // import referenced embedded form into host document embeddedNode = (Element) this.container.getDocument().importNode(embed, true); //import namespaces NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(), (Element) embeddedNode); // keep original targetElem id within hostdoc embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id")); //copy all Attributes that might have been on original mountPoint to embedded node DOMUtil.copyAttributes(targetElem, embeddedNode, null); targetElem.getParentNode().replaceChild(embeddedNode, targetElem); //create model for it this.container.createEmbeddedForm((Element) embeddedNode); // dispatch internal betterform event this.container.dispatch((EventTarget) embeddedNode, BetterFormEventNames.EMBED_DONE, map); if (getModel().isReady()) { map.put("uri", absoluteURI); map.put("show", this.showAttribute); map.put("targetElement", embeddedNode); map.put("nameTarget", evaluatedTarget); map.put("xlinkTarget", getXFormsAttribute(targetElem, "id")); map.put("inlineCSS", inlineCssRules); map.put("externalCSS", externalCssRules); map.put("inlineJavascript", inlineJavaScript); map.put("externalJavascript", externalJavaScript); map.put("utilizedEvents", utilizedEvents); this.container.dispatch((EventTarget) embeddedNode, BetterFormEventNames.EMBED, map); this.container.dispatch(this.target, BetterFormEventNames.LOAD_URI, map); } // storeInContext(absoluteURI, this.showAttribute); } else { String message = "Element reference for targetid: " + this.targetAttribute + " not found. " + DOMUtil.getCanonicalPath(this.element); /* Element div = this.element.getOwnerDocument().createElementNS("", "div"); div.setAttribute("class", "bfException"); div.setTextContent("Element reference for targetid: " + this.targetAttribute + "not found. " + DOMUtil.getCanonicalPath(this.element)); Element body = (Element) this.container.getDocument().getElementsByTagName("body").item(0); body.insertBefore(div, DOMUtil.getFirstChildElement(body)); */ map.put("message", message); map.put("exceptionPath", DOMUtil.getCanonicalPath(this.element)); this.container.dispatch(this.target, BetterFormEventNames.EXCEPTION, map); //throw new XFormsException(message); } }
From source file:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.dataConnector.LdapDataConnectorBeanDefinitionParser.java
/** * Process the pooling configuration for the LDAP data connector. * //from w w w . ja va 2 s . c om * @param pluginId ID of the LDAP plugin * @param pluginConfig LDAP plugin configuration element * @param pluginConfigChildren child elements of the plugin * @param pluginBuilder plugin builder * @param parserContext current parsing context */ protected void processPoolingConfig(String pluginId, Element pluginConfig, Map<QName, List<Element>> pluginConfigChildren, BeanDefinitionBuilder pluginBuilder, ParserContext parserContext) { List<Element> poolConfigElems = pluginConfigChildren .get(new QName(DataConnectorNamespaceHandler.NAMESPACE, "ConnectionPool")); if (poolConfigElems == null || poolConfigElems.size() == 0) { log.debug("Data connector {} is pooling connections: {}", pluginId, false); pluginBuilder.addPropertyValue("poolStrategy", new LdapPoolEmptyStrategy()); return; } Element poolConfigElem = poolConfigElems.get(0); LdapPoolConfig ldapPoolConfig = new LdapPoolConfig(); LdapPoolVTStrategy ldapPoolStrategy = new LdapPoolVTStrategy(); ldapPoolStrategy.setLdapPoolConfig(ldapPoolConfig); log.debug("Data connector {} is pooling connections: {}", pluginId, true); pluginBuilder.addPropertyValue("poolStrategy", ldapPoolStrategy); int poolMinSize = 0; if (pluginConfig.hasAttributeNS(null, "poolInitialSize")) { poolMinSize = Integer.parseInt(pluginConfig.getAttributeNS(null, "poolInitialSize")); log.warn( "Data connector {} using deprecated attribute poolInitialSize on <DataConnector> use minPoolSize on child <PoolConfig> instead"); } else if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "minPoolSize")) { poolMinSize = Integer.parseInt(poolConfigElem.getAttributeNS(null, "minPoolSize")); } log.debug("Data connector {} pool minimum connections: {}", pluginId, poolMinSize); ldapPoolConfig.setMinPoolSize(poolMinSize); int poolMaxSize = 3; if (pluginConfig.hasAttributeNS(null, "poolMaxIdleSize")) { poolMaxSize = Integer.parseInt(pluginConfig.getAttributeNS(null, "poolMaxIdleSize")); log.warn( "Data connector {} using deprecated attribute poolMaxIdleSize on <DataConnector> use maxPoolSize on child <PoolConfig> instead"); } else if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "maxPoolSize")) { poolMaxSize = Integer.parseInt(poolConfigElem.getAttributeNS(null, "maxPoolSize")); } log.debug("Data connector {} pool maximum connections: {}", pluginId, poolMaxSize); ldapPoolConfig.setMaxPoolSize(poolMaxSize); boolean blockWhenEmpty = true; if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "blockWhenEmpty")) { blockWhenEmpty = XMLHelper .getAttributeValueAsBoolean(poolConfigElem.getAttributeNodeNS(null, "blockWhenEmpty")); } log.debug("Data connector {} pool block when empty: {}", pluginId, blockWhenEmpty); ldapPoolStrategy.setBlockWhenEmpty(blockWhenEmpty); int blockWaitTime = 0; if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "blockWaitTime")) { blockWaitTime = (int) SpringConfigurationUtils.parseDurationToMillis("blockWaitTime", poolConfigElem.getAttributeNS(null, "blockWaitTime"), 0); } if (blockWaitTime == 0) { log.debug("Data connector {} pool block wait time: indefintely", pluginId); } else { log.debug("Data connector {} pool block wait time: {}ms", pluginId, blockWaitTime); } ldapPoolStrategy.setBlockWaitTime(blockWaitTime); boolean poolValidatePeriodically = false; if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "validatePeriodically")) { poolValidatePeriodically = XMLHelper .getAttributeValueAsBoolean(poolConfigElem.getAttributeNodeNS(null, "validatePeriodically")); } log.debug("Data connector {} pool validate periodically: {}", pluginId, poolValidatePeriodically); ldapPoolConfig.setValidatePeriodically(poolValidatePeriodically); int poolValidateTimerPeriod = 1800000; if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "validateTimerPeriod")) { poolValidateTimerPeriod = (int) SpringConfigurationUtils.parseDurationToMillis("validateTimerPeriod", poolConfigElem.getAttributeNS(null, "validateTimerPeriod"), 0); } log.debug("Data connector {} pool validate timer period: {}ms", pluginId, poolValidateTimerPeriod); ldapPoolConfig.setValidateTimerPeriod(poolValidateTimerPeriod); String poolValidateDn = ""; if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "validateDN")) { poolValidateDn = poolConfigElem.getAttributeNS(null, "validateDN"); } String poolValidateFilter = "(objectClass=*)"; if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "validateFilter")) { poolValidateFilter = poolConfigElem.getAttributeNS(null, "validateFilter"); } LdapValidator poolValidator = new CompareLdapValidator(poolValidateDn, new SearchFilter(poolValidateFilter)); log.debug("Data connector {} pool validation filter: {}", pluginId, poolValidateFilter); pluginBuilder.addPropertyValue("poolValidator", poolValidator); int poolExpirationTime = 600000; if (poolConfigElem != null && poolConfigElem.hasAttributeNS(null, "expirationTime")) { poolExpirationTime = (int) SpringConfigurationUtils.parseDurationToMillis("expirationTime", poolConfigElem.getAttributeNS(null, "expirationTime"), 0); } log.debug("Data connector {} pool expiration time: {}ms", pluginId, poolExpirationTime); ldapPoolConfig.setExpirationTime(poolExpirationTime); }
From source file:de.betterform.xml.xforms.model.submission.Submission.java
private void submitReplaceEmbedXForms(Map response) throws XFormsException { // check for targetid String targetid = getXFormsAttribute(TARGETID_ATTRIBUTE); String resource = getResource(); Map eventInfo = new HashMap(); String error = null;/* ww w. java 2 s. c o m*/ if (targetid == null) { error = "targetId"; } else if (resource == null) { error = "resource"; } if (error != null && error.length() > 0) { eventInfo.put(XFormsConstants.ERROR_TYPE, "no " + error + "defined for submission resource"); this.container.dispatch(this.target, XFormsEventNames.SUBMIT_ERROR, eventInfo); return; } Document result = getResponseAsDocument(response); Node embedElement = result.getDocumentElement(); if (resource.indexOf("#") != -1) { // detected a fragment so extract that from our result Document String fragmentid = resource.substring(resource.indexOf("#") + 1); if (fragmentid.indexOf("?") != -1) { fragmentid = fragmentid.substring(0, fragmentid.indexOf("?")); } embedElement = DOMUtil.getById(result, fragmentid); } Element embeddedNode = null; if (LOGGER.isDebugEnabled()) { LOGGER.debug("get target element for id: " + targetid); } Element targetElem = this.container.getElementById(targetid); DOMResult domResult = new DOMResult(); //Test if targetElem exist. if (targetElem != null) { // destroy existing embedded form within targetNode if (targetElem.hasChildNodes()) { // destroyembeddedModels(targetElem); Initializer.disposeUIElements(targetElem); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("destroyed any existing ui elements for target elem"); } // import referenced embedded form into host document embeddedNode = (Element) this.container.getDocument().importNode(embedElement, true); //import namespaces NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(), (Element) embeddedNode); // keep original targetElem id within hostdoc embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id")); //copy all Attributes that might have been on original mountPoint to embedded node DOMUtil.copyAttributes(targetElem, embeddedNode, null); targetElem.getParentNode().replaceChild(embeddedNode, targetElem); //create model for it Initializer.initializeUIElements(model, embeddedNode, null, null); try { CachingTransformerService transformerService = new CachingTransformerService( new ClasspathResourceResolver("unused")); // TODO: MUST BE GENERIFIED USING USERAGENT MECHANISM //TODO: check exploded mode!!! String path = getClass().getResource("/META-INF/resources/xslt/xhtml.xsl").getPath(); //String xslFilePath = "file:" + path; transformerService.getTransformer(new URI(path)); XSLTGenerator generator = new XSLTGenerator(); generator.setTransformerService(transformerService); generator.setStylesheetURI(new URI(path)); generator.setInput(embeddedNode); generator.setOutput(domResult); generator.generate(); } catch (TransformerException e) { throw new XFormsException( "Transformation error while executing 'Submission.submitReplaceEmbedXForms'", e); } catch (URISyntaxException e) { throw new XFormsException( "Malformed URI throwed URISyntaxException in 'Submission.submitReplaceEmbedXForms'", e); } } // Map eventInfo = constructEventInfo(response); OutputStream outputStream = new ByteArrayOutputStream(); try { DOMUtil.prettyPrintDOM(domResult.getNode(), outputStream); } catch (TransformerException e) { throw new XFormsException(e); } eventInfo.put(EMBEDNODE, outputStream.toString()); eventInfo.put("embedTarget", targetid); eventInfo.put("embedXForms", true); // dispatch xforms-submit-done this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, eventInfo); }
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java
/** * This method takes the ER response and converts the Java objects to the Merge Response XML. * // w ww. j a va 2 s .c o m * @param entityContainerNode * @param results * @param recordLimit * @param attributeParametersNode * @return * @throws ParserConfigurationException * @throws XPathExpressionException * @throws TransformerException */ private Document createResponseMessage(Node entityContainerNode, EntityResolutionResults results, Node attributeParametersNode, int recordLimit) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document resultDocument = dbf.newDocumentBuilder().newDocument(); Element entityMergeResultMessageElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityMergeResultMessage"); resultDocument.appendChild(entityMergeResultMessageElement); Element entityContainerElement = resultDocument .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityContainer"); entityMergeResultMessageElement.appendChild(entityContainerElement); NodeList inputEntityNodes = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode, XPathConstants.NODESET); Collection<Element> inputEntityElements = null; if (attributeParametersNode == null) { inputEntityElements = new ArrayList<Element>(); } else { inputEntityElements = TreeMultiset .create(new EntityElementComparator((Element) attributeParametersNode)); //inputEntityElements = new ArrayList<Element>(); } for (int i = 0; i < inputEntityNodes.getLength(); i++) { inputEntityElements.add((Element) inputEntityNodes.item(i)); } if (attributeParametersNode == null) { LOG.warn("Attribute Parameters element was null, so records will not be sorted"); } //Collections.sort((List<Element>) inputEntityElements, new EntityElementComparator((Element) attributeParametersNode)); if (inputEntityElements.size() != inputEntityNodes.getLength()) { LOG.error("Lost elements in ER output sorting. Input count=" + inputEntityNodes.getLength() + ", output count=" + inputEntityElements.size()); } for (Element e : inputEntityElements) { Node clone = resultDocument.adoptNode(e.cloneNode(true)); resultDocument.renameNode(clone, EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, e.getLocalName()); entityContainerElement.appendChild(clone); } Element mergedRecordsElement = resultDocument .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "MergedRecords"); entityMergeResultMessageElement.appendChild(mergedRecordsElement); if (results != null) { List<RecordWrapper> records = results.getRecords(); // Loop through RecordWrappers to extract info to create merged records for (RecordWrapper record : records) { LOG.debug(" !#!#!#!# Record 1, id=" + record.getExternalId() + ", externals=" + record.getRelatedIds()); // Create Merged Record Container Element mergedRecordElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord"); mergedRecordsElement.appendChild(mergedRecordElement); // Create Original Record Reference for 'first record' Element originalRecordRefElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference"); originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref", record.getExternalId()); mergedRecordElement.appendChild(originalRecordRefElement); // Loop through and add any related records for (String relatedRecordId : record.getRelatedIds()) { originalRecordRefElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference"); originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref", relatedRecordId); mergedRecordElement.appendChild(originalRecordRefElement); } // Create Merge Quality Element Element mergeQualityElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality"); mergedRecordElement.appendChild(mergeQualityElement); Set<AttributeStatistics> stats = results.getStatisticsForRecord(record.getExternalId()); for (AttributeStatistics stat : stats) { Element stringDistanceStatsElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "StringDistanceStatistics"); mergeQualityElement.appendChild(stringDistanceStatsElement); Element xpathElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath"); stringDistanceStatsElement.appendChild(xpathElement); Node contentNode = resultDocument.createTextNode(stat.getAttributeName()); xpathElement.appendChild(contentNode); Element meanElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "StringDistanceMeanInRecord"); stringDistanceStatsElement.appendChild(meanElement); contentNode = resultDocument.createTextNode(String.valueOf(stat.getAverageStringDistance())); meanElement.appendChild(contentNode); Element sdElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "StringDistanceStandardDeviationInRecord"); stringDistanceStatsElement.appendChild(sdElement); contentNode = resultDocument .createTextNode(String.valueOf(stat.getStandardDeviationStringDistance())); sdElement.appendChild(contentNode); } } } else { for (Element e : inputEntityElements) { String id = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "id"); Element mergedRecordElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord"); mergedRecordsElement.appendChild(mergedRecordElement); Element originalRecordRefElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference"); originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref", id); mergedRecordElement.appendChild(originalRecordRefElement); Element mergeQualityElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality"); mergedRecordElement.appendChild(mergeQualityElement); XPath xp = XPathFactory.newInstance().newXPath(); xp.setNamespaceContext(new EntityResolutionNamespaceContext()); NodeList attributeParameterNodes = (NodeList) xp.evaluate("er-ext:AttributeParameter", attributeParametersNode, XPathConstants.NODESET); for (int i = 0; i < attributeParameterNodes.getLength(); i++) { String attributeName = xp.evaluate("er-ext:AttributeXPath", attributeParametersNode); Element stringDistanceStatsElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "StringDistanceStatistics"); mergeQualityElement.appendChild(stringDistanceStatsElement); Element xpathElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath"); stringDistanceStatsElement.appendChild(xpathElement); Node contentNode = resultDocument.createTextNode(attributeName); xpathElement.appendChild(contentNode); Element meanElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "StringDistanceMeanInRecord"); stringDistanceStatsElement.appendChild(meanElement); contentNode = resultDocument.createTextNode("0.0"); meanElement.appendChild(contentNode); Element sdElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "StringDistanceStandardDeviationInRecord"); stringDistanceStatsElement.appendChild(sdElement); contentNode = resultDocument.createTextNode("0.0"); sdElement.appendChild(contentNode); } } } Element recordLimitExceededElement = resultDocument.createElementNS( EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "RecordLimitExceededIndicator"); recordLimitExceededElement.setTextContent(new Boolean(results == null).toString()); entityMergeResultMessageElement.appendChild(recordLimitExceededElement); return resultDocument; }
From source file:com.android.ide.eclipse.adt.internal.editors.layout.gre.ClientRulesEngine.java
/** Find declared ids under the given DOM node */ private static void addIds(Node node, Set<String> ids) { if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; String id = element.getAttributeNS(ANDROID_URI, ATTR_ID); if (id != null && id.startsWith(NEW_ID_PREFIX)) { ids.add(BaseViewRule.stripIdPrefix(id)); }/*from w ww. ja v a2s . c om*/ } NodeList children = node.getChildNodes(); for (int i = 0, n = children.getLength(); i < n; i++) { Node child = children.item(i); addIds(child, ids); } }