List of usage examples for org.w3c.dom Element getNamespaceURI
public String getNamespaceURI();
null
if it is unspecified (see ). From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerSpringBookTest.java
private void checkWadlResourcesType(String baseURI, String requestTypeURI, String schemaRef) throws Exception { WebClient client = WebClient.create(requestTypeURI); WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(1000000); Document doc = StaxUtils.read(new InputStreamReader(client.get(InputStream.class), StandardCharsets.UTF_8)); Element root = doc.getDocumentElement(); assertEquals(WadlGenerator.WADL_NS, root.getNamespaceURI()); assertEquals("application", root.getLocalName()); List<Element> grammarEls = DOMUtils.getChildrenWithName(root, WadlGenerator.WADL_NS, "grammars"); assertEquals(1, grammarEls.size());// w w w . j a v a 2s. c om List<Element> includeEls = DOMUtils.getChildrenWithName(grammarEls.get(0), WadlGenerator.WADL_NS, "include"); assertEquals(1, includeEls.size()); String href = includeEls.get(0).getAttribute("href"); assertEquals(baseURI + schemaRef, href); List<Element> resourcesEls = DOMUtils.getChildrenWithName(root, WadlGenerator.WADL_NS, "resources"); assertEquals(0, resourcesEls.size()); List<Element> resourceTypeEls = DOMUtils.getChildrenWithName(root, WadlGenerator.WADL_NS, "resource_type"); assertEquals(1, resourceTypeEls.size()); }
From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerSpringBookTest.java
private List<Element> checkWadlResourcesInfo(Document doc, String baseURI, String schemaRef, int size) throws Exception { Element root = doc.getDocumentElement(); assertEquals(WadlGenerator.WADL_NS, root.getNamespaceURI()); assertEquals("application", root.getLocalName()); List<Element> grammarEls = DOMUtils.getChildrenWithName(root, WadlGenerator.WADL_NS, "grammars"); assertEquals(1, grammarEls.size());/*from www . j a v a2 s . c o m*/ List<Element> includeEls = DOMUtils.getChildrenWithName(grammarEls.get(0), WadlGenerator.WADL_NS, "include"); assertEquals(1, includeEls.size()); String href = includeEls.get(0).getAttribute("href"); assertEquals(baseURI + schemaRef, href); List<Element> resourcesEls = DOMUtils.getChildrenWithName(root, WadlGenerator.WADL_NS, "resources"); assertEquals(1, resourcesEls.size()); Element resourcesEl = resourcesEls.get(0); assertEquals(baseURI, resourcesEl.getAttribute("base")); List<Element> resourceEls = DOMUtils.getChildrenWithName(resourcesEl, WadlGenerator.WADL_NS, "resource"); assertEquals(size, resourceEls.size()); return resourceEls; }
From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerSpringBookTest.java
private void checkSchemas(String address, String schemaSegment, String includedSchema, String refAttrName) throws Exception { WebClient client = WebClient.create(address + schemaSegment); WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(10000000L); Document doc = StaxUtils.read(new InputStreamReader(client.get(InputStream.class), StandardCharsets.UTF_8)); Element root = doc.getDocumentElement(); assertEquals(Constants.URI_2001_SCHEMA_XSD, root.getNamespaceURI()); assertEquals("schema", root.getLocalName()); if (includedSchema != null) { List<Element> includeEls = DOMUtils.getChildrenWithName(root, Constants.URI_2001_SCHEMA_XSD, refAttrName);/*from ww w. j a v a2 s .co m*/ assertEquals(1, includeEls.size()); String href = includeEls.get(0).getAttribute("schemaLocation"); assertEquals(address + includedSchema, href); } }
From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java
protected Revision parseIdentificationAnnotations(Annotations annotations) { SortedMap<Calendar, UUID> revisions = new TreeMap<>(); if (annotations == null || annotations.getAnnotationChainOrAnnotationChain22() == null) return null; for (JAXBElement<AnnotationChain> el : annotations.getAnnotationChainOrAnnotationChain22()) { NetSfTavernaT2AnnotationAnnotationAssertionImpl ann = el.getValue() .getNetSfTavernaT2AnnotationAnnotationChainImpl().getAnnotationAssertions() .getNetSfTavernaT2AnnotationAnnotationAssertionImpl(); String annClass = ann.getAnnotationBean().getClazz(); if (!annClass.equals(IDENTIFICATION_ASSERTION)) continue; for (Object obj : ann.getAnnotationBean().getAny()) { if (!(obj instanceof Element)) continue; Element elem = (Element) obj; if (elem.getNamespaceURI() == null && elem.getLocalName().equals("identification")) { String uuid = elem.getTextContent().trim(); String date = ann.getDate(); Calendar cal = parseDate(date); revisions.put(cal, UUID.fromString(uuid)); }//from w ww . j av a2 s. c o m } } Revision rev = null; for (Entry<Calendar, UUID> entry : revisions.entrySet()) { Calendar cal = entry.getKey(); UUID uuid = entry.getValue(); URI uri = WORKFLOW_ROOT.resolve(uuid.toString() + "/"); rev = new Revision(uri, rev); rev.setGeneratedAtTime(cal); } return rev; }
From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java
private void validateToken(Element tokenElement, String expectedAudience, IdentityProviderConfiguration identityProviderConfiguration) throws Exception { List<X509Certificate> certificateChain = identityProviderConfiguration.getIdentityCertificateChain(); if (certificateChain.isEmpty()) { throw new SecurityException("no eID IdP service identity configured"); }// w ww. j a v a2 s.co m Element nsElement = tokenElement.getOwnerDocument().createElement("nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion"); LOG.debug("token element: " + tokenElement.getLocalName()); LOG.debug("token element namespace: " + tokenElement.getNamespaceURI()); LOG.debug("token: " + toString(tokenElement)); // fix for recent versions of Apache xmlsec. tokenElement.setIdAttribute("ID", true); Element signatureElement = (Element) XPathAPI.selectSingleNode(tokenElement, "ds:Signature", nsElement); if (null == signatureElement) { throw new SecurityException("missing XML signature"); } XMLSignature xmlSignature = new XMLSignature(signatureElement, ""); KeyInfo keyInfo = xmlSignature.getKeyInfo(); X509Certificate actualCertificate = keyInfo.getX509Certificate(); boolean signatureResult = xmlSignature.checkSignatureValue(actualCertificate); if (false == signatureResult) { throw new SecurityException("invalid XML signature"); } LOG.debug("XML signature OK"); X509Certificate serviceCertificate = certificateChain.get(0); if (false == Arrays.equals(serviceCertificate.getEncoded(), actualCertificate.getEncoded())) { throw new SecurityException("SAML signing certificate different from eID IdP service identity"); } LOG.debug("SAML signer OK"); String actualIssuer = XPathAPI.selectSingleNode(tokenElement, "saml2:Issuer/text()", nsElement) .getNodeValue(); String serviceIssuer = identityProviderConfiguration.getDefaultIssuer(); if (false == actualIssuer.equals(serviceIssuer)) { LOG.debug("actual issuer: " + actualIssuer); LOG.debug("service issuer: " + serviceIssuer); throw new SecurityException("wrong SAML issuer"); } LOG.debug("SAML issuer OK"); if (null != expectedAudience) { String audience = XPathAPI .selectSingleNode(tokenElement, "saml2:Conditions/saml2:AudienceRestriction/saml2:Audience/text()", nsElement) .getNodeValue(); if (false == expectedAudience.equals(audience)) { LOG.debug("expected audience: " + expectedAudience); LOG.debug("actual audience: " + audience); throw new SecurityException("incorrect SAML audience"); } LOG.debug("SAML Audience OK"); } else { LOG.warn("SAML audience restriction not checked"); } String authnContextClassRef = XPathAPI .selectSingleNode(tokenElement, "saml2:AuthnStatement/saml2:AuthnContext/saml2:AuthnContextClassRef/text()", nsElement) .getNodeValue(); LOG.debug("AuthnContextClassRef: " + authnContextClassRef); SamlAuthenticationPolicy samlAuthenticationPolicy = SamlAuthenticationPolicy .getAuthenticationPolicy(authnContextClassRef); if (SamlAuthenticationPolicy.AUTHENTICATION != samlAuthenticationPolicy && SamlAuthenticationPolicy.AUTHENTICATION_WITH_IDENTIFICATION != samlAuthenticationPolicy) { throw new SecurityException("wrong SAML authentication policy: " + samlAuthenticationPolicy); } String notBeforeStr = XPathAPI.selectSingleNode(tokenElement, "saml2:Conditions/@NotBefore", nsElement) .getNodeValue(); String notOnOrAfterStr = XPathAPI .selectSingleNode(tokenElement, "saml2:Conditions/@NotOnOrAfter", nsElement).getNodeValue(); DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser(); DateTime notBefore = dateTimeFormatter.parseDateTime(notBeforeStr); DateTime notOnOrAfter = dateTimeFormatter.parseDateTime(notOnOrAfterStr); DateTime now = new DateTime(); if (now.isBefore(notBefore)) { throw new SecurityException("SAML assertion in future"); } if (now.isAfter(notOnOrAfter)) { throw new SecurityException("SAML assertion expired"); } LOG.debug("SAML timestamp OK"); }
From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java
public void parseAnnotations(WorkflowBean annotatedBean, Annotations annotations) throws ReaderException { // logger.fine("Checking annotations for " + annotatedSubject); Map<String, NetSfTavernaT2AnnotationAnnotationAssertionImpl> annotationElems = new HashMap<>(); if (annotations == null || annotations.getAnnotationChainOrAnnotationChain22() == null) return;/* www . ja v a 2 s . c o m*/ for (JAXBElement<AnnotationChain> el : annotations.getAnnotationChainOrAnnotationChain22()) { NetSfTavernaT2AnnotationAnnotationAssertionImpl ann = el.getValue() .getNetSfTavernaT2AnnotationAnnotationChainImpl().getAnnotationAssertions() .getNetSfTavernaT2AnnotationAnnotationAssertionImpl(); String annClass = ann.getAnnotationBean().getClazz(); if (annotationElems.containsKey(annClass) && annotationElems.get(annClass).getDate().compareToIgnoreCase(ann.getDate()) > 0) // ann.getDate() is less than current 'latest' annotation, skip continue; annotationElems.put(annClass, ann); } for (String clazz : annotationElems.keySet()) { NetSfTavernaT2AnnotationAnnotationAssertionImpl ann = annotationElems.get(clazz); Calendar cal = parseDate(ann.getDate()); String value = null; String semanticMediaType = TEXT_TURTLE; for (Object obj : ann.getAnnotationBean().getAny()) { if (!(obj instanceof Element)) continue; Element elem = (Element) obj; if (!(elem.getNamespaceURI() == null)) continue; if (elem.getLocalName().equals("text")) { value = elem.getTextContent().trim(); break; } if (clazz.equals(SEMANTIC_ANNOTATION)) { if (elem.getLocalName().equals("content")) value = elem.getTextContent().trim(); if (elem.getLocalName().equals("mimeType")) semanticMediaType = elem.getTextContent().trim(); } } if (value != null) { // Add the annotation Annotation annotation = new Annotation(); WorkflowBundle workflowBundle = parserState.get().getCurrentWorkflowBundle(); annotation.setParent(workflowBundle); String path = "annotation/" + annotation.getName() + ".ttl"; URI bodyURI = URI.create(path); annotation.setTarget(annotatedBean); annotation.setAnnotatedAt(cal); // annotation.setAnnotator(); annotation.setSerializedBy(t2flowParserURI); annotation.setSerializedAt(new GregorianCalendar()); URI annotatedSubject = uriTools.relativeUriForBean(annotatedBean, annotation); String body; if (clazz.equals(SEMANTIC_ANNOTATION)) { String baseStr = "@base <" + annotatedSubject.toASCIIString() + "> .\n"; body = baseStr + value; } else { // Generate Turtle from 'classic' annotation URI predicate = getPredicatesForClass().get(clazz); if (predicate == null) { if (isStrict()) throw new ReaderException("Unsupported annotation class " + clazz); return; } StringBuilder turtle = new StringBuilder(); turtle.append("<"); turtle.append(annotatedSubject.toASCIIString()); turtle.append("> "); turtle.append("<"); turtle.append(predicate.toASCIIString()); turtle.append("> "); // A potentially multi-line string turtle.append("\"\"\""); // Escape existing \ to \\ String escaped = value.replace("\\", "\\\\"); // Escape existing " to \" (beware Java's escaping of \ and " below) escaped = escaped.replace("\"", "\\\""); turtle.append(escaped); turtle.append("\"\"\""); turtle.append(" ."); body = turtle.toString(); } try { workflowBundle.getResources().addResource(body, path, semanticMediaType); } catch (IOException e) { throw new ReaderException("Could not store annotation body to " + path, e); } annotation.setBody(bodyURI); } } }
From source file:org.springjutsu.validation.namespace.ValidationConfigurationDefinitionParser.java
/** * Do actual parsing./*w ww. j av a 2 s.com*/ */ public BeanDefinition parse(Element configNode, ParserContext context) { BeanDefinitionBuilder validationManagerBuilder = BeanDefinitionBuilder .genericBeanDefinition(ValidationManager.class); BeanDefinitionBuilder validationErrorMessageHandlerBuilder = BeanDefinitionBuilder .genericBeanDefinition(ValidationErrorMessageHandler.class); BeanDefinitionBuilder ruleExecutorContainerBuilder = BeanDefinitionBuilder .genericBeanDefinition(RuleExecutorContainer.class); BeanDefinitionBuilder contextHandlerContainerBuilder = BeanDefinitionBuilder .genericBeanDefinition(ValidationContextHandlerContainer.class); BeanDefinitionBuilder validationRulesContainerBuilder = BeanDefinitionBuilder .genericBeanDefinition(ValidationRulesContainer.class); // Parse message configuration... Element messageConfig = (Element) configNode .getElementsByTagNameNS(configNode.getNamespaceURI(), "message-config").item(0); if (messageConfig != null) { validationErrorMessageHandlerBuilder.addPropertyValue("errorMessagePrefix", messageConfig.getAttribute("errorMessagePrefix")); validationErrorMessageHandlerBuilder.addPropertyValue("fieldLabelPrefix", messageConfig.getAttribute("fieldLabelPrefix")); validationErrorMessageHandlerBuilder.addPropertyValue("enableSuperclassFieldLabelLookup", messageConfig.getAttribute("enableSuperclassFieldLabelLookup")); } // Parse rules configuration... Element rulesConfig = (Element) configNode .getElementsByTagNameNS(configNode.getNamespaceURI(), "rules-config").item(0); if (rulesConfig != null) { boolean addDefaultRules = Boolean.valueOf(rulesConfig.getAttribute("addDefaultRuleExecutors")); ruleExecutorContainerBuilder.addPropertyValue("addDefaultRuleExecutors", addDefaultRules); List<KeyedBeanRegistrant> ruleExecutors = new ArrayList<KeyedBeanRegistrant>(); NodeList ruleExecutorNodes = rulesConfig.getElementsByTagNameNS(rulesConfig.getNamespaceURI(), "rule-executor"); for (int executorNbr = 0; executorNbr < ruleExecutorNodes.getLength(); executorNbr++) { Element ruleExecutorNode = (Element) ruleExecutorNodes.item(executorNbr); BeanDefinitionBuilder executorBuilder = BeanDefinitionBuilder .genericBeanDefinition(ruleExecutorNode.getAttribute("class")); String ruleExecutorBeanName = registerInfrastructureBean(context, executorBuilder); ruleExecutors .add(new KeyedBeanRegistrant(ruleExecutorBeanName, ruleExecutorNode.getAttribute("name"))); } ruleExecutorContainerBuilder.addPropertyValue("ruleExecutorBeanRegistrants", ruleExecutors); List<Class<?>> excludeAnnotations = new ArrayList<Class<?>>(); excludeAnnotations.add(RecursiveValidationExclude.class); NodeList excludeAnnotationNodes = rulesConfig.getElementsByTagNameNS(rulesConfig.getNamespaceURI(), "recursion-exclude-annotation"); for (int excludeNbr = 0; excludeNbr < excludeAnnotationNodes.getLength(); excludeNbr++) { Element excludeNode = (Element) excludeAnnotationNodes.item(excludeNbr); String excludeAnnotationClass = excludeNode.getAttribute("class"); try { excludeAnnotations.add(Class.forName(excludeAnnotationClass)); } catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException( "Invalid exclude annotation class: " + excludeAnnotationClass, cnfe); } } validationRulesContainerBuilder.addPropertyValue("excludeAnnotations", excludeAnnotations); List<Class<?>> includeAnnotations = new ArrayList<Class<?>>(); includeAnnotations.add(RecursiveValidationInclude.class); NodeList includeAnnotationNodes = rulesConfig.getElementsByTagNameNS(rulesConfig.getNamespaceURI(), "recursion-include-annotation"); for (int includeNbr = 0; includeNbr < includeAnnotationNodes.getLength(); includeNbr++) { Element includeNode = (Element) includeAnnotationNodes.item(includeNbr); String includeAnnotationClass = includeNode.getAttribute("class"); try { includeAnnotations.add(Class.forName(includeAnnotationClass)); } catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException( "Invalid include annotation class: " + includeAnnotationClass, cnfe); } } validationRulesContainerBuilder.addPropertyValue("includeAnnotations", includeAnnotations); } // Parse context configuration... Element contextConfig = (Element) configNode .getElementsByTagNameNS(configNode.getNamespaceURI(), "context-config").item(0); if (contextConfig != null) { boolean addDefaultContextHandlers = Boolean .valueOf(contextConfig.getAttribute("addDefaultContextHandlers")); contextHandlerContainerBuilder.addPropertyValue("addDefaultContextHandlers", addDefaultContextHandlers); List<KeyedBeanRegistrant> contextHandlers = new ArrayList<KeyedBeanRegistrant>(); NodeList contextHandlerNodes = contextConfig.getElementsByTagNameNS(contextConfig.getNamespaceURI(), "context-handler"); for (int handlerNbr = 0; handlerNbr < contextHandlerNodes.getLength(); handlerNbr++) { Element contextHandlerNode = (Element) contextHandlerNodes.item(handlerNbr); BeanDefinitionBuilder handlerBuilder = BeanDefinitionBuilder .genericBeanDefinition(contextHandlerNode.getAttribute("class")); String ruleExecutorBeanName = registerInfrastructureBean(context, handlerBuilder); contextHandlers.add( new KeyedBeanRegistrant(ruleExecutorBeanName, contextHandlerNode.getAttribute("type"))); } contextHandlerContainerBuilder.addPropertyValue("contextHandlerBeanRegistrants", contextHandlers); } // Register them beans. registerInfrastructureBean(context, validationRulesContainerBuilder); registerInfrastructureBean(context, ruleExecutorContainerBuilder); registerInfrastructureBean(context, contextHandlerContainerBuilder); registerInfrastructureBean(context, validationErrorMessageHandlerBuilder); context.registerBeanComponent(new BeanComponentDefinition(validationManagerBuilder.getBeanDefinition(), configNode.getAttribute("validatorName"))); return null; }
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./* w w w . j a v a2 s. c o m*/ */ 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:io.personium.core.model.impl.fs.DavCmpFsImpl.java
/** * load the info from FS for this Dav resouce. *//*from w w w . ja va 2s. co m*/ public final void load() { this.metaFile.load(); /* * Analyze JSON Object, and set metadata such as ACL. */ this.name = fsDir.getName(); this.acl = this.translateAcl(this.metaFile.getAcl()); @SuppressWarnings("unchecked") Map<String, String> props = (Map<String, String>) this.metaFile.getProperties(); if (props != null) { for (Map.Entry<String, String> entry : props.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); int idx = key.indexOf("@"); String elementName = key.substring(0, idx); String namespace = key.substring(idx + 1); QName keyQName = new QName(namespace, elementName); Element element = parseProp(val); String elementNameSpace = element.getNamespaceURI(); // ownerRepresentativeAccounts??? if (Key.PROP_KEY_OWNER_REPRESENTIVE_ACCOUNTS.equals(keyQName)) { NodeList accountNodeList = element.getElementsByTagNameNS(elementNameSpace, Key.PROP_KEY_OWNER_REPRESENTIVE_ACCOUNT.getLocalPart()); for (int i = 0; i < accountNodeList.getLength(); i++) { this.ownerRepresentativeAccounts.add(accountNodeList.item(i).getTextContent().trim()); } } } } }
From source file:org.jdal.beans.ServiceBeanDefinitionParser.java
/** * {@inheritDoc}/* w w w. j a va 2 s .co m*/ */ public AbstractBeanDefinition parse(Element element, ParserContext parserContext) { // default dao and service classes String daoClassName = JPA_DAO_CLASS_NAME; String serviceClassName = PERSISTENT_SERVICE_CLASS_NAME; String name = null; boolean declareService = false; if (element.hasAttribute(DAO_CLASS)) daoClassName = element.getAttribute(DAO_CLASS); if (element.hasAttribute(SERVICE_CLASS)) { serviceClassName = element.getAttribute(SERVICE_CLASS); declareService = true; } if (element.hasAttribute(NAME)) name = element.getAttribute(NAME); if (element.hasAttribute(ENTITY)) { String className = element.getAttribute(ENTITY); if (name == null) { name = StringUtils .uncapitalize(StringUtils.substringAfterLast(className, PropertyUtils.PROPERTY_SEPARATOR)); } parserContext.pushContainingComponent( new CompositeComponentDefinition(name, parserContext.extractSource(element))); // Dao BeanDefinitionBuilder daoBuilder = BeanDefinitionBuilder.genericBeanDefinition(daoClassName); NodeList nl = element.getElementsByTagNameNS(element.getNamespaceURI(), CRITERIA); if (nl.getLength() > 0) { ManagedMap<String, BeanReference> builders = new ManagedMap<String, BeanReference>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); builders.put(e.getAttribute(NAME), new RuntimeBeanReference(e.getAttribute(BUILDER))); } daoBuilder.addPropertyValue(CRITERIA_BUILDER_MAP, builders); } daoBuilder.addConstructorArgValue(ClassUtils.resolveClassName(className, null)); daoBuilder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); String daoBeanName; if (declareService) { // use dao suffix daoBeanName = name + DAO_SUFFIX; registerBeanDefinition(parserContext, daoBuilder, daoBeanName); // register service wrapper String serviceBeanName = name + SERVICE_SUFFIX; BeanDefinitionBuilder serviceBuilder = BeanDefinitionBuilder .genericBeanDefinition(serviceClassName); serviceBuilder.addPropertyReference("dao", daoBeanName); registerBeanDefinition(parserContext, serviceBuilder, serviceBeanName); } else { // use service suffix for dao and declare an alias with dao suffix for compatibility with older api. daoBeanName = name + SERVICE_SUFFIX; String[] aliases = new String[] { name + DAO_SUFFIX }; BeanComponentDefinition bcd = new BeanComponentDefinition(daoBuilder.getBeanDefinition(), daoBeanName, aliases); parserContext.registerBeanComponent(bcd); } parserContext.popAndRegisterContainingComponent(); } return null; }