List of usage examples for org.w3c.dom NamedNodeMap getNamedItem
public Node getNamedItem(String name);
From source file:be.ibridge.kettle.core.XMLHandler.java
public static final String getTagAttribute(Node node, String attribute) { String retval = null;//from w w w. j av a2s. c o m NamedNodeMap nnm = node.getAttributes(); if (nnm != null) { Node attr = nnm.getNamedItem(attribute); if (attr != null) { retval = attr.getNodeValue(); } } return retval; }
From source file:com.photon.phresco.framework.commons.QualityUtil.java
public static PerformancResultInfo getPerformanceReport(Document document, String techId, String deviceId) throws Exception { // deviceid is the tag name for android String xpath = "/*/*"; // For other technologies String device = "*";//from ww w. jav a2 s . c om PerformancResultInfo performanceResultInfo = new PerformancResultInfo(); TestResultInfo generateTestResultValues = new TestResultInfo(); ; if (StringUtils.isNotEmpty(deviceId)) { device = "deviceInfo[@id='" + deviceId + "']"; } if (TechnologyTypes.ANDROIDS.contains(techId)) { xpath = "/*/" + device + "/*"; } NodeList nodeList = org.apache.xpath.XPathAPI.selectNodeList(document, xpath); Map<String, PerformanceTestResult> tempMap = new LinkedHashMap<String, PerformanceTestResult>(100); List<PerformanceTestResult> results = new ArrayList<PerformanceTestResult>(); double maxTs = 0; double minTs = 0; int lastTime = 0; int noOfSamples = nodeList.getLength(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); NamedNodeMap nameNodeMap = node.getAttributes(); Node timeAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_TIME); int time = Integer.parseInt(timeAttr.getNodeValue()); Node bytesAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_BYTES); int bytes = Integer.parseInt(bytesAttr.getNodeValue()); Node successFlagAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_SUCCESS_FLAG); boolean success = Boolean.parseBoolean(successFlagAttr.getNodeValue()) ? true : false; Node labelAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_LABEL); String label = labelAttr.getNodeValue(); Node timeStampAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_TIMESTAMP); double timeStamp = Long.parseLong(timeStampAttr.getNodeValue()); boolean firstEntry = false; PerformanceTestResult performanceTestResult = tempMap.get(label); if (performanceTestResult == null) { performanceTestResult = new PerformanceTestResult(); firstEntry = true; } else { firstEntry = false; } performanceTestResult.setLabel(label.trim()); performanceTestResult.setNoOfSamples(performanceTestResult.getNoOfSamples() + 1); performanceTestResult.getTimes().add(time); performanceTestResult.setTotalTime(performanceTestResult.getTotalTime() + time); performanceTestResult.setTotalBytes(performanceTestResult.getTotalBytes() + bytes); if (time < performanceTestResult.getMin() || firstEntry) { performanceTestResult.setMin(time); } if (time > performanceTestResult.getMax()) { performanceTestResult.setMax(time); } // Error calculation if (!success) { performanceTestResult.setErr(performanceTestResult.getErr() + 1); } // Throughput calculation if (timeStamp >= performanceTestResult.getMaxTs()) { performanceTestResult.setMaxTs(timeStamp); performanceTestResult.setLastTime(time); } if (i == 0 || (performanceTestResult.getMaxTs() > maxTs)) { maxTs = performanceTestResult.getMaxTs(); lastTime = performanceTestResult.getLastTime(); } if (timeStamp < performanceTestResult.getMinTs() || firstEntry) { performanceTestResult.setMinTs(timeStamp); } if (i == 0) { minTs = performanceTestResult.getMinTs(); } else if (performanceTestResult.getMinTs() < minTs) { minTs = performanceTestResult.getMinTs(); } Double calThroughPut = new Double(performanceTestResult.getNoOfSamples()); double timeSpan = performanceTestResult.getMaxTs() + performanceTestResult.getLastTime() - performanceTestResult.getMinTs(); if (timeSpan > 0) { calThroughPut = calThroughPut / timeSpan; } else { calThroughPut = 0.0; } double throughPut = calThroughPut * 1000; performanceTestResult.setThroughtPut(throughPut); tempMap.put(label, performanceTestResult); } Set<String> keySet = tempMap.keySet(); for (String label : keySet) { results.add(tempMap.get(label)); } // Total Throughput calculation double totalThroughput; double timeSpan = ((maxTs + lastTime) - minTs); if (timeSpan > 0) { totalThroughput = (noOfSamples / timeSpan) * 1000; } else { totalThroughput = 0.0; } generateTestResultValues = setStdDevToResults(results, generateTestResultValues); generateTestResultValues = generateTestResultValues(results, totalThroughput, generateTestResultValues); setNewValuesToResults(results); performanceResultInfo.setPerfromanceTestResult(results); performanceResultInfo.setAggregateResult(generateTestResultValues); return performanceResultInfo; }
From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java
/** * Generates download manifest based on bundle manifest and puts in into * system owned bucket/*from ww w.j a v a 2s . co m*/ * * @param baseManifest * the base manifest * @param keyToUse * public key that used for encryption * @param manifestName * name for generated manifest file * @param expirationHours * expiration policy in hours for pre-signed URLs * @param urlForNc * indicates if urs are constructed for NC use * @return pre-signed URL that can be used to download generated manifest * @throws DownloadManifestException */ public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse, final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException { EucaS3Client s3Client = null; try { try { s3Client = s3ClientsPool.borrowObject(); } catch (Exception ex) { throw new DownloadManifestException("Can't borrow s3Client from the pool"); } // prepare to do pre-signed urls if (!urlForNc) s3Client.refreshEndpoint(true); else s3Client.refreshEndpoint(); Date expiration = new Date(); long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours; expiration.setTime(msec); // check if download-manifest already exists if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) { LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' is already created and has not expired. Skipping creation"); URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET); return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(), s.getQuery()); } else { LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist"); } UrlValidator urlValidator = new UrlValidator(); final String manifest = baseManifest.getManifest(); if (manifest == null) { throw new DownloadManifestException("Can't generate download manifest from null base manifest"); } final Document inputSource; final XPath xpath; Function<String, String> xpathHelper; DocumentBuilder builder = XMLParser.getDocBuilder(); inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes())); if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) { LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false)); throw new InvalidBaseManifestException("Base manifest does not have manifest element"); } StringBuilder signatureSrc = new StringBuilder(); Document manifestDoc = builder.newDocument(); Element root = (Element) manifestDoc.createElement("manifest"); manifestDoc.appendChild(root); Element el = manifestDoc.createElement("version"); el.appendChild(manifestDoc.createTextNode("2014-01-14")); signatureSrc.append(nodeToString(el, false)); root.appendChild(el); el = manifestDoc.createElement("file-format"); el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString())); root.appendChild(el); signatureSrc.append(nodeToString(el, false)); xpath = XPathFactory.newInstance().newXPath(); xpathHelper = new Function<String, String>() { @Override public String apply(String input) { try { return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING); } catch (XPathExpressionException ex) { return null; } } }; // extract keys // TODO: move this? if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) { String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key"); String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv"); String size = xpathHelper.apply("/manifest/image/size"); EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse); el = manifestDoc.createElement("bundle"); Element key = manifestDoc.createElement("encrypted-key"); key.appendChild(manifestDoc.createTextNode(encryptKey.getKey())); Element iv = manifestDoc.createElement("encrypted-iv"); iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV())); el.appendChild(key); el.appendChild(iv); Element sizeEl = manifestDoc.createElement("unbundled-size"); sizeEl.appendChild(manifestDoc.createTextNode(size)); el.appendChild(sizeEl); root.appendChild(el); signatureSrc.append(nodeToString(el, false)); } el = manifestDoc.createElement("image"); String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath()); if (bundleSize == null) { throw new InvalidBaseManifestException("Base manifest does not have size element"); } Element size = manifestDoc.createElement("size"); size.appendChild(manifestDoc.createTextNode(bundleSize)); el.appendChild(size); Element partsEl = manifestDoc.createElement("parts"); el.appendChild(partsEl); // parts NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource, XPathConstants.NODESET); if (parts == null) { throw new InvalidBaseManifestException("Base manifest does not have parts"); } for (int i = 0; i < parts.getLength(); i++) { Node part = parts.item(i); String partIndex = part.getAttributes().getNamedItem("index").getNodeValue(); String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part, XPathConstants.NODE)).getTextContent(); String partDownloadUrl = partKey; if (baseManifest.getManifestType().signPartUrl()) { GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest( baseManifest.getBaseBucket(), partKey, HttpMethod.GET); generatePresignedUrlRequest.setExpiration(expiration); URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest); partDownloadUrl = s.toString(); } else { // validate url per EUCA-9144 if (!urlValidator.isEucalyptusUrl(partDownloadUrl)) throw new DownloadManifestException( "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:" + partDownloadUrl); } Node digestNode = null; if (baseManifest.getManifestType().getDigestElement() != null) digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part, XPathConstants.NODE)); Element aPart = manifestDoc.createElement("part"); Element getUrl = manifestDoc.createElement("get-url"); getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl)); aPart.setAttribute("index", partIndex); aPart.appendChild(getUrl); if (digestNode != null) { NamedNodeMap nm = digestNode.getAttributes(); if (nm == null) throw new DownloadManifestException( "Some parts in manifest don't have digest's verification algorithm"); Element digest = manifestDoc.createElement("digest"); digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent()); digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent())); aPart.appendChild(digest); } partsEl.appendChild(aPart); } root.appendChild(el); signatureSrc.append(nodeToString(el, false)); String signatureData = signatureSrc.toString(); Element signature = manifestDoc.createElement("signature"); signature.setAttribute("algorithm", "RSA-SHA256"); signature.appendChild(manifestDoc .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes()))); root.appendChild(signature); String downloadManifest = nodeToString(manifestDoc, true); // TODO: move this ? createManifestsBucketIfNeeded(s3Client); putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, downloadManifest, expiration); // generate pre-sign url for download manifest URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET); return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(), s.getQuery()); } catch (Exception ex) { LOG.error("Got an error", ex); throw new DownloadManifestException("Can't generate download manifest"); } finally { if (s3Client != null) try { s3ClientsPool.returnObject(s3Client); } catch (Exception e) { // sad, but let's not break instances run LOG.warn("Could not return s3Client to the pool"); } } }
From source file:DOMUtils.java
public static void compareNodes(Node expected, Node actual) throws Exception { if (expected.getNodeType() != actual.getNodeType()) { throw new Exception("Different types of nodes: " + expected + " " + actual); }//w w w .j a v a 2 s .c om if (expected instanceof Document) { Document expectedDoc = (Document) expected; Document actualDoc = (Document) actual; compareNodes(expectedDoc.getDocumentElement(), actualDoc.getDocumentElement()); } else if (expected instanceof Element) { Element expectedElement = (Element) expected; Element actualElement = (Element) actual; // compare element names if (!expectedElement.getLocalName().equals(actualElement.getLocalName())) { throw new Exception("Element names do not match: " + expectedElement.getLocalName() + " " + actualElement.getLocalName()); } // compare element ns String expectedNS = expectedElement.getNamespaceURI(); String actualNS = actualElement.getNamespaceURI(); if ((expectedNS == null && actualNS != null) || (expectedNS != null && !expectedNS.equals(actualNS))) { throw new Exception("Element namespaces names do not match: " + expectedNS + " " + actualNS); } String elementName = "{" + expectedElement.getNamespaceURI() + "}" + actualElement.getLocalName(); // compare attributes NamedNodeMap expectedAttrs = expectedElement.getAttributes(); NamedNodeMap actualAttrs = actualElement.getAttributes(); if (countNonNamespaceAttribures(expectedAttrs) != countNonNamespaceAttribures(actualAttrs)) { throw new Exception(elementName + ": Number of attributes do not match up: " + countNonNamespaceAttribures(expectedAttrs) + " " + countNonNamespaceAttribures(actualAttrs)); } for (int i = 0; i < expectedAttrs.getLength(); i++) { Attr expectedAttr = (Attr) expectedAttrs.item(i); if (expectedAttr.getName().startsWith("xmlns")) { continue; } Attr actualAttr = null; if (expectedAttr.getNamespaceURI() == null) { actualAttr = (Attr) actualAttrs.getNamedItem(expectedAttr.getName()); } else { actualAttr = (Attr) actualAttrs.getNamedItemNS(expectedAttr.getNamespaceURI(), expectedAttr.getLocalName()); } if (actualAttr == null) { throw new Exception(elementName + ": No attribute found:" + expectedAttr); } if (!expectedAttr.getValue().equals(actualAttr.getValue())) { throw new Exception(elementName + ": Attribute values do not match: " + expectedAttr.getValue() + " " + actualAttr.getValue()); } } // compare children NodeList expectedChildren = expectedElement.getChildNodes(); NodeList actualChildren = actualElement.getChildNodes(); if (expectedChildren.getLength() != actualChildren.getLength()) { throw new Exception(elementName + ": Number of children do not match up: " + expectedChildren.getLength() + " " + actualChildren.getLength()); } for (int i = 0; i < expectedChildren.getLength(); i++) { Node expectedChild = expectedChildren.item(i); Node actualChild = actualChildren.item(i); compareNodes(expectedChild, actualChild); } } else if (expected instanceof Text) { String expectedData = ((Text) expected).getData().trim(); String actualData = ((Text) actual).getData().trim(); if (!expectedData.equals(actualData)) { throw new Exception("Text does not match: " + expectedData + " " + actualData); } } }
From source file:edu.eurac.commul.pepperModules.mmax2.Salt2MMAXMapping.java
public static SAnnotationNameSpaceMatchCondition parseSAnnotationNameSpaceMatchCondition(Node node) { NamedNodeMap attributes = node.getAttributes(); Node nsAttributeNode = attributes.getNamedItem(SANN_NS_REGEXP); String nsRegExp = null;/*from w w w .j a v a 2 s.co m*/ if (nsAttributeNode != null) { nsRegExp = nsAttributeNode.getNodeValue(); attributes.removeNamedItem(SANN_NS_REGEXP); } else { throw new PepperModuleException("'" + SANN_NS_REGEXP + "' attribute not found on SAnnotation NameSpace Match Condition '" + node + "'"); } if (attributes.getLength() != 0) { throw new PepperModuleException( "Additional unexpected attributes found on SAnnotation NameSpace Match Condition '" + node + "'"); } return new SAnnotationNameSpaceMatchCondition(Pattern.compile(nsRegExp)); }
From source file:edu.eurac.commul.pepperModules.mmax2.Salt2MMAXMapping.java
public static SAnnotationSNameMatchCondition parseSAnnotationSNameMatchCondition(Node node) { NamedNodeMap attributes = node.getAttributes(); Node snameAttributeNode = attributes.getNamedItem(SANN_SNAME_REGEXP); String nameRegExp = null;/*from www. j a v a 2 s.c o m*/ if (snameAttributeNode != null) { nameRegExp = snameAttributeNode.getNodeValue(); attributes.removeNamedItem(SANN_SNAME_REGEXP); } else { throw new PepperModuleException("'" + SANN_SNAME_REGEXP + "' attribute not found on SAnnotation SName Match Condition '" + node + "'"); } if (attributes.getLength() != 0) { throw new PepperModuleException( "Additional unexpected attributes found on SAnnotation SName Match Condition '" + node + "'"); } return new SAnnotationSNameMatchCondition(Pattern.compile(nameRegExp)); }
From source file:edu.eurac.commul.pepperModules.mmax2.Salt2MMAXMapping.java
public static SRelationSNameMatchCondition parseSRelationSNameMatchCondition(Node node) { NamedNodeMap attributes = node.getAttributes(); Node snameAttributeNode = attributes.getNamedItem(SREL_SNAME_REGEXP); String snameRegExp = null;// w ww. j a va2s . c o m if (snameAttributeNode != null) { snameRegExp = snameAttributeNode.getNodeValue(); attributes.removeNamedItem(SREL_SNAME_REGEXP); } else { throw new PepperModuleException("'" + SREL_SNAME_REGEXP + " attribute not found on SRelation SName Match Condition '" + node + "'"); } if (attributes.getLength() != 0) { throw new PepperModuleException( "Additional unexpected attributes found on SRelation SName Match Condition '" + node + "'"); } return new SRelationSNameMatchCondition(Pattern.compile(snameRegExp)); }
From source file:edu.eurac.commul.pepperModules.mmax2.Salt2MMAXMapping.java
public static SRelationSTypeMatchCondition parseSRelationSTypeMatchCondition(Node node) { NamedNodeMap attributes = node.getAttributes(); Node stypeAttributeNode = attributes.getNamedItem(SREL_STYPE_REGEXP); String stypeRegExp = null;/*from w ww . j ava 2 s.c om*/ if (stypeAttributeNode != null) { stypeRegExp = stypeAttributeNode.getNodeValue(); attributes.removeNamedItem(SREL_STYPE_REGEXP); } else { throw new PepperModuleException("'" + SREL_STYPE_REGEXP + " attribute not found on SRelation SType Match Condition '" + node + "'"); } if (attributes.getLength() != 0) { throw new PepperModuleException( "Additional unexpected attributes found on SRelation SType Match Condition '" + node + "'"); } return new SRelationSTypeMatchCondition(Pattern.compile(stypeRegExp)); }
From source file:edu.eurac.commul.pepperModules.mmax2.Salt2MMAXMapping.java
public static SAnnotationSLayerMatchCondition parseSAnnotationSLayerMatchCondition(Node node) { NamedNodeMap attributes = node.getAttributes(); Node slayerAttributeNode = attributes.getNamedItem(SANN_SLAYER_REGEXP); String slayerRegExp = null;// w w w . j a va 2s.c o m if (slayerAttributeNode != null) { slayerRegExp = slayerAttributeNode.getNodeValue(); attributes.removeNamedItem(SANN_SLAYER_REGEXP); } else { throw new PepperModuleException("'" + SANN_SLAYER_REGEXP + " attribute not found on SAnnotation SLayer Match Condition '" + node + "'"); } if (attributes.getLength() != 0) { throw new PepperModuleException( "Additional unexpected attributes found on SAnnnotation SLayer Match Condition '" + node + "'"); } return new SAnnotationSLayerMatchCondition(Pattern.compile(slayerRegExp)); }
From source file:edu.eurac.commul.pepperModules.mmax2.Salt2MMAXMapping.java
public static SRelationSLayerMatchCondition parseSRelationSLayerMatchCondition(Node node) { NamedNodeMap attributes = node.getAttributes(); Node slayerAttributeNode = attributes.getNamedItem(SREL_SLAYER_REGEXP); String slayerRegExp = null;//from ww w . ja v a2 s . c om if (slayerAttributeNode != null) { slayerRegExp = slayerAttributeNode.getNodeValue(); attributes.removeNamedItem(SREL_SLAYER_REGEXP); } else { throw new PepperModuleException("'" + SREL_SLAYER_REGEXP + " attribute not found on SRelation SLayer Match Condition '" + node + "'"); } if (attributes.getLength() != 0) { throw new PepperModuleException( "Additional unexpected attributes found on SRelation SLayer Match Condition '" + node + "'"); } return new SRelationSLayerMatchCondition(Pattern.compile(slayerRegExp)); }