List of usage examples for org.w3c.dom Document getElementsByTagName
public NodeList getElementsByTagName(String tagname);
NodeList
of all the Elements
in document order with a given tag name and are contained in the document. From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * TransCellAccessToken????./* www .j av a 2s .c o m*/ * @param token * @return TransCellAccessToken(?) * @throws AbstractOAuth2Token.TokenParseException ? * @throws AbstractOAuth2Token.TokenDsigException ??? * @throws AbstractOAuth2Token.TokenRootCrtException CA? */ public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException, AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException { try { byte[] samlBytes = DcCoreUtils.decodeBase64Url(token); ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.parse(bais); Element assertion = doc.getDocumentElement(); Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0)); Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0)); Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0)); String id = assertion.getAttribute("ID"); String issuedAtStr = assertion.getAttribute("IssueInstant"); DateTime dt = new DateTime(issuedAtStr); NodeList audienceList = assertion.getElementsByTagName("Audience"); Element aud1 = (Element) (audienceList.item(0)); String target = aud1.getTextContent(); String schema = null; if (audienceList.getLength() > 1) { Element aud2 = (Element) (audienceList.item(1)); schema = aud2.getTextContent(); } List<Role> roles = new ArrayList<Role>(); NodeList attrList = assertion.getElementsByTagName("AttributeValue"); for (int i = 0; i < attrList.getLength(); i++) { Element attv = (Element) (attrList.item(i)); roles.add(new Role(new URL(attv.getTextContent()))); } NodeList nl = assertion.getElementsByTagName("Signature"); if (nl.getLength() == 0) { throw new TokenParseException("Cannot find Signature element"); } Element signatureElement = (Element) nl.item(0); // ???????TokenDsigException?? // Create a DOMValidateContext and specify a KeySelector // and document context. X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent()); DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement); // Unmarshal the XMLSignature. XMLSignature signature; try { signature = xmlSignatureFactory.unmarshalXMLSignature(valContext); } catch (MarshalException e) { throw new TokenDsigException(e.getMessage(), e); } // CA?? try { x509KeySelector.readRoot(x509RootCertificateFileNames); } catch (CertificateException e) { // CA????????500 throw new TokenRootCrtException(e.getMessage(), e); } // Validate the XMLSignature x509. boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { if (e.getCause().getClass() == new KeySelectorException().getClass()) { throw new TokenDsigException(e.getCause().getMessage(), e.getCause()); } throw new TokenDsigException(e.getMessage(), e); } // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation // Check core validation status. if (!coreValidity) { // ?? boolean isDsigValid; try { isDsigValid = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!isDsigValid) { throw new TokenDsigException("Failed signature validation"); } // Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { boolean refValid; try { refValid = ((Reference) i.next()).validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!refValid) { throw new TokenDsigException("Failed to validate reference [" + j + "]"); } } throw new TokenDsigException("Signature failed core validation. unkwnon reason."); } return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(), subjectNameID.getTextContent(), target, roles, schema); } catch (UnsupportedEncodingException e) { throw new TokenParseException(e.getMessage(), e); } catch (SAXException e) { throw new TokenParseException(e.getMessage(), e); } catch (IOException e) { throw new TokenParseException(e.getMessage(), e); } }
From source file:edu.stanford.epad.epadws.queries.XNATQueries.java
public static String getXNATSubjectFieldValue(String sessionID, String xnatSubjectID, String fieldName) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml"); int xnatStatusCode; //log.info("Calling XNAT Subject info:" + XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml"); method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID); try {//from w ww. j a v a 2 s . com xnatStatusCode = client.executeMethod(method); String xmlResp = method.getResponseBodyAsString(10000); log.debug(xmlResp); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputStream is = new StringBufferInputStream(xmlResp); Document doc = db.parse(is); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("xnat:field"); String value = ""; String subjfieldname = ""; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); value = node.getTextContent(); if (value != null) value = value.replace('\n', ' ').trim(); NamedNodeMap attrs = node.getAttributes(); String attrName = null; for (int j = 0; attrs != null && j < attrs.getLength(); j++) { attrName = attrs.item(j).getNodeName(); subjfieldname = attrs.item(j).getNodeValue(); if (fieldName.equalsIgnoreCase(subjfieldname)) return value; } } return value; } catch (Exception e) { log.warning( "Warning: error performing XNAT subject query " + XNATQueryUtil.buildSubjectURL(xnatSubjectID), e); xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } finally { method.releaseConnection(); } return null; }
From source file:io.personium.common.auth.token.TransCellAccessToken.java
/** * TransCellAccessToken????.//from w w w. j av a2 s .c om * @param token * @return TransCellAccessToken(?) * @throws AbstractOAuth2Token.TokenParseException ? * @throws AbstractOAuth2Token.TokenDsigException ??? * @throws AbstractOAuth2Token.TokenRootCrtException CA? */ public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException, AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException { try { byte[] samlBytes = PersoniumCoreUtils.decodeBase64Url(token); ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.parse(bais); Element assertion = doc.getDocumentElement(); Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0)); Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0)); Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0)); String id = assertion.getAttribute("ID"); String issuedAtStr = assertion.getAttribute("IssueInstant"); DateTime dt = new DateTime(issuedAtStr); NodeList audienceList = assertion.getElementsByTagName("Audience"); Element aud1 = (Element) (audienceList.item(0)); String target = aud1.getTextContent(); String schema = null; if (audienceList.getLength() > 1) { Element aud2 = (Element) (audienceList.item(1)); schema = aud2.getTextContent(); } List<Role> roles = new ArrayList<Role>(); NodeList attrList = assertion.getElementsByTagName("AttributeValue"); for (int i = 0; i < attrList.getLength(); i++) { Element attv = (Element) (attrList.item(i)); roles.add(new Role(new URL(attv.getTextContent()))); } NodeList nl = assertion.getElementsByTagName("Signature"); if (nl.getLength() == 0) { throw new TokenParseException("Cannot find Signature element"); } Element signatureElement = (Element) nl.item(0); // ???????TokenDsigException?? // Create a DOMValidateContext and specify a KeySelector // and document context. X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent()); DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement); // Unmarshal the XMLSignature. XMLSignature signature; try { signature = xmlSignatureFactory.unmarshalXMLSignature(valContext); } catch (MarshalException e) { throw new TokenDsigException(e.getMessage(), e); } // CA?? try { x509KeySelector.readRoot(x509RootCertificateFileNames); } catch (CertificateException e) { // CA????????500 throw new TokenRootCrtException(e.getMessage(), e); } // Validate the XMLSignature x509. boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { if (e.getCause().getClass() == new KeySelectorException().getClass()) { throw new TokenDsigException(e.getCause().getMessage(), e.getCause()); } throw new TokenDsigException(e.getMessage(), e); } // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation // Check core validation status. if (!coreValidity) { // ?? boolean isDsigValid; try { isDsigValid = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!isDsigValid) { throw new TokenDsigException("Failed signature validation"); } // Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { boolean refValid; try { refValid = ((Reference) i.next()).validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!refValid) { throw new TokenDsigException("Failed to validate reference [" + j + "]"); } } throw new TokenDsigException("Signature failed core validation. unkwnon reason."); } return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(), subjectNameID.getTextContent(), target, roles, schema); } catch (UnsupportedEncodingException e) { throw new TokenParseException(e.getMessage(), e); } catch (SAXException e) { throw new TokenParseException(e.getMessage(), e); } catch (IOException e) { throw new TokenParseException(e.getMessage(), e); } }
From source file:com.fota.Link.sdpApi.java
public static String getNcnInfo(String CTN) throws JDOMException { String resultStr = ""; String logData = ""; try {/*from w w w. j a v a 2s. co m*/ String endPointUrl = PropUtil.getPropValue("sdp.oif516.url"); String strRequest = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' " + "xmlns:oas='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'" + " xmlns:sdp='http://kt.com/sdp'>" + " <soapenv:Header>" + " <oas:Security>" + " <oas:UsernameToken>" + " <oas:Username>" + PropUtil.getPropValue("sdp.id") + "</oas:Username>" + " <oas:Password>" + PropUtil.getPropValue("sdp.pw") + "</oas:Password>" + " </oas:UsernameToken>" + " </oas:Security>" + " </soapenv:Header>" + " <soapenv:Body>" + " <sdp:getBasicUserInfoAndMarketInfoRequest>" + " <!--You may enterthe following 6 items in any order-->" + " <sdp:CALL_CTN>" + CTN + "</sdp:CALL_CTN>" + " </sdp:getBasicUserInfoAndMarketInfoRequest>\n" + " </soapenv:Body>\n" + "</soapenv:Envelope>"; logData = "\r\n---------- Get Ncn Req Info start ----------\r\n"; logData += " get Ncn Req Info - endPointUrl : " + endPointUrl; logData += "\r\n get Ncn Req Info - Content-type : text/xml;charset=utf-8"; logData += "\r\n get Ncn Req Info - RequestMethod : POST"; logData += "\r\n get Ncn Req Info - xml : " + strRequest; logData += "\r\n---------- Get Ncn Req Info end ----------"; logger.info(logData); // connection URL url = new URL(endPointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-type", "text/xml;charset=utf-8"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // output OutputStream os = connection.getOutputStream(); // os.write(strRequest.getBytes(), 0, strRequest.length()); os.write(strRequest.getBytes("utf-8")); os.flush(); os.close(); // input InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8")); String line = ""; String resValue = ""; String parseStr = ""; while ((line = br.readLine()) != null) { System.out.println(line); parseStr = line; } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource temp = new InputSource(); temp.setCharacterStream(new StringReader(parseStr)); Document doc = builder.parse(temp); //xml? NodeList list = doc.getElementsByTagName("*"); int i = 0; Element element; String contents; String contractNum = ""; String customerId = ""; while (list.item(i) != null) { element = (Element) list.item(i); if (element.hasChildNodes()) { contents = element.getFirstChild().getNodeValue(); System.out.println(element.getNodeName() + " / " + element.getFirstChild().getNodeName()); if (element.getNodeName().equals("sdp:NS_CONTRACT_NUM")) { // resultStr = element.getFirstChild().getNodeValue(); contractNum = element.getFirstChild().getNodeValue(); } if (element.getNodeName().equals("sdp:NS_CUSTOMER_ID")) { customerId = element.getFirstChild().getNodeValue(); } // System.out.println(" >>>>> " + contents); } i++; } // System.out.println("contractNum : " + contractNum + " / cusomerId : " + customerId); resultStr = getNcnFromContractnumAndCustomerId(contractNum, customerId); // System.out.println("ncn : " + resultStr); //resultStr = resValue; // resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr"); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resultStr; }
From source file:dk.clarin.tools.workflow.java
public static String errorInfo(String toolsandfiles) { String body = ""; try {//from w w w . ja v a 2s .c o m DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(toolsandfiles)); Document doc = db.parse(is); NodeList nodes = doc.getElementsByTagName("step"); // iterate the results for (int i = 0; i < nodes.getLength(); ++i) { Element element = (Element) nodes.item(i); //NodeList JobNrlist = element.getElementsByTagName("JobNr"); //Element JobNrelement = (Element) JobNrlist.item(0); //String JobNr = getCharacterDataFromElement(JobNrelement); NodeList JobIDlist = element.getElementsByTagName("JobId"); Element JobIDelement = (Element) JobIDlist.item(0); String JobID = getCharacterDataFromElement(JobIDelement); NodeList toollist = element.getElementsByTagName("tool"); Element toolelement = (Element) toollist.item(0); String tool = getCharacterDataFromElement(toolelement); body += "Fejlen skete i trin " + JobID + " (vrktj: " + tool + ")" + ":<br />\n"; NodeList itemslist = element.getElementsByTagName("item"); if (itemslist.getLength() > 0) { body += "Vrktjet havde disse resurser som input:<br />\n"; for (int j = 0; j < itemslist.getLength(); ++j) { Element item = (Element) itemslist.item(j); NodeList idlist = item.getElementsByTagName("id"); Element idelement = (Element) idlist.item(0); String id = getCharacterDataFromElement(idelement); NodeList titlelist = item.getElementsByTagName("title"); Element titleelement = (Element) titlelist.item(0); String title = getCharacterDataFromElement(titleelement); body += id + " \'" + title + "\'<br />\n"; } if (i > 0) body += "<br />\n(Input fra eventuelt foregende trin er ikke nvnt.)<br />\n"; else body += "<br />\n"; } } } catch (Exception e) { logger.error(e.getMessage()); } return body; }
From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java
/** * * @param filePath : file path//from w w w . jav a 2s. c om * @param tagName : tag name * @return : value of the elements */ public static String[] getDataFromXmlByTagName(String filePath, String tagName) { String[] data = null; try { File file = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); //optional, but recommended //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work doc.getDocumentElement().normalize(); //System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 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) { Element eElement = (Element) nNode; dataList.add(eElement.getTextContent()); //System.out.println("file type : " + eElement.getTextContent() + "\n"); } } 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, ex); } return data; }
From source file:com.liferay.ide.server.util.ServerUtil.java
public static String[] getServletFilterNames(IPath portalDir) throws Exception { List<String> retval = new ArrayList<String>(); File filtersWebXmlFile = portalDir.append("WEB-INF/liferay-web.xml").toFile(); //$NON-NLS-1$ if (!filtersWebXmlFile.exists()) { filtersWebXmlFile = portalDir.append("WEB-INF/web.xml").toFile(); //$NON-NLS-1$ }// www . j a v a 2 s .c o m if (filtersWebXmlFile.exists()) { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(filtersWebXmlFile); NodeList filterNameElements = document.getElementsByTagName("filter-name"); //$NON-NLS-1$ for (int i = 0; i < filterNameElements.getLength(); i++) { Node filterNameElement = filterNameElements.item(i); String content = filterNameElement.getTextContent(); if (!CoreUtil.isNullOrEmpty(content)) { retval.add(content.trim()); } } } return retval.toArray(new String[0]); }
From source file:Main.java
public static String setValueXPath(String srcXmlString, String xPath, String newVal) { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(false); // never forget this! int i, j;/*from w w w . j a va 2s. co m*/ Document doc = null; DocumentBuilder builder = null; try { builder = domFactory.newDocumentBuilder(); doc = builder.parse(new ByteArrayInputStream(srcXmlString.getBytes())); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(xPath); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList xPathNodes = (NodeList) result; logger.debug("xpath result count: " + xPathNodes.getLength()); logger.debug(xPathNodes.item(0).getNodeName() + " = " + xPathNodes.item(0).getTextContent()); // get list of all nodes in doc NodeList nodes = doc.getElementsByTagName("*"); // iterate through all the nodes for (i = 0; i < xPathNodes.getLength(); i++) { // for each node in xpath result - traverse through all nodes in // doc to find match for (j = 0; j < nodes.getLength(); j++) { if (nodes.item(j).isSameNode(xPathNodes.item(i))) { logger.debug("Old value " + i + ": " + xPathNodes.item(i).getNodeName() + " = " + xPathNodes.item(i).getTextContent()); nodes.item(j).setTextContent(newVal); logger.debug("New value " + i + ": " + xPathNodes.item(i).getNodeName() + " = " + xPathNodes.item(i).getTextContent()); break; } } } } catch (Exception ex) { logger.error(ex.getMessage()); // ex.printStackTrace(); } return getW3CXmlFromDoc(doc); }
From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java
public static List<TechnicalFragment> parseRassetXML(String path, TechnicalFragment tf) { List<TechnicalFragment> dependencies = new ArrayList<TechnicalFragment>(); Document doc = getDocument(path); if (doc != null) { if (doc != null) { Node type = doc.getElementsByTagName("type").item(0); Node origin = doc.getElementsByTagName("origin").item(0); Node objective = doc.getElementsByTagName("objective").item(0); Node input = doc.getElementsByTagName("input").item(0); Node output = doc.getElementsByTagName("output").item(0); tf.setType(type.getAttributes().getNamedItem("value").getNodeValue()); tf.setOrigin(origin.getAttributes().getNamedItem("value").getNodeValue()); tf.setObjective(objective.getAttributes().getNamedItem("value").getNodeValue()); tf.setInput(input.getAttributes().getNamedItem("value").getNodeValue()); tf.setOutput(output.getAttributes().getNamedItem("value").getNodeValue()); NodeList deps = doc.getElementsByTagName("dependency"); int length = deps.getLength(); for (int i = 0; i < length; i++) { Node depNode = deps.item(i); String depName = depNode.getAttributes().getNamedItem("value").getNodeValue(); String extension = ".ras.zip"; String assetName = depName.substring(0, depName.length() - extension.length()); TechnicalFragment asset = new TechnicalFragment(assetName, "", "", "", "", ""); dependencies.add(asset); }//from ww w. ja v a2 s.c o m } } return dependencies; }
From source file:com.omertron.thetvdbapi.tools.TvdbParser.java
/** * Get a list of series from the URL//from ww w. j av a 2s.c o m * * @param urlString * @param bannerMirror * @return */ public static List<Series> getSeriesList(String urlString, String bannerMirror) { List<Series> seriesList = new ArrayList<Series>(); Series series; NodeList nlSeries; Node nSeries; Element eSeries; Document doc; try { doc = DOMHelper.getEventDocFromUrl(urlString); } catch (WebServiceException ex) { LOG.trace(ERROR_GET_XML, ex); return seriesList; } if (doc != null) { nlSeries = doc.getElementsByTagName(SERIES); for (int loop = 0; loop < nlSeries.getLength(); loop++) { nSeries = nlSeries.item(loop); if (nSeries.getNodeType() == Node.ELEMENT_NODE) { eSeries = (Element) nSeries; series = parseNextSeries(eSeries, bannerMirror); if (series != null) { seriesList.add(series); } } } } return seriesList; }