List of usage examples for javax.xml.namespace NamespaceContext NamespaceContext
NamespaceContext
From source file:org.craftercms.cstudio.share.forms.impl.FormServiceBaseImpl.java
/** * merge the instance data with the document * /*w w w .j a v a 2s. c om*/ * @param xformDocument * @param model * @return */ protected Document mergeInstanceDataWithForm(Document xformDocument, Map<String, Document> model, final String namespace) { Document retDocument = xformDocument; if (model != null) { XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); try { NamespaceContext cstudio = new NamespaceContext() { public String getNamespaceURI(String prefix) { String uri = ""; if (prefix.equals(namespace)) uri = "http://www.w3.org/2002/xforms"; return uri; } @SuppressWarnings("unchecked") public Iterator getPrefixes(String val) { return null; } public String getPrefix(String uri) { return null; } }; xPath.setNamespaceContext(cstudio); XPathExpression xPathExpression = xPath.compile("//" + namespace + ":instance"); // DOMSource source = new DOMSource(xformDocument); // StringWriter xmlAsWriter = new StringWriter(); // StreamResult result = new StreamResult(xmlAsWriter); // TransformerFactory.newInstance().newTransformer().transform(source, // result); StringReader xmlReader = new StringReader(DomUtils.xmlToString(xformDocument)); InputSource documentAsInputSource = new InputSource(xmlReader); // using implementation here, see article // http://onjava.com/pub/a/onjava/2005/01/12/xpath.html DTMNodeList nodes = (DTMNodeList) xPathExpression.evaluate(documentAsInputSource, XPathConstants.NODESET); int nodeCount = nodes.getLength(); for (int i = 0; i < nodeCount; i++) { Element currentNode = (Element) nodes.item(i); String modelId = currentNode.getAttribute("id"); Document documentToInsert = model.get(modelId); if (documentToInsert != null) { Element importedModelRoot = documentToInsert.getDocumentElement(); retDocument = currentNode.getOwnerDocument(); Node importedModel = retDocument.importNode(importedModelRoot, true); currentNode.appendChild(importedModel); } } } catch (Exception e) { e.printStackTrace(); } } return retDocument; }
From source file:org.entrystore.harvesting.oaipmh.jobs.GetRecordJob.java
/** * //from ww w. j a va 2s. co m * @return */ private static NamespaceContext createNamespace() { // We map the prefixes to URIs NamespaceContext ctx = new NamespaceContext() { public String getNamespaceURI(String prefix) { String uri; if (prefix.equals("oai")) uri = "http://www.openarchives.org/OAI/2.0/"; else if (prefix.equals("dc")) uri = "http://purl.org/dc/elements/1.1/"; else if (prefix.equals("oai_dc")) uri = "http://www.openarchives.org/OAI/2.0/oai_dc/"; else uri = null; return uri; } // Dummy implementation - not used! public Iterator getPrefixes(String val) { return null; } // Dummy implementation - not used! public String getPrefix(String uri) { return null; } }; return ctx; }
From source file:org.entrystore.harvesting.oaipmh.jobs.ListRecordsJob.java
private static NamespaceContext createNamespace() { // We map the prefixes to URIs NamespaceContext ctx = new NamespaceContext() { public String getNamespaceURI(String prefix) { String uri;// www. j a v a 2s .c o m if (prefix.equals("oai")) uri = "http://www.openarchives.org/OAI/2.0/"; else if (prefix.equals("dc")) uri = "http://purl.org/dc/elements/1.1/"; else if (prefix.equals("dcterms")) uri = "http://purl.org/dc/terms/"; else if (prefix.equals("oai_dc")) uri = "http://www.openarchives.org/OAI/2.0/oai_dc/"; else if (prefix.equals("rdn_dc")) uri = "http://www.rdn.ac.uk/oai/rdn_dc/"; else if (prefix.equals("lom")) uri = "http://ltsc.ieee.org/xsd/LOM"; else uri = null; return uri; } // Dummy implementation - not used! public Iterator getPrefixes(String val) { return null; } // Dummy implemenation - not used! public String getPrefix(String uri) { return null; } }; return ctx; }
From source file:org.iexhub.connectors.XdsBRepositoryManager.java
private XPath getCustomXPath() { XPath xPath = XPathFactory.newInstance().newXPath(); //set namespace to xpath xPath.setNamespaceContext(new NamespaceContext() { private final String uri = "urn:hl7-org:v3"; private final String prefix = "hl7"; @Override// ww w.j a v a 2 s . c om public String getNamespaceURI(String prefix) { return this.prefix.equals(prefix) ? uri : null; } @Override public String getPrefix(String namespaceURI) { return this.uri.equals(namespaceURI) ? this.prefix : null; } @Override public Iterator getPrefixes(String namespaceURI) { return null; } }); return xPath; }
From source file:org.iexhub.services.GetPatientDataService.java
@GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public Response getPatientData(@Context HttpHeaders headers) { log.info("Entered getPatientData service"); boolean tls = false; tls = (IExHubConfig.getProperty("XdsBRegistryEndpointURI") == null) ? false : ((IExHubConfig.getProperty("XdsBRegistryEndpointURI").toLowerCase().contains("https") ? true : false));/*from w w w . ja va 2s . c o m*/ GetPatientDataService.testMode = IExHubConfig.getProperty("TestMode", GetPatientDataService.testMode); GetPatientDataService.testJSONDocumentPathname = IExHubConfig.getProperty("TestJSONDocumentPathname", GetPatientDataService.testJSONDocumentPathname); GetPatientDataService.cdaToJsonTransformXslt = IExHubConfig.getProperty("CDAToJSONTransformXSLT", GetPatientDataService.cdaToJsonTransformXslt); GetPatientDataService.iExHubDomainOid = IExHubConfig.getProperty("IExHubDomainOID", GetPatientDataService.iExHubDomainOid); GetPatientDataService.iExHubAssigningAuthority = IExHubConfig.getProperty("IExHubAssigningAuthority", GetPatientDataService.iExHubAssigningAuthority); GetPatientDataService.xdsBRepositoryUniqueId = IExHubConfig.getProperty("XdsBRepositoryUniqueId", GetPatientDataService.xdsBRepositoryUniqueId); String retVal = ""; GetPatientDataResponse patientDataResponse = new GetPatientDataResponse(); StringBuilder jsonOutput = new StringBuilder(); if (!testMode) { try { if (xdsB == null) { log.info("Instantiating XdsB connector..."); xdsB = new XdsB(null, null, tls); log.info("XdsB connector successfully started"); } } catch (Exception e) { log.error("Error encountered instantiating XdsB connector, " + e.getMessage()); throw new UnexpectedServerException("Error - " + e.getMessage()); } try { MultivaluedMap<String, String> headerParams = headers.getRequestHeaders(); String ssoAuth = headerParams.getFirst("ssoauth"); log.info("HTTP headers successfully retrieved"); // Extract patient ID, query start date, and query end date. Expected format from the client is // "PatientId={0}&LastName={1}&FirstName={2}&MiddleName={3}&DateOfBirth={4}&PatientGender={5}&MotherMaidenName={6}&AddressStreet={7}&AddressCity={8}&AddressState={9}&AddressPostalCode={10}&OtherIDsScopingOrganization={11}&StartDate={12}&EndDate={13}" String[] splitPatientId = ssoAuth.split("&LastName="); String patientId = (splitPatientId[0].split("=").length == 2) ? splitPatientId[0].split("=")[1] : null; String[] parts = splitPatientId[1].split("&"); String lastName = (parts[0].length() > 0) ? parts[0] : null; String firstName = (parts[1].split("=").length == 2) ? parts[1].split("=")[1] : null; String middleName = (parts[2].split("=").length == 2) ? parts[2].split("=")[1] : null; String dateOfBirth = (parts[3].split("=").length == 2) ? parts[3].split("=")[1] : null; String gender = (parts[4].split("=").length == 2) ? parts[4].split("=")[1] : null; String motherMaidenName = (parts[5].split("=").length == 2) ? parts[5].split("=")[1] : null; String addressStreet = (parts[6].split("=").length == 2) ? parts[6].split("=")[1] : null; String addressCity = (parts[7].split("=").length == 2) ? parts[7].split("=")[1] : null; String addressState = (parts[8].split("=").length == 2) ? parts[8].split("=")[1] : null; String addressPostalCode = (parts[9].split("=").length == 2) ? parts[9].split("=")[1] : null; String otherIDsScopingOrganization = (parts[10].split("=").length == 2) ? parts[10].split("=")[1] : null; String startDate = (parts[11].split("=").length == 2) ? parts[11].split("=")[1] : null; String endDate = (parts[12].split("=").length == 2) ? parts[12].split("=")[1] : null; log.info("HTTP headers successfully parsed, now calling XdsB registry..."); // Determine if a complete patient ID (including OID and ISO specification) was provided. If not, then append IExHubDomainOid and IExAssigningAuthority... if (!patientId.contains("^^^&")) { patientId = "'" + patientId + "^^^&" + GetPatientDataService.iExHubDomainOid + "&" + GetPatientDataService.iExHubAssigningAuthority + "'"; } AdhocQueryResponse registryResponse = xdsB.registryStoredQuery(patientId, (startDate != null) ? DateFormat.getDateInstance().format(startDate) : null, (endDate != null) ? DateFormat.getDateInstance().format(endDate) : null); log.info("Call to XdsB registry successful"); // Determine if registry server returned any errors... if ((registryResponse.getRegistryErrorList() != null) && (registryResponse.getRegistryErrorList().getRegistryError().length > 0)) { for (RegistryError_type0 error : registryResponse.getRegistryErrorList().getRegistryError()) { StringBuilder errorText = new StringBuilder(); if (error.getErrorCode() != null) { errorText.append("Error code=" + error.getErrorCode() + "\n"); } if (error.getCodeContext() != null) { errorText.append("Error code context=" + error.getCodeContext() + "\n"); } // Error code location (i.e., stack trace) only to be logged to IExHub error file patientDataResponse.getErrorMsgs().add(errorText.toString()); if (error.getLocation() != null) { errorText.append("Error location=" + error.getLocation()); } log.error(errorText.toString()); } } // Try to retrieve documents... RegistryObjectListType registryObjectList = registryResponse.getRegistryObjectList(); IdentifiableType[] documentObjects = registryObjectList.getIdentifiable(); if ((documentObjects != null) && (documentObjects.length > 0)) { log.info("Documents found in the registry, retrieving them from the repository..."); HashMap<String, String> documents = new HashMap<String, String>(); for (IdentifiableType identifiable : documentObjects) { if (identifiable.getClass().equals(ExtrinsicObjectType.class)) { // Determine if the "home" attribute (homeCommunityId in XCA parlance) is present... String home = ((((ExtrinsicObjectType) identifiable).getHome() != null) && (((ExtrinsicObjectType) identifiable).getHome().getPath().length() > 0)) ? ((ExtrinsicObjectType) identifiable).getHome().getPath() : null; ExternalIdentifierType[] externalIdentifiers = ((ExtrinsicObjectType) identifiable) .getExternalIdentifier(); // Find the ExternalIdentifier that has the "XDSDocumentEntry.uniqueId" value... String uniqueId = null; for (ExternalIdentifierType externalIdentifier : externalIdentifiers) { String val = externalIdentifier.getName().getInternationalStringTypeSequence()[0] .getLocalizedString().getValue().getFreeFormText(); if ((val != null) && (val.compareToIgnoreCase("XDSDocumentEntry.uniqueId") == 0)) { log.info("Located XDSDocumentEntry.uniqueId ExternalIdentifier, uniqueId=" + uniqueId); uniqueId = externalIdentifier.getValue().getLongName(); break; } } if (uniqueId != null) { documents.put(uniqueId, home); log.info("Document ID added: " + uniqueId + ", homeCommunityId: " + home); } } else { String home = ((identifiable.getHome() != null) && (identifiable.getHome().getPath().length() > 0)) ? identifiable.getHome().getPath() : null; documents.put(identifiable.getId().getPath(), home); log.info("Document ID added: " + identifiable.getId().getPath() + ", homeCommunityId: " + home); } } log.info("Invoking XdsB repository connector retrieval..."); RetrieveDocumentSetResponse documentSetResponse = xdsB .retrieveDocumentSet(xdsBRepositoryUniqueId, documents, patientId); log.info("XdsB repository connector retrieval succeeded"); // Invoke appropriate map(s) to process documents in documentSetResponse... if (documentSetResponse.getRetrieveDocumentSetResponse() .getRetrieveDocumentSetResponseTypeSequence_type0() != null) { DocumentResponse_type0[] docResponseArray = documentSetResponse .getRetrieveDocumentSetResponse().getRetrieveDocumentSetResponseTypeSequence_type0() .getDocumentResponse(); if (docResponseArray != null) { jsonOutput.append("{\"Documents\":["); boolean first = true; try { for (DocumentResponse_type0 document : docResponseArray) { if (!first) { jsonOutput.append(","); } first = false; log.info("Processing document ID=" + document.getDocumentUniqueId().getLongName()); String mimeType = docResponseArray[0].getMimeType().getLongName(); if (mimeType.compareToIgnoreCase("text/xml") == 0) { final String filename = this.testOutputPath + "/" + document.getDocumentUniqueId().getLongName() + ".xml"; log.info("Persisting document to filesystem, filename=" + filename); DataHandler dh = document.getDocument(); File file = new File(filename); FileOutputStream fileOutStream = new FileOutputStream(file); dh.writeTo(fileOutStream); fileOutStream.close(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new FileInputStream(filename)); XPath xPath = XPathFactory.newInstance().newXPath(); //set namespace to xpath xPath.setNamespaceContext(new NamespaceContext() { private final String uri = "urn:hl7-org:v3"; private final String prefix = "hl7"; @Override public String getNamespaceURI(String prefix) { return this.prefix.equals(prefix) ? uri : null; } @Override public String getPrefix(String namespaceURI) { return this.uri.equals(namespaceURI) ? this.prefix : null; } @Override public Iterator getPrefixes(String namespaceURI) { return null; } }); NodeList nodes = (NodeList) xPath.evaluate( "/hl7:ClinicalDocument/hl7:templateId", doc.getDocumentElement(), XPathConstants.NODESET); boolean templateFound = false; if (nodes.getLength() > 0) { log.info("Searching for /ClinicalDocument/templateId, document ID=" + document.getDocumentUniqueId().getLongName()); for (int i = 0; i < nodes.getLength(); ++i) { String val = ((Element) nodes.item(i)).getAttribute("root"); if ((val != null) && (val.compareToIgnoreCase( "2.16.840.1.113883.10.20.22.1.2") == 0)) { log.info("/ClinicalDocument/templateId node found, document ID=" + document.getDocumentUniqueId().getLongName()); log.info("Invoking XSL transform, document ID=" + document.getDocumentUniqueId().getLongName()); DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document mappedDoc = builder.parse(new File(filename)); DOMSource source = new DOMSource(mappedDoc); TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory .newTransformer(new StreamSource( GetPatientDataService.cdaToJsonTransformXslt)); final String jsonFilename = this.testOutputPath + "/" + document.getDocumentUniqueId().getLongName() + ".json"; File jsonFile = new File(jsonFilename); FileOutputStream jsonFileOutStream = new FileOutputStream( jsonFile); StreamResult result = new StreamResult(jsonFileOutStream); transformer.transform(source, result); jsonFileOutStream.close(); log.info("Successfully transformed CCDA to JSON, filename=" + jsonFilename); jsonOutput.append(new String(readAllBytes(get(jsonFilename)))); templateFound = true; } } } if (!templateFound) { // Document doesn't match the template ID - add to error list... patientDataResponse.getErrorMsgs().add( "Document retrieved doesn't match required template ID - document ID=" + document.getDocumentUniqueId().getLongName()); } } else { patientDataResponse.getErrorMsgs() .add("Document retrieved is not XML - document ID=" + document.getDocumentUniqueId().getLongName()); } } } catch (Exception e) { log.error("Error encountered, " + e.getMessage()); throw e; } } } if (jsonOutput.length() > 0) { jsonOutput.append("]}"); } } } catch (Exception e) { log.error("Error encountered, " + e.getMessage()); throw new UnexpectedServerException("Error - " + e.getMessage()); } } else { // Return test document when testMode is true try { retVal = FileUtils.readFileToString(new File(GetPatientDataService.testJSONDocumentPathname)); return Response.status(Response.Status.OK).entity(retVal).type(MediaType.APPLICATION_JSON).build(); } catch (Exception e) { throw new UnexpectedServerException("Error - " + e.getMessage()); } } return Response.status(Response.Status.OK).entity(jsonOutput.toString()).type(MediaType.APPLICATION_JSON) .build(); }
From source file:org.iish.visualmets.services.TocDaoImp.java
private XPathExpression getXPathExpression(String xquery) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // http://www.ibm.com/developerworks/library/x-javaxpathapi.html NamespaceContext ns = new NamespaceContext() { @Override// w ww . j a va 2 s. co m public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException(); } @Override public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException(); } @Override public String getNamespaceURI(String prefix) { final String metsNs = "http://www.loc.gov/METS/"; if (prefix == null) throw new NullPointerException(metsNs); if (prefix.equalsIgnoreCase("mets")) return metsNs; if (prefix.equalsIgnoreCase("xml")) return XMLConstants.XML_NS_URI; return XMLConstants.NULL_NS_URI; } }; // if ( !namespaceName.equals("") ) { xpath.setNamespaceContext(ns); // } XPathExpression expr = xpath.compile(xquery); return expr; }
From source file:org.kalypsodeegree_impl.model.feature.gmlxpath.GMLXPathSegment.java
public static GMLXPathSegment forQName(final QName qname) { final String namespaceURI = qname.getNamespaceURI(); final String localPart = qname.getLocalPart(); if (XMLConstants.NULL_NS_URI.equals(namespaceURI)) return new GMLXPathSegment(localPart, null); final String defaultPrefix = "ns" + System.currentTimeMillis(); // Hopefully this works allways... final String prefix = NSUtilities.getNSProvider().getPreferredPrefix(namespaceURI, defaultPrefix); // Create a constant context final NamespaceContext namespaceContext = new NamespaceContext() { @Override//from w w w .j a v a 2 s . c om public String getNamespaceURI(final String pref) { return namespaceURI; } @Override public String getPrefix(final String namespace) { return prefix; } @Override public Iterator<String> getPrefixes(final String namespace) { throw new UnsupportedOperationException(); } }; final String segment = String.format("%s:%s", prefix, localPart); return new GMLXPathSegment(segment, namespaceContext); }
From source file:org.kie.workbench.common.dmn.backend.DMNMarshallerTest.java
@SafeVarargs private final XPath namespaceAwareXPath(Map.Entry<String, String>... pfxAndURI) { XPath result = XPathFactory.newInstance().newXPath(); result.setNamespaceContext(new NamespaceContext() { final Map<String, String> pfxToURI = new HashMap<String, String>() { {/* w ww.ja v a2s.c o m*/ for (Map.Entry<String, String> pair : pfxAndURI) { put(pair.getKey(), pair.getValue()); } } }; final Map<String, String> URItoPfx = new HashMap<String, String>() { { for (Map.Entry<String, String> pair : pfxAndURI) { put(pair.getValue(), pair.getKey()); } } }; @Override public String getNamespaceURI(String prefix) { return pfxToURI.get(prefix); } @Override public String getPrefix(String namespaceURI) { return URItoPfx.get(namespaceURI); } @Override public Iterator getPrefixes(String namespaceURI) { return pfxToURI.keySet().iterator(); } }); return result; }
From source file:org.mule.module.xml.filters.XPathFilter.java
@Override public void initialise() throws InitialisationException { super.initialise(); if (getXpath() == null) { setXpath(XPathFactory.newInstance().newXPath()); }/*from ww w. j a v a2s . com*/ if (pattern == null) { throw new InitialisationException(MessageFactory.createStaticMessage( "A pattern must be supplied to the " + ClassUtils.getSimpleName(getClass())), this); } if (muleContext != null) { try { namespaceManager = muleContext.getRegistry().lookupObject(NamespaceManager.class); } catch (RegistrationException e) { throw new ExpressionRuntimeException(CoreMessages.failedToLoad("NamespaceManager"), e); } if (namespaceManager != null) { if (prefixToNamespaceMap == null) { prefixToNamespaceMap = new HashMap<String, String>(namespaceManager.getNamespaces()); } else { prefixToNamespaceMap.putAll(namespaceManager.getNamespaces()); } } } final Map<String, String> prefixToNamespaceMap = this.prefixToNamespaceMap; if (prefixToNamespaceMap != null) { getXpath().setNamespaceContext(new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { return prefixToNamespaceMap.get(prefix); } @Override public String getPrefix(String namespaceURI) { for (Map.Entry<String, String> entry : prefixToNamespaceMap.entrySet()) { if (namespaceURI.equals(entry.getValue())) { return entry.getKey(); } } return null; } @Override public Iterator<String> getPrefixes(String namespaceURI) { String prefix = getPrefix(namespaceURI); if (prefix == null) { return Collections.<String>emptyList().iterator(); } else { return Arrays.asList(prefix).iterator(); } } }); } if (logger.isInfoEnabled()) { logger.info("XPath implementation: " + getXpath()); logger.info("DocumentBuilderFactory implementation: " + getDocumentBuilderFactory()); } }
From source file:org.openhab.binding.ihc.ws.IhcResourceInteractionService.java
private NodeList parseList(String xml, String xpathExpression) throws XPathExpressionException, UnsupportedEncodingException { InputStream is = new ByteArrayInputStream(xml.getBytes("UTF8")); XPath xpath = XPathFactory.newInstance().newXPath(); InputSource inputSource = new InputSource(is); xpath.setNamespaceContext(new NamespaceContext() { public String getNamespaceURI(String prefix) { if (prefix == null) throw new NullPointerException("Null prefix"); else if ("SOAP-ENV".equals(prefix)) return "http://schemas.xmlsoap.org/soap/envelope/"; else if ("ns1".equals(prefix)) return "utcs"; else if ("ns2".equals(prefix)) return "utcs.values"; return null; }//from w ww. ja v a 2s .c o m public String getPrefix(String uri) { return null; } @SuppressWarnings("rawtypes") public Iterator getPrefixes(String uri) { throw new UnsupportedOperationException(); } }); return (NodeList) xpath.evaluate(xpathExpression, inputSource, XPathConstants.NODESET); }