List of usage examples for org.w3c.dom Element getTextContent
public String getTextContent() throws DOMException;
From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java
private void setMultiplicity(ItemDefinition itemDef, XSParticle particle, XSAnnotation annotation, boolean topLevel) { if (topLevel || particle == null) { itemDef.setMinOccurs(0);/*from w w w . j a v a 2 s . c om*/ Element maxOccursAnnotation = SchemaProcessorUtil.getAnnotationElement(annotation, A_MAX_OCCURS); if (maxOccursAnnotation != null) { String maxOccursString = maxOccursAnnotation.getTextContent(); int maxOccurs = XsdTypeMapper.multiplicityToInteger(maxOccursString); itemDef.setMaxOccurs(maxOccurs); } else { itemDef.setMaxOccurs(-1); } } else { //itemDef.setMinOccurs(particle.getMinOccurs()); //itemDef.setMaxOccurs(particle.getMaxOccurs()); itemDef.setMinOccurs(particle.getMinOccurs().intValue()); itemDef.setMaxOccurs(particle.getMaxOccurs().intValue()); } }
From source file:com.microsoft.windowsazure.management.servicebus.ServiceBusManagementClientImpl.java
/** * Retrieves the list of regions that support the creation and management of * Service Bus service namespaces. (see// w w w . ja v a 2 s .c om * http://msdn.microsoft.com/en-us/library/windowsazure/jj860465.aspx for * more information) * * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return A response to a request for a list of regions. */ @Override public ServiceBusRegionsResponse getServiceBusRegions() throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); CloudTracing.enter(invocationId, this, "getServiceBusRegionsAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/servicebus/regions"; String baseUrl = this.getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("Accept", "application/atom+xml"); httpRequest.setHeader("Content-Type", "application/atom+xml"); httpRequest.setHeader("x-ms-version", "2013-08-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ServiceBusRegionsResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServiceBusRegionsResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element feedElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom", "feed"); if (feedElement != null) { if (feedElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(feedElement, "http://www.w3.org/2005/Atom", "entry") .size(); i1 = i1 + 1) { org.w3c.dom.Element entriesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(feedElement, "http://www.w3.org/2005/Atom", "entry") .get(i1)); ServiceBusLocation entryInstance = new ServiceBusLocation(); result.getRegions().add(entryInstance); Element contentElement = XmlUtility.getElementByTagNameNS(entriesElement, "http://www.w3.org/2005/Atom", "content"); if (contentElement != null) { Element regionCodeDescriptionElement = XmlUtility.getElementByTagNameNS( contentElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RegionCodeDescription"); if (regionCodeDescriptionElement != null) { Element codeElement = XmlUtility.getElementByTagNameNS( regionCodeDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Code"); if (codeElement != null) { String codeInstance; codeInstance = codeElement.getTextContent(); entryInstance.setCode(codeInstance); } Element fullNameElement = XmlUtility.getElementByTagNameNS( regionCodeDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "FullName"); if (fullNameElement != null) { String fullNameInstance; fullNameInstance = fullNameElement.getTextContent(); entryInstance.setFullName(fullNameInstance); } } } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:betullam.xmlmodifier.XMLmodifier.java
private boolean hasDuplicate(Element parentElement, String elementName, String attrName, String attrValue, String textContent) {/*from www. j a va 2 s . c o m*/ boolean hasDuplicate = false; NodeList childNodes = parentElement.getChildNodes(); if (childNodes.getLength() > 0) { for (int i = 0; i < childNodes.getLength(); i++) { if (childNodes.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element childElement = (Element) childNodes.item(i); // Get name of child element: String childElementName = childElement.getTagName(); // Check if the element with the given element name exists if (childElementName.equals(elementName)) { boolean elementExists = true; if (elementExists) { // The given element exists // Check if given text content exists String childElementTextContent = childElement.getTextContent().trim(); boolean textContentExists = (childElementTextContent.equals(textContent)) ? true : false; // If attribute value and name are null, we don't check for them (in this case, only the text content is relevant). if (attrName.equals("null") && attrValue.equals("null")) { if (textContentExists) { // Element exists with the given text content. hasDuplicate = true; // The new element would be a duplicate } else { // Element exists but not with the given text content. hasDuplicate = false; // The new element wouldn't be a duplicate } } else { // If attribute value and name are not null, check if they are the same as the given value. // Check if child element has the given attribute boolean elementHasAttr = childElement.hasAttribute(attrName); if (elementHasAttr) { // The given element has the given attribute // Check if the attribute has the given value String childElementAttrValue = childElement.getAttribute(attrName); if (childElementAttrValue.equals(attrValue)) { if (textContentExists) { // Element exists with the given text content. hasDuplicate = true; // The attribute contains the given attribute value, so the new element would be a duplicate. } else { // Element exists but not with the given text content. hasDuplicate = false; // The new element wouldn't be a duplicate } } else { hasDuplicate = false; // The attribute does not contain the given attribute value, so the new element would not be a duplicate. } } else { hasDuplicate = false; // The attribute does not exist, so the new element would not be a duplicate. } } } } } } } return hasDuplicate; }
From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java
private void parseItemDefinitionAnnotations(ItemDefinition itemDef, XSAnnotation annotation) throws SchemaException { if (annotation == null || annotation.getAnnotation() == null) { return;/*from w w w .j a v a 2s . com*/ } QName elementName = itemDef.getName(); // ignore Boolean ignore = SchemaProcessorUtil.getAnnotationBooleanMarker(annotation, A_IGNORE); if (ignore != null) { itemDef.setIgnored(ignore); } // deprecated Boolean deprecated = SchemaProcessorUtil.getAnnotationBooleanMarker(annotation, A_DEPRECATED); if (deprecated != null) { itemDef.setDeprecated(deprecated); } // operational Boolean operational = SchemaProcessorUtil.getAnnotationBooleanMarker(annotation, A_OPERATIONAL); if (operational != null) { itemDef.setOperational(operational); } // displayName Element attributeDisplayName = SchemaProcessorUtil.getAnnotationElement(annotation, A_DISPLAY_NAME); if (attributeDisplayName != null) { itemDef.setDisplayName(attributeDisplayName.getTextContent()); } // displayOrder Element displayOrderElement = SchemaProcessorUtil.getAnnotationElement(annotation, A_DISPLAY_ORDER); if (displayOrderElement != null) { Integer displayOrder = DOMUtil.getIntegerValue(displayOrderElement); itemDef.setDisplayOrder(displayOrder); } // help Element help = SchemaProcessorUtil.getAnnotationElement(annotation, A_HELP); if (help != null) { itemDef.setHelp(help.getTextContent()); } // documentation extractDocumentation(itemDef, annotation); }
From source file:com.bluexml.xforms.controller.navigation.NavigationManager.java
/** * Removes a specific submit button from the group of submit buttons. * //ww w . j a va 2 s. c o m * @param docElt * @param buttonId */ private void removeSubmitButton(Element docElt, MsgId buttonId) { String realCaption = MsgPool.getMsg(buttonId); Element button = null; // find the group of submits String groupId = MsgId.INT_SUBMIT_BUTTONS_GROUP_ID.getText(); Element submitGroup = DOMUtil.getEltInDescentByAttrValue(docElt, "id", groupId); // find the "xf:submit" node that has the right caption in its // "xf:label" List<Element> listOfSubmits = DOMUtil.getAllChildren(submitGroup); for (Element aSubmit : listOfSubmits) { if (StringUtils.equals(aSubmit.getTagName(), "xf:submit")) { Element label = DOMUtil.getChild(aSubmit, "xf:label"); if (StringUtils.equals(label.getTextContent(), realCaption)) { button = aSubmit; break; } } } if (button != null) { submitGroup.removeChild(button); } }
From source file:com.moviejukebox.reader.MovieJukeboxXMLReader.java
/** * Parse the set XML file for movies/*from ww w .j av a 2 s . c o m*/ * * @param xmlSetFile * @param setMaster * @param moviesList * @return */ public boolean parseSetXML(File xmlSetFile, Movie setMaster, List<Movie> moviesList) { boolean forceDirtyFlag = Boolean.FALSE; Document xmlDoc; try { xmlDoc = DOMHelper.getDocFromFile(xmlSetFile); } catch (MalformedURLException error) { LOG.error(ERROR_FIXIT, xmlSetFile.getName(), "movie"); LOG.error(SystemTools.getStackTrace(error)); return Boolean.FALSE; } catch (IOException error) { LOG.error(ERROR_FIXIT, xmlSetFile.getName(), "movie"); LOG.error(SystemTools.getStackTrace(error)); return Boolean.FALSE; } catch (ParserConfigurationException | SAXException error) { LOG.error(ERROR_FIXIT, xmlSetFile.getName(), "movie"); LOG.error(SystemTools.getStackTrace(error)); return Boolean.FALSE; } Node nFilename; NodeList nlFilenames = xmlDoc.getElementsByTagName("baseFilename"); Collection<String> xmlSetMovieNames = new ArrayList<>(); for (int loopMovie = 0; loopMovie < nlFilenames.getLength(); loopMovie++) { nFilename = nlFilenames.item(loopMovie); if (nFilename.getNodeType() == Node.ELEMENT_NODE) { Element eFilename = (Element) nFilename; xmlSetMovieNames.add(eFilename.getTextContent()); } } int counter = setMaster.getSetSize(); if (counter == xmlSetMovieNames.size()) { for (String movieName : xmlSetMovieNames) { for (Movie movie : moviesList) { if (movie.getBaseName().equals(movieName)) { // See if the movie is in a collection OR isDirty forceDirtyFlag |= (!movie.isTVShow() && !movie.getSetsKeys().contains(setMaster.getTitle())) || movie.isDirty(DirtyFlag.INFO); counter--; break; } } // Stop if the Set is dirty, no need to check more if (forceDirtyFlag) { break; } } forceDirtyFlag |= counter != 0; } else { forceDirtyFlag = Boolean.TRUE; } setMaster.setDirty(DirtyFlag.INFO, forceDirtyFlag); return Boolean.TRUE; }
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 w w. j a v a 2 s. com } } 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:com.evolveum.midpoint.prism.schema.DomToSchemaPostProcessor.java
/** * Creates appropriate instance of PropertyDefinition. It creates either * PropertyDefinition itself or one of its subclasses * (ResourceObjectAttributeDefinition). The behavior depends of the "mode" * of the schema. This method is also processing annotations and other fancy * property-relates stuff./*from w w w .j av a 2 s .co m*/ */ private <T> PrismPropertyDefinitionImpl<T> createPropertyDefinition(XSType xsType, QName elementName, QName typeName, ComplexTypeDefinition ctd, XSAnnotation annotation, XSParticle elementParticle) throws SchemaException { PrismPropertyDefinitionImpl<T> propDef; SchemaDefinitionFactory definitionFactory = getDefinitionFactory(); Collection<? extends DisplayableValue<T>> allowedValues = parseEnumAllowedValues(typeName, ctd, xsType); Object defaultValue = parseDefaultValue(elementParticle, typeName); propDef = (PrismPropertyDefinitionImpl) definitionFactory.createPropertyDefinition(elementName, typeName, ctd, prismContext, annotation, elementParticle, allowedValues, null); setMultiplicity(propDef, elementParticle, annotation, ctd == null); // Process generic annotations parseItemDefinitionAnnotations(propDef, annotation); List<Element> accessElements = SchemaProcessorUtil.getAnnotationElements(annotation, A_ACCESS); if (accessElements.isEmpty()) { // Default access is read-write-create propDef.setCanAdd(true); propDef.setCanModify(true); propDef.setCanRead(true); } else { propDef.setCanAdd(false); propDef.setCanModify(false); propDef.setCanRead(false); for (Element e : accessElements) { String access = e.getTextContent(); if (access.equals(A_ACCESS_CREATE)) { propDef.setCanAdd(true); } if (access.equals(A_ACCESS_UPDATE)) { propDef.setCanModify(true); } if (access.equals(A_ACCESS_READ)) { propDef.setCanRead(true); } } } markRuntime(propDef); Element indexableElement = SchemaProcessorUtil.getAnnotationElement(annotation, A_INDEXED); if (indexableElement != null) { Boolean indexable = XmlTypeConverter.toJavaValue(indexableElement, Boolean.class); propDef.setIndexed(indexable); } Element matchingRuleElement = SchemaProcessorUtil.getAnnotationElement(annotation, A_MATCHING_RULE); if (matchingRuleElement != null) { QName matchingRule = XmlTypeConverter.toJavaValue(matchingRuleElement, QName.class); propDef.setMatchingRuleQName(matchingRule); } Element valueEnumerationRefElement = SchemaProcessorUtil.getAnnotationElement(annotation, A_VALUE_ENUMERATION_REF); if (valueEnumerationRefElement != null) { String oid = valueEnumerationRefElement.getAttribute(PrismConstants.ATTRIBUTE_OID_LOCAL_NAME); if (oid != null) { QName targetType = DOMUtil.getQNameAttribute(valueEnumerationRefElement, PrismConstants.ATTRIBUTE_REF_TYPE_LOCAL_NAME); PrismReferenceValue valueEnumerationRef = new PrismReferenceValue(oid, targetType); propDef.setValueEnumerationRef(valueEnumerationRef); } } return propDef; }
From source file:org.apache.servicemix.http.ConsumerEndpointTest.java
public void testHttpSoap12FaultOnEnvelope() throws Exception { initSoapEndpoints(true);//from w w w . j a va2 s .c om PostMethod post = new PostMethod("http://localhost:8192/ep2/"); post.setRequestEntity(new StringRequestEntity("<hello>world</hello>")); new HttpClient().executeMethod(post); String res = post.getResponseBodyAsString(); log.info(res); Element elem = transformer.toDOMElement(new StringSource(res)); assertEquals(Soap12.getInstance().getEnvelope(), DomUtil.getQName(elem)); elem = DomUtil.getFirstChildElement(elem); assertEquals(Soap12.getInstance().getBody(), DomUtil.getQName(elem)); elem = DomUtil.getFirstChildElement(elem); assertEquals(Soap12.getInstance().getFault(), DomUtil.getQName(elem)); elem = DomUtil.getFirstChildElement(elem); assertEquals(SoapConstants.SOAP_12_FAULTCODE, DomUtil.getQName(elem)); elem = DomUtil.getFirstChildElement(elem); assertEquals(SoapConstants.SOAP_12_FAULTVALUE, DomUtil.getQName(elem)); assertEquals(SoapConstants.SOAP_12_CODE_SENDER, DomUtil.createQName(elem, elem.getTextContent())); elem = DomUtil.getNextSiblingElement(elem); assertEquals(SoapConstants.SOAP_12_FAULTSUBCODE, DomUtil.getQName(elem)); assertEquals(SoapConstants.SOAP_12_CODE_VERSIONMISMATCH, DomUtil.createQName(elem, elem.getTextContent())); assertEquals(500, post.getStatusCode()); }
From source file:com.googlecode.jdeltasync.DeltaSyncClient.java
private void downloadMessageContent(final IDeltaSyncSession session, final String messageId, final OutputStream output, final boolean raw) throws DeltaSyncException, IOException { String request = "<ItemOperations xmlns=\"ItemOperations:\" xmlns:A=\"HMMAIL:\">" + "<Fetch>" + "<Class>Email</Class>" + "<A:ServerId>" + messageId + "</A:ServerId>" + "<A:Compression>hm-compression</A:Compression>" + "<A:ResponseContentType>mtom</A:ResponseContentType>" + "</Fetch>" + "</ItemOperations>"; Document response = itemOperations(session, request, new UriCapturingResponseHandler<Document>() { public Document handle(URI uri, HttpResponse response) throws DeltaSyncException, IOException { session.setBaseUri(uri.getScheme() + "://" + uri.getHost()); Header contentType = response.getFirstHeader("Content-Type"); if (contentType == null || !contentType.getValue().equals("application/xop+xml")) { if (contentType != null && contentType.getValue().equals("text/xml")) { // If we receive a text/xml response it means an error has occurred return XmlUtil.parse(response.getEntity().getContent()); }//from w w w. j a v a 2 s . c o m throw new DeltaSyncException("Unexpected Content-Type received: " + contentType); } final Object[] result = new Object[1]; MimeStreamParser parser = new MimeStreamParser(); parser.setContentHandler(new SimpleContentHandler() { @Override public void headers(org.apache.james.mime4j.message.Header header) { } @Override public void bodyDecoded(BodyDescriptor bd, InputStream is) throws IOException { if ("application/xop+xml".equals(bd.getMimeType())) { try { result[0] = XmlUtil.parse(is); } catch (XmlException e) { result[0] = e; } } else if ("application/octet-stream".equals(bd.getMimeType())) { OutputStream out = output; if (!raw) { out = new HU01DecompressorOutputStream(output); } byte[] buffer = new byte[4096]; int n; while ((n = is.read(buffer)) != -1) { out.write(buffer, 0, n); } out.flush(); } } }); try { parser.parse(response.getEntity().getContent()); } catch (MimeException e) { throw new DeltaSyncException("Failed to parse multipart xop+xml response", e); } catch (IOException e) { if (e.getCause() != null && (e.getCause() instanceof HU01Exception)) { session.getLogger().error("HU01 decompression failed: ", e.getCause()); session.getLogger().error("Dumping HU01 stream as BASE64 for message {}", messageId); session.getLogger().error("Please submit the BASE64 encoded message content"); session.getLogger().error("and the plain text message content to the JDeltaSync"); session.getLogger().error("issue tracker. The plain text message content can"); session.getLogger().error("be retrieved by clicking \"View message source\" in"); session.getLogger().error("the Hotmail web UI."); ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); Base64OutputStream base64Out = new Base64OutputStream(baos, true, 72, LINE_SEPARATOR); try { downloadRawMessageContent(session, messageId, base64Out); base64Out.close(); session.getLogger().error(new String(baos.toByteArray(), "ASCII")); } catch (Throwable t) { session.getLogger().error("Failed to dump HU01 stream", t); } throw (HU01Exception) e.getCause(); } throw e; } if (result[0] instanceof DeltaSyncException) { throw (DeltaSyncException) result[0]; } return (Document) result[0]; } }); if (session.getLogger().isDebugEnabled()) { session.getLogger().debug("Received ItemOperations response: {}", XmlUtil.toString(response, false)); } checkStatus(response); // No general error in the response. Check for a specific <Fetch> error. Element elStatus = XmlUtil.getElement(response, "/itemop:ItemOperations/itemop:Responses/itemop:Fetch/itemop:Status"); if (elStatus == null) { throw new DeltaSyncException( "No <Status> element found in <Fetch> response: " + XmlUtil.toString(response, true)); } int code = Integer.parseInt(elStatus.getTextContent().trim()); if (code == 4403) { throw new NoSuchMessageException(messageId); } else if (code != 1) { throw new UnrecognizedErrorCodeException(code, "Unrecognized error code in response for <Fetch> request. Response was: " + XmlUtil.toString(response, true)); } }