List of usage examples for javax.xml.namespace QName QName
public QName(final String namespaceURI, final String localPart)
QName
constructor specifying the Namespace URI and local part.
If the Namespace URI is null
, it is set to javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI .
From source file:com.googlecode.ddom.frontend.saaj.SOAPElementTest.java
@Validated @Test//w w w .j ava 2 s . co m public void testAddAttributeFromNameWithoutNamespace() throws Exception { SOAPEnvelope envelope = saajUtil.createSOAP11Envelope(); SOAPBody body = envelope.addBody(); SOAPElement element = body.addChildElement(new QName("urn:test", "test")); SOAPElement retValue = element.addAttribute(envelope.createName("attr"), "value"); assertSame(element, retValue); Attr attr = element.getAttributeNodeNS(null, "attr"); assertNull(attr.getNamespaceURI()); String localName = attr.getLocalName(); if (localName != null) { assertEquals("attr", attr.getLocalName()); } assertNull(attr.getPrefix()); assertEquals("value", attr.getValue()); }
From source file:eu.planets_project.pp.plato.services.action.planets.PlanetsMigrationService.java
private QName determineServiceQNameFromWsdl(URL wsdlLocation) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Using factory get an instance of document builder DocumentBuilder db;//from ww w . jav a 2 s. c om try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } // parse using builder to get DOM representation of the XML file Document dom; try { dom = db.parse(wsdlLocation.openStream()); } catch (Exception e) { e.printStackTrace(); return null; } // get the root elememt Element root = dom.getDocumentElement(); return new QName(root.getAttribute("targetNamespace"), root.getAttribute("name")); }
From source file:nz.co.senanque.sandbox.ObjectTest.java
@Test public void test1() throws Exception { @SuppressWarnings("unused") Object en = IndustryType.fromValue("Ag"); ValidationSession validationSession = m_validationEngine.createSession(); // create a customer Customer customer = m_customerDAO.createCustomer(); validationSession.bind(customer);/*from www .ja va 2s. co m*/ Invoice invoice = new Invoice(); invoice.setDescription("test invoice"); invoice.setTestBoolean(true); customer.getInvoices().add(invoice); boolean exceptionFound = false; try { customer.setName("ttt"); } catch (ValidationException e) { exceptionFound = true; } assertTrue(exceptionFound); final ObjectMetadata customerMetadata = validationSession.getMetadata(customer); @SuppressWarnings("unused") final FieldMetadata customerTypeMetadata = customerMetadata.getFieldMetadata(Customer.CUSTOMERTYPE); // assertFalse(customerTypeMetadata.isActive()); // assertFalse(customerTypeMetadata.isReadOnly()); // assertFalse(customerTypeMetadata.isRequired()); customer.setName("aaaab"); exceptionFound = false; try { customer.setCustomerType("B"); } catch (Exception e) { exceptionFound = true; } // assertTrue(exceptionFound); exceptionFound = false; try { customer.setCustomerType("XXX"); } catch (Exception e) { exceptionFound = true; } assertTrue(exceptionFound); customer.setBusiness(IndustryType.AG); customer.setAmount(new Double(500.99)); final long id = m_customerDAO.save(customer); log.info("{}", id); // fetch customer back customer = m_customerDAO.getCustomer(id); @SuppressWarnings("unused") final int invoiceCount = customer.getInvoices().size(); validationSession.bind(customer); invoice = new Invoice(); ValidationUtils.setDefaults(invoice); invoice.setDescription("test invoice2"); invoice.setTestBoolean(true); customer.getInvoices().add(invoice); assertEquals("xyz", invoice.getTestDefault()); assertEquals("Ag", invoice.getTestEnumDefault().value()); m_customerDAO.save(customer); // fetch customer again customer = m_customerDAO.getCustomer(id); customer.toString(); final Invoice inv0 = customer.getInvoices().get(0); assertTrue(inv0.isTestBoolean()); validationSession.bind(customer); final Invoice inv = customer.getInvoices().get(0); assertTrue(inv.isTestBoolean()); customer.getInvoices().remove(inv); //ObjectMetadata metadata = validationSession.getMetadata(customer); ObjectMetadata metadata = customer.getMetadata(); assertEquals("this is a description", metadata.getFieldMetadata(Customer.NAME).getDescription()); assertEquals("ABC", metadata.getFieldMetadata(Customer.NAME).getPermission()); @SuppressWarnings("unused") List<ChoiceBase> choices = metadata.getFieldMetadata(Customer.BUSINESS).getChoiceList(); // assertEquals(1,choices.size()); List<ChoiceBase> choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList(); // assertEquals(1,choices2.size()); choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList(); // assertEquals(1,choices2.size()); for (ChoiceBase choice : choices2) { System.out.println(choice.getDescription()); } customer.setName("aab"); choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList(); // assertEquals(6,choices2.size()); // Convert customer to XML QName qname = new QName("http://www.example.org/sandbox", "Session"); JAXBElement<Session> sessionJAXB = new JAXBElement<Session>(qname, Session.class, new Session()); sessionJAXB.getValue().getCustomers().add(customer); //??This fails to actually add StringWriter marshallWriter = new StringWriter(); Result marshallResult = new StreamResult(marshallWriter); m_marshaller.marshal(sessionJAXB, marshallResult); marshallWriter.flush(); String result = marshallWriter.getBuffer().toString().trim(); String xml = result.replaceAll("\\Qhttp://www.example.org/sandbox\\E", "http://www.example.org/sandbox"); log.info("{}", xml); // Convert customer back to objects SAXBuilder builder = new SAXBuilder(); org.jdom.Document resultDOM = builder.build(new StringReader(xml)); @SuppressWarnings("unchecked") JAXBElement<Session> request = (JAXBElement<Session>) m_unmarshaller.unmarshal(new JDOMSource(resultDOM)); validationSession = m_validationEngine.createSession(); validationSession.bind(request.getValue()); assertEquals(3, validationSession.getProxyCount()); List<Customer> customers = request.getValue().getCustomers(); assertEquals(1, customers.size()); assertTrue(customers.get(0).getInvoices().get(0).isTestBoolean()); customers.clear(); assertEquals(1, validationSession.getProxyCount()); request.toString(); validationSession.close(); }
From source file:com._4dconcept.springframework.data.marklogic.repository.query.PartTreeMarklogicQueryTest.java
@Test public void booleanFieldShouldBeConsideredTrue() { Query query = deriveQueryFromMethod("findByActiveIsTrue"); assertCriteria(query.getCriteria(), is(new QName("http://spring.data.marklogic/test/contact", "active")), is(true));// w ww . j a v a2 s . c o m }
From source file:XMLUtils.java
public static QName getNamespace(Map<String, String> namespaces, String str, String defaultNamespace) { String prefix = null;//from w w w. j a v a2s . c om String localName = null; StringTokenizer tokenizer = new StringTokenizer(str, ":"); if (tokenizer.countTokens() == 2) { prefix = tokenizer.nextToken(); localName = tokenizer.nextToken(); } else if (tokenizer.countTokens() == 1) { localName = tokenizer.nextToken(); } String namespceURI = defaultNamespace; if (prefix != null) { namespceURI = (String) namespaces.get(prefix); } return new QName(namespceURI, localName); }
From source file:com.baidu.api.client.core.VersionService.java
/** * Change the user in header into another one. * * @param authHeader// www. j a va 2 s . c om * @param service The client side service sub. */ public void updateHeader(AuthHeader authHeader, Object service) { try { Header header = new Header(new QName(currentVersion.getHeaderNameSpace(), "AuthHeader"), authHeader, new JAXBDataBinding(AuthHeader.class)); List<Header> tmpHeaders = new ArrayList<Header>(); tmpHeaders.add(header); if (service instanceof BindingProvider) { Map<String, Object> reqCtxt = ((BindingProvider) service).getRequestContext(); reqCtxt.put(Header.HEADER_LIST, tmpHeaders); log.info("Current user changed to: " + authHeader.getUsername()); } else { throw new IllegalArgumentException("service instance is not correct!"); } } catch (JAXBException e) { log.fatal("Failed to genarate AuthHeader!", e); throw new ClientInternalException("Failed to update AuthHeader!"); } }
From source file:net.di2e.ecdr.search.transform.atom.response.AtomResponseTransformer.java
private Metacard entryToMetacard(Entry entry, String siteName) { CDRMetacard metacard = new CDRMetacard(CDRMetacardType.CDR_METACARD); String id = entry.getIdElement().getText(); // id may be formatted catalog:id:<id>, so we parse out the <id> if (StringUtils.isNotBlank(id) && (id.startsWith("urn:uuid:") || id.startsWith("urn:catalog:id:"))) { id = id.substring(id.lastIndexOf(':') + 1); }//from w w w.ja v a2 s . c o m metacard.setId(id); metacard.setSourceId(siteName); List<Category> categories = entry.getCategories(); if (categories != null && !categories.isEmpty()) { Category category = categories.get(0); metacard.setContentTypeName(category.getTerm()); IRI scheme = category.getScheme(); if (scheme != null) { metacard.setContentTypeVersion(scheme.toString()); } } try { metacard.setModifiedDate(entry.getUpdated()); } catch (IllegalArgumentException e) { LOGGER.warn("InvalidDate found in atom reponse, setting Metacard modified time to now "); metacard.setEffectiveDate(new Date()); } try { metacard.setEffectiveDate(entry.getPublished()); } catch (IllegalArgumentException e) { LOGGER.warn("InvalidDate found in atom reponse, setting Metacard Effective time to now "); metacard.setEffectiveDate(new Date()); } String createdDate = entry.getSimpleExtension(new QName(AtomResponseConstants.METACARD_ATOM_NAMESPACE, AtomResponseConstants.METACARD_CREATED_DATE_ELEMENT)); if (createdDate != null) { metacard.setCreatedDate(new Date(DATE_FORMATTER.parseMillis(createdDate))); } String expirationDate = entry.getSimpleExtension(new QName(AtomResponseConstants.METACARD_ATOM_NAMESPACE, AtomResponseConstants.METADATA_EXPIRATION_DATE_ELEMENT)); if (expirationDate != null) { metacard.setExpirationDate(new Date(DATE_FORMATTER.parseMillis(expirationDate))); } AtomContentXmlWrapOption wrap = filterConfig.getAtomContentXmlWrapOption(); String metadata = entry.getContent(); populateMetadata(entry, metacard, wrap, metadata); metacard.setLocation(getWKT(entry)); Link productLink = entry.getLink(filterConfig.getProductLinkRelation()); if (productLink != null) { metacard.setResourceURI(URI.create(productLink.getHref().toASCIIString())); long resourceSize = productLink.getLength(); if (resourceSize > 0) { metacard.setResourceSize(String.valueOf(resourceSize)); } String productTitle = productLink.getTitle(); if (productTitle != null) { metacard.setAttribute(CDRMetacard.RESOURCE_TITLE, productTitle); } // ECDR-41 figure out MIMEType MimeType productType = productLink.getMimeType(); if (productType != null) { metacard.setAttribute(CDRMetacard.RESOURCE_MIME_TYPE, productType.toString()); } } String thumbnailLinkRel = filterConfig.getThumbnailLinkRelation(); if (thumbnailLinkRel != null) { List<Link> links = entry.getLinks(thumbnailLinkRel); if (links != null && !links.isEmpty()) { for (Link link : links) { MimeType mimeType = link.getMimeType(); if (mimeType == null || "image".equals(mimeType.getPrimaryType())) { metacard.setThumbnailLinkURI(URI.create(link.getHref().toASCIIString())); long thumbnailSize = link.getLength(); if (thumbnailSize > 0) { metacard.setAttribute(CDRMetacard.THUMBNAIL_LENGTH, Long.valueOf(thumbnailSize)); } // ECDR-41 figure out MIMEType metacard.setAttribute(CDRMetacard.THUMBNAIL_MIMETYPE, link.getMimeType()); metacard.setAttribute(CDRMetacard.THUMBNAIL_LINK_TITLE, link.getTitle()); break; } } } } metacard.setTitle(entry.getTitle()); boolean isMetadataSet = false; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(AtomResponseTransformer.class.getClassLoader()); List<Element> extensions = entry.getExtensions(); for (Element element : extensions) { if (METADATA_ELEMENT_NAME.equalsIgnoreCase(element.getQName().getLocalPart())) { StringWriter writer = new StringWriter(); try { element.writeTo(writer); metacard.setMetadata(writer.toString()); isMetadataSet = true; break; } catch (IOException e) { LOGGER.error( "Could not convert Metadata String value from Atom to Metacard.METADATA attribute", e); } } } } finally { Thread.currentThread().setContextClassLoader(tccl); } if (!isMetadataSet) { String metadataLinkRel = filterConfig.getMetadataLinkRelation(); if (metadataLinkRel != null) { List<Link> metadataLinks = entry.getLinks(metadataLinkRel); String metadataLink = null; for (Link link : metadataLinks) { MimeType mimeType = link.getMimeType(); if (mimeType != null) { if (mimeType.getSubType().contains("xml")) { metadataLink = link.getHref().toASCIIString(); metacard.setMetadataLinkURI(URI.create(metadataLink)); metacard.setAttribute(CDRMetacard.WRAP_METADATA, null); break; } else if (mimeType.getBaseType().contains("text")) { metadataLink = link.getHref().toASCIIString(); metacard.setMetadataLinkURI(URI.create(metadataLink)); metacard.setAttribute(CDRMetacard.WRAP_METADATA, Boolean.TRUE); } } } } } Metacard returnMetacard = SecurityMarkingParser.addSecurityToMetacard(metacard, entry); return new CDRMetacard(returnMetacard); }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.AttachmentUtils.java
public static boolean isSwaRefType(SchemaType schemaType) { return schemaType.getName() != null && schemaType.getName().equals(new QName("http://ws-i.org/profiles/basic/1.1/xsd", "swaRef")); }
From source file:com.evolveum.midpoint.prism.marshaller.XPathHolder.java
/** * Parses XPath-like expression (midPoint flavour), with regards to domNode from where the namespace declarations * (embedded in XML using xmlns attributes) are taken. * * @param xpath text representation of the XPath-like expression * @param domNode context (DOM node from which the expression was taken) * @param namespaceMap externally specified namespaces *//*from www . j a va 2s. co m*/ private void parse(String xpath, Node domNode, Map<String, String> namespaceMap) { segments = new ArrayList<>(); absolute = false; if (".".equals(xpath)) { return; } // Check for explicit namespace declarations. TrivialXPathParser parser = TrivialXPathParser.parse(xpath); explicitNamespaceDeclarations = parser.getNamespaceMap(); // Continue parsing with Xpath without the "preamble" xpath = parser.getPureXPathString(); String[] segArray = xpath.split("/"); for (int i = 0; i < segArray.length; i++) { if (segArray[i] == null || segArray[i].isEmpty()) { if (i == 0) { absolute = true; // ignore the first empty segment of absolute path continue; } else { throw new IllegalArgumentException( "XPath " + xpath + " has an empty segment (number " + i + ")"); } } String segmentStr = segArray[i]; XPathSegment idValueFilterSegment; // is ID value filter attached to this segment? int idValuePosition = segmentStr.indexOf('['); if (idValuePosition >= 0) { if (!segmentStr.endsWith("]")) { throw new IllegalArgumentException( "XPath " + xpath + " has a ID segment not ending with ']': '" + segmentStr + "'"); } String value = segmentStr.substring(idValuePosition + 1, segmentStr.length() - 1); segmentStr = segmentStr.substring(0, idValuePosition); idValueFilterSegment = new XPathSegment(value); } else { idValueFilterSegment = null; } // processing the rest (i.e. the first part) of the segment boolean variable = false; if (segmentStr.startsWith("$")) { // We have variable here variable = true; segmentStr = segmentStr.substring(1); } String[] qnameArray = segmentStr.split(":"); if (qnameArray.length > 2) { throw new IllegalArgumentException( "Unsupported format: more than one colon in XPath segment: " + segArray[i]); } QName qname; if (qnameArray.length == 1 || qnameArray[1] == null || qnameArray[1].isEmpty()) { if (ParentPathSegment.SYMBOL.equals(qnameArray[0])) { qname = ParentPathSegment.QNAME; } else if (ObjectReferencePathSegment.SYMBOL.equals(qnameArray[0])) { qname = ObjectReferencePathSegment.QNAME; } else if (IdentifierPathSegment.SYMBOL.equals(qnameArray[0])) { qname = IdentifierPathSegment.QNAME; } else { // default namespace <= empty prefix String namespace = findNamespace(null, domNode, namespaceMap); qname = new QName(namespace, qnameArray[0]); } } else { String namespacePrefix = qnameArray[0]; String namespace = findNamespace(namespacePrefix, domNode, namespaceMap); if (namespace == null) { QNameUtil.reportUndeclaredNamespacePrefix(namespacePrefix, xpath); namespacePrefix = QNameUtil.markPrefixAsUndeclared(namespacePrefix); } qname = new QName(namespace, qnameArray[1], namespacePrefix); } segments.add(new XPathSegment(qname, variable)); if (idValueFilterSegment != null) { segments.add(idValueFilterSegment); } } }
From source file:org.apache.cxf.cwiki.SiteExporter.java
public static synchronized Dispatch<Document> getDispatch() { if (dispatch == null) { Service service = Service.create(new QName(SOAPNS, "Service")); service.addPort(new QName(SOAPNS, "Port"), SOAPBinding.SOAP11HTTP_BINDING, ROOT + RPC_ROOT + apiVersion); dispatch = service.createDispatch(new QName(SOAPNS, "Port"), Document.class, Service.Mode.PAYLOAD); if (debug) { ((org.apache.cxf.jaxws.DispatchImpl<?>) dispatch).getClient().getEndpoint().getInInterceptors() .add(new LoggingInInterceptor()); ((org.apache.cxf.jaxws.DispatchImpl<?>) dispatch).getClient().getEndpoint().getOutInterceptors() .add(new LoggingOutInterceptor()); }/*from w w w .j a v a 2s . c o m*/ HTTPConduit c = (HTTPConduit) ((org.apache.cxf.jaxws.DispatchImpl<?>) dispatch).getClient() .getConduit(); HTTPClientPolicy clientPol = c.getClient(); if (clientPol == null) { clientPol = new HTTPClientPolicy(); } //CAMEL has a couple of HUGE HUGE pages that take a long time to render clientPol.setReceiveTimeout(5 * 60 * 1000); c.setClient(clientPol); } return dispatch; }