List of usage examples for org.w3c.dom Element hasAttribute
public boolean hasAttribute(String name);
true
when an attribute with a given name is specified on this element or has a default value, false
otherwise. From source file:Main.java
public static Element overrideXml(Element target, Element parent) { if (parent != null) { NamedNodeMap namedNodeMap = parent.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Node attributeNode = namedNodeMap.item(i); String parentAttributeName = attributeNode.getNodeName(); String parentAttributeValue = attributeNode.getNodeValue(); // attribute override if (!target.hasAttribute(parentAttributeName)) { target.setAttribute(parentAttributeName, parentAttributeValue); }//from ww w .ja va 2s .c o m // children override if (parent.getChildNodes().getLength() > 0) { if (target.getChildNodes().getLength() == 0) { for (int j = 0; j < target.getChildNodes().getLength(); j++) { target.appendChild(target.getChildNodes().item(j)); } } } } } return target; }
From source file:at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient.java
public static List<MISMandate> sendGetMandatesRequest(String webServiceURL, String sessionId, SSLSocketFactory sSLSocketFactory) throws MISSimpleClientException { if (webServiceURL == null) { throw new NullPointerException("Argument webServiceURL must not be null."); }/*w ww. j a v a2s . c o m*/ if (sessionId == null) { throw new NullPointerException("Argument sessionId must not be null."); } // ssl settings if (sSLSocketFactory != null) { SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory); Protocol.registerProtocol("https", new Protocol("https", fac, 443)); } try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element mirElement = doc.createElementNS(MIS_NS, "MandateIssueRequest"); Element sessionIdElement = doc.createElementNS(MIS_NS, "SessionID"); sessionIdElement.appendChild(doc.createTextNode(sessionId)); mirElement.appendChild(sessionIdElement); // send soap request Element mandateIssueResponseElement = sendSOAPRequest(webServiceURL, mirElement); // check for error checkForError(mandateIssueResponseElement); // check for session id NodeList mandateElements = XPathAPI.selectNodeList(mandateIssueResponseElement, "//mis:MandateIssueResponse/mis:Mandates/mis:Mandate", NS_NODE); if (mandateElements == null || mandateElements.getLength() == 0) { throw new MISSimpleClientException("No mandates found in response."); } ArrayList<MISMandate> foundMandates = new ArrayList<MISMandate>(); for (int i = 0; i < mandateElements.getLength(); i++) { Element mandate = (Element) mandateElements.item(i); MISMandate misMandate = new MISMandate(); if (mandate.hasAttribute("ProfessionalRepresentative")) { // System.out.println("OID: " + mandate.getAttribute("ProfessionalRepresentative")); misMandate.setProfRep(mandate.getAttribute("ProfessionalRepresentative")); } if (mandate.hasAttribute("OWbPK")) { misMandate.setOWbPK(mandate.getAttribute("OWbPK")); // System.out.println("OWBPK: " + mandate.getAttribute("OWbPK")); } //misMandate.setMandate(Base64.decodeBase64(DOMUtils.getText(mandate))); misMandate.setMandate(Base64.decodeBase64(DOMUtils.getText(mandate).getBytes())); misMandate.setFullMandateIncluded(true); foundMandates.add(misMandate); } return foundMandates; } catch (ParserConfigurationException e) { throw new MISSimpleClientException("service.06", e); } catch (DOMException e) { throw new MISSimpleClientException("service.06", e); } catch (TransformerException e) { throw new MISSimpleClientException("service.06", e); } }
From source file:org.dataone.proto.trove.mn.http.client.HttpExceptionHandler.java
private static ErrorElements deserializeXml(HttpResponse response) throws IllegalStateException, IOException // throws NotFound, InvalidToken, ServiceFailure, NotAuthorized, // NotFound, IdentifierNotUnique, UnsupportedType, // InsufficientResources, InvalidSystemMetadata, NotImplemented, // InvalidCredentials, InvalidRequest, IOException { { ErrorElements ee = new ErrorElements(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc;/*from w w w . jav a 2 s . co m*/ int httpCode = response.getStatusLine().getStatusCode(); if (response.getEntity() != null) { BufferedInputStream bErrorStream = new BufferedInputStream(response.getEntity().getContent()); bErrorStream.mark(5000); // good for resetting up to 5000 bytes String detailCode = null; String description = null; String name = null; int errorCode = -1; try { DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(bErrorStream); Element root = doc.getDocumentElement(); root.normalize(); if (root.getNodeName().equalsIgnoreCase("error")) { if (root.hasAttribute("errorCode")) { try { errorCode = Integer.getInteger(root.getAttribute("errorCode")); } catch (NumberFormatException nfe) { System.out.println("errorCode unexpectedly not able to parse to int," + " using http status for creating exception"); errorCode = httpCode; } } if (errorCode != httpCode) // throw new ServiceFailure("1000","errorCode in message body doesn't match httpStatus"); { System.out.println("errorCode in message body doesn't match httpStatus," + " using errorCode for creating exception"); } if (root.hasAttribute("detailCode")) { detailCode = root.getAttribute("detailCode"); } else { detailCode = "detail code is Not Set!"; } if (root.hasAttribute("name")) { name = root.getAttribute("name"); } else { name = "Exception"; } Node child = root.getFirstChild(); do { if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equalsIgnoreCase("description")) { Element element = (Element) child; description = element.getTextContent(); break; } } } while ((child = child.getNextSibling()) != null); } else { description = domToString(doc); detailCode = "detail code was never Set!"; } } catch (TransformerException e) { description = deserializeNonXMLErrorStream(bErrorStream, e); } catch (SAXException e) { description = deserializeNonXMLErrorStream(bErrorStream, e); } catch (IOException e) { description = deserializeNonXMLErrorStream(bErrorStream, e); } catch (ParserConfigurationException e) { description = deserializeNonXMLErrorStream(bErrorStream, e); } ee.setCode(errorCode); ee.setName(name); ee.setDetailCode(detailCode); ee.setDescription(description); } return ee; }
From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java
public static Element findSolrElement(Element docE, final String name) { Element found = XMLUtils.findElement(docE, new XMLUtils.ElementsFilter() { @Override/*w w w. j a v a2s. c om*/ public boolean acceptElement(Element element) { return (element.hasAttribute("name") && element.getAttribute("name").equals(name)); } }); return found; }
From source file:de.betterform.xml.xforms.ui.state.UIElementStateUtil.java
/** * returns the value of a state attribute * * @param state the betterForm state element to examine * @param attributeName the name of the attribute to look up * @return the value of a state attribute *///from www . j a v a 2 s. com public static Object getStateAttribute(Element state, String attributeName) { if (state.hasAttribute(attributeName)) { return state.getAttribute(attributeName); } return null; }
From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java
/** * Get child nodes of the first element that has the specified tag name and also contains the * specified attribute id and value/* w ww . j a v a2s .c om*/ * * @param xmlFile XML file contents * @param elementName name of the required element * @param attrId Id of an attribute in element * @param attrVal attribute value for the given attribute * @return NodeList childNodes if the given element name with the given attributeId and * attributeValue exists, otherwise null * @throws Exception */ public static NodeList getChildNodes(String xmlFile, String elementName, String attrId, String attrVal) throws Exception { NodeList childNodes = null; Document xmlDoc = getXmlDocumentElement(xmlFile); NodeList elements = xmlDoc.getElementsByTagName(elementName); for (int i = 0; i < elements.getLength(); i++) { Element element = (Element) elements.item(i); if (element.hasAttribute(attrId)) { if (element.getAttribute(attrId).equals(attrVal)) { childNodes = element.getChildNodes(); break; } } } return childNodes; }
From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java
public static void changeMasterPidInDOM(Element docElem) { // <str name="PID">uuid:2ad31d65-50ca-11e1-916e-001b63bd97ba</str> Element elm = XMLUtils.findElement(docElem, new XMLUtils.ElementsFilter() { @Override/*from w w w . j ava 2 s . co m*/ public boolean acceptElement(Element element) { if (element.getNodeName().equals("str")) { if (element.hasAttribute("name") && (element.getAttribute("name").equals("PID"))) { return true; } } return false; } }); if (elm != null) { String pid = elm.getTextContent(); if (pid.contains("/")) { pid = pid.replace("/", ""); elm.setTextContent(pid); } } }
From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java
/** * * @param filePath : file path/* ww w.j a v a 2 s. c o m*/ * @param tagName : tag name * @param attributeMap : the map of attribute name-value map. Note: no null value contained in this map * @return : value of the elements */ public static String[] getDataFromXmlByTagNameAndAttributes(String filePath, String tagName, Map<String, String> attributeMap) { String[] data = null; try { File file = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName(tagName); int length = nList.getLength(); if (length == 0) { return null; } List<String> dataList = new ArrayList<>(); for (int temp = 0; temp < length; temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { boolean attrMatched = true; Element eElement = (Element) nNode; for (String att : attributeMap.keySet()) { String val = attributeMap.get(att); if (!eElement.hasAttribute(att) || !val.equals(eElement.getAttribute(att))) { attrMatched = false; } } if (attrMatched == true) { dataList.add(eElement.getTextContent()); } } } int size = dataList.size(); data = new String[size]; data = dataList.toArray(data); } catch (ParserConfigurationException | SAXException | IOException | DOMException ex) { logger.error("Cannot get the data from file at " + filePath + " by tag name " + tagName + " and attributes map", ex); } return data; }
From source file:fll.web.admin.UploadSubjectiveData.java
@SuppressFBWarnings(value = { "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns are dynamic") private static void saveCategoryData(final int currentTournament, final Connection connection, final Element scoreCategoryElement, final String categoryName, final ScoreCategory categoryElement) throws SQLException, ParseException { final List<AbstractGoal> goalDescriptions = categoryElement.getGoals(); PreparedStatement insertPrep = null; PreparedStatement updatePrep = null; try {//from w w w .j ava 2 s .c o m // prepare statements for update and insert final StringBuffer updateStmt = new StringBuffer(); final StringBuffer insertSQLColumns = new StringBuffer(); insertSQLColumns.append("INSERT INTO " + categoryName + " (TeamNumber, Tournament, Judge, NoShow"); final StringBuffer insertSQLValues = new StringBuffer(); insertSQLValues.append(") VALUES ( ?, ?, ?, ?"); updateStmt.append("UPDATE " + categoryName + " SET NoShow = ? "); final int numGoals = goalDescriptions.size(); for (final AbstractGoal goalDescription : goalDescriptions) { insertSQLColumns.append(", " + goalDescription.getName()); insertSQLValues.append(", ?"); updateStmt.append(", " + goalDescription.getName() + " = ?"); } updateStmt.append(" WHERE TeamNumber = ? AND Tournament = ? AND Judge = ?"); updatePrep = connection.prepareStatement(updateStmt.toString()); insertPrep = connection .prepareStatement(insertSQLColumns.toString() + insertSQLValues.toString() + ")"); // initialze the tournament insertPrep.setInt(2, currentTournament); updatePrep.setInt(numGoals + 3, currentTournament); for (final Element scoreElement : new NodelistElementCollectionAdapter( scoreCategoryElement.getElementsByTagName("score"))) { if (scoreElement.hasAttribute("modified") && "true".equalsIgnoreCase(scoreElement.getAttribute("modified"))) { final int teamNumber = Utilities.NUMBER_FORMAT_INSTANCE .parse(scoreElement.getAttribute("teamNumber")).intValue(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Saving score data for team: " + teamNumber); } final String judgeId = scoreElement.getAttribute("judge"); final boolean noShow = Boolean.parseBoolean(scoreElement.getAttribute("NoShow")); updatePrep.setBoolean(1, noShow); insertPrep.setBoolean(4, noShow); insertPrep.setInt(1, teamNumber); updatePrep.setInt(numGoals + 2, teamNumber); insertPrep.setString(3, judgeId); updatePrep.setString(numGoals + 4, judgeId); int goalIndex = 0; for (final AbstractGoal goalDescription : goalDescriptions) { final String goalName = goalDescription.getName(); final Element subscoreElement = SubjectiveUtils.getSubscoreElement(scoreElement, goalName); if (null == subscoreElement) { // no subscore element, no show or deleted insertPrep.setNull(goalIndex + 5, Types.DOUBLE); updatePrep.setNull(goalIndex + 2, Types.DOUBLE); } else { final String value = subscoreElement.getAttribute("value"); if (!value.trim().isEmpty()) { insertPrep.setString(goalIndex + 5, value.trim()); updatePrep.setString(goalIndex + 2, value.trim()); } else { insertPrep.setNull(goalIndex + 5, Types.DOUBLE); updatePrep.setNull(goalIndex + 2, Types.DOUBLE); } } ++goalIndex; } // end for // attempt the update first final int modifiedRows = updatePrep.executeUpdate(); if (modifiedRows < 1) { // do insert if nothing was updated insertPrep.executeUpdate(); } } } } finally { SQLFunctions.close(insertPrep); SQLFunctions.close(updatePrep); } }
From source file:com.centeractive.ws.SchemaUtils.java
/** * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the * specified wsdlUrl/*from w w w . j a v a 2s . co m*/ */ public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader, String tns, String xml) { if (existing.containsKey(wsdlUrl)) { return; } log.debug("Getting schema " + wsdlUrl); ArrayList<?> errorList = new ArrayList<Object>(); Map<String, XmlObject> result = new HashMap<String, XmlObject>(); boolean common = false; try { XmlOptions options = new XmlOptions(); options.setCompileNoValidation(); options.setSaveUseOpenFrag(); options.setErrorListener(errorList); options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema")); XmlObject xmlObject = loader.loadXmlObject(xml); if (xmlObject == null) throw new Exception("Failed to load schema from [" + wsdlUrl + "]"); Document dom = (Document) xmlObject.getDomNode(); Node domNode = dom.getDocumentElement(); // is this an xml schema? if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) { // set targetNamespace (this happens if we are following an include // statement) if (tns != null) { Element elm = ((Element) domNode); if (!elm.hasAttribute("targetNamespace")) { common = true; elm.setAttribute("targetNamespace", tns); } // check for namespace prefix for targetNamespace NamedNodeMap attributes = elm.getAttributes(); int c = 0; for (; c < attributes.getLength(); c++) { Node item = attributes.item(c); if (item.getNodeName().equals("xmlns")) break; if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns")) break; } if (c == attributes.getLength()) elm.setAttribute("xmlns", tns); } if (common && !existing.containsKey(wsdlUrl + "@" + tns)) result.put(wsdlUrl + "@" + tns, xmlObject); else result.put(wsdlUrl, xmlObject); } else { existing.put(wsdlUrl, null); XmlObject[] schemas = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema"); for (int i = 0; i < schemas.length; i++) { XmlCursor xmlCursor = schemas[i].newCursor(); String xmlText = xmlCursor.getObject().xmlText(options); // schemas[i] = XmlObject.Factory.parse( xmlText, options ); schemas[i] = XmlUtils.createXmlObject(xmlText, options); schemas[i].documentProperties().setSourceName(wsdlUrl); result.put(wsdlUrl + "@" + (i + 1), schemas[i]); } XmlObject[] wsdlImports = xmlObject .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location"); for (int i = 0; i < wsdlImports.length; i++) { String location = ((SimpleValue) wsdlImports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null, xml); } } XmlObject[] wadl10Imports = xmlObject.selectPath( "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href"); for (int i = 0; i < wadl10Imports.length; i++) { String location = ((SimpleValue) wadl10Imports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null, xml); } } XmlObject[] wadlImports = xmlObject.selectPath( "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href"); for (int i = 0; i < wadlImports.length; i++) { String location = ((SimpleValue) wadlImports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null, xml); } } } existing.putAll(result); XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]); for (int c = 0; c < schemas.length; c++) { xmlObject = schemas[c]; XmlObject[] schemaImports = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation"); for (int i = 0; i < schemaImports.length; i++) { String location = ((SimpleValue) schemaImports[i]).getStringValue(); Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement(); if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null, xml); } } XmlObject[] schemaIncludes = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation"); for (int i = 0; i < schemaIncludes.length; i++) { String location = ((SimpleValue) schemaIncludes[i]).getStringValue(); if (location != null) { String targetNS = getTargetNamespace(xmlObject); if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, targetNS, xml); } } } } catch (Exception e) { throw new SoapBuilderException(e); } }