List of usage examples for org.w3c.dom Node hasAttributes
public boolean hasAttributes();
From source file:hoot.services.writers.osm.ChangesetDbWriter.java
private List<Element> write(final Document changesetDoc) throws Exception { // System.out.println(XmlUtils.documentToString(changesetDoc)); initParsedElementCache();/*from w w w .j a v a2 s. c om*/ // SQLQuery query = new SQLQuery(conn, DbUtils.getConfiguration()); /* try { log.debug("Retrieving map ID associated with changeset having ID: " + requestChangesetId + " ..."); assert (requestChangesetId != -1); // see Changeset::isOpen for comments on why references to ChangesetsDao // have been removed // from this code requestChangesetMapId = new SQLQuery(conn, DbUtils.getConfiguration()).from(changesets) .where(changesets.id.eq(requestChangesetId)).singleResult(changesets.mapId); assert (requestChangesetMapId != -1); log.debug("Retrieved map ID: " + requestChangesetMapId); } catch (Exception e) { throw new Exception("Error locating map associated with changeset with ID: " + requestChangesetId + " (" + e.getMessage() + ")"); } */ log.debug("Inserting new OSM elements and updating existing OSM elements..."); // By storing the elements and the element records in two different // collections, // changesetDiffElements and recordsToStore, data is being duplicated here // since Element // already has a copy of the UpdatableRecord. However, this prevents having // to parse through // the records a second time to collect them to pass on to the database with // the batch method. // This is wasteful of memory, so perhaps there is a better way to do this. List<Element> changesetDiffElements = new ArrayList<Element>(); long changesetDiffElementsSize = 0; // Process on entity change type at a time, different database update types // must be batched // separately (inserts/updates/deletes). for (EntityChangeType entityChangeType : EntityChangeType.values()) { // Process one element type at a time. For create/modify operations we // want to make sure // elements that contain an element type are processed after that element // type (ways contain // nodes, so process ways after nodes). This corresponds to the default // ordering of // ElementType. For delete operations we want to go in the reverse order. List<ElementType> elementTypeValues = Arrays.asList(ElementType.values()); if (entityChangeType.equals(EntityChangeType.DELETE)) { Collections.reverse(elementTypeValues); } for (ElementType elementType : elementTypeValues) { if (!elementType.equals(ElementType.Changeset)) { // The "if-unused" attribute in the delete tag prevents any element // being used by another // element from being deleted (e.g. node can't be deleted that is // still being used by a way // or relation, etc.); its attribute value is ignored; only the // presence of the attribute // or lack thereof is looked at. This seems a little confusing to me, // but that's how // rails port parses it, and I'm trying to stay consistent with what // it does when possible. boolean deleteIfUnused = false; org.w3c.dom.Node deleteXml = XPathAPI.selectSingleNode(changesetDoc, "//osmChange/" + entityChangeType.toString().toLowerCase()); if (deleteXml != null && deleteXml.hasAttributes() && deleteXml.getAttributes().getNamedItem("if-unused") != null) { deleteIfUnused = true; } // parse the elements from the request XML for the given element type changesetDiffElements.addAll(parseElements( XPathAPI.selectNodeList(changesetDoc, "//osmChange/" + entityChangeType.toString().toLowerCase() + "/" + elementType.toString().toLowerCase()), elementType, entityChangeType, deleteIfUnused)); // If any elements were actually parsed for this element and entity // update type, update // the database with the parsed elements, their related records, and // their tags if (changesetDiffElements.size() > changesetDiffElementsSize) { changesetDiffElementsSize += (changesetDiffElements.size() - changesetDiffElementsSize); assert (recordsToModify.size() > 0); // don't need to clear tags or related records out if this is a new // element, since they // won't exist yet if (!entityChangeType.equals(EntityChangeType.CREATE)) { // Clear out *all* related elements (e.g. way nodes for node, // relation members for // relation, etc.) first (this is how the rails port does it, // although while it seems // necessary for ways, it doesn't seem necessary to me for // relations). Any related // elements to be created/retained specified in the request have // already been added to // relatedRecordsToStore and will be inserted into the db // following this. final Element prototypeElement = ElementFactory.getInstance() .create(requestChangesetMapId, elementType, conn); // Elements which don't have related elements, will return a null // for the // relatedRecordType. final RelationalPathBase<?> relatedRecordTable = prototypeElement .getRelatedRecordTable(); Element.removeRelatedRecords(requestChangesetMapId, relatedRecordTable, prototypeElement.getRelatedRecordJoinField(), parsedElementIds, relatedRecordTable != null, conn); } // TODO: really need to be flushing these batch executions after // they get to be a certain // size to avoid memory problems; see maxRecordBatchSize if (elementType == ElementType.Node) { DbUtils.batchRecordsDirectNodes(requestChangesetMapId, recordsToModify, DbUtils.recordBatchTypeForEntityChangeType(entityChangeType), conn, maxRecordBatchSize); } else if (elementType == ElementType.Way) { DbUtils.batchRecordsDirectWays(requestChangesetMapId, recordsToModify, DbUtils.recordBatchTypeForEntityChangeType(entityChangeType), conn, maxRecordBatchSize); } else if (elementType == ElementType.Relation) { DbUtils.batchRecordsDirectRelations(requestChangesetMapId, recordsToModify, DbUtils.recordBatchTypeForEntityChangeType(entityChangeType), conn, maxRecordBatchSize); } // make the database updates for the element records recordsToModify.clear(); parsedElementIds.clear(); // Add the related records after the parent element records to keep // from violating // foreign key constraints. Any existing related records for this // element have already // been completely cleared. if (relatedRecordsToStore != null && relatedRecordsToStore.size() > 0) { if (elementType == ElementType.Node) { DbUtils.batchRecordsDirectNodes(requestChangesetMapId, relatedRecordsToStore, RecordBatchType.INSERT, conn, maxRecordBatchSize); } else if (elementType == ElementType.Way) { // DbUtils.batchRecordsDirectWays(relatedRecordsToStore, // RecordBatchType.INSERT, conn, maxRecordBatchSize); DbUtils.batchRecords(requestChangesetMapId, relatedRecordsToStore, QCurrentWayNodes.currentWayNodes, null, RecordBatchType.INSERT, conn, maxRecordBatchSize); } else if (elementType == ElementType.Relation) { // DbUtils.batchRecordsDirectRelations(relatedRecordsToStore, // RecordBatchType.INSERT, conn, maxRecordBatchSize); DbUtils.batchRecords(requestChangesetMapId, relatedRecordsToStore, QCurrentRelationMembers.currentRelationMembers, null, RecordBatchType.INSERT, conn, maxRecordBatchSize); } relatedRecordsToStore.clear(); } } } } } changeset.updateNumChanges((int) changesetDiffElementsSize); // Even if a bounds is specified in the incoming changeset diff data, it // should be ignored, // per OSM docs. BoundingBox newChangesetBounds = changeset.getBounds(); newChangesetBounds.expand(diffBounds, Double.parseDouble( HootProperties.getInstance().getProperty("changesetBoundsExpansionFactorDeegrees", HootProperties.getDefault("changesetBoundsExpansionFactorDeegrees")))); changeset.setBounds(newChangesetBounds); changeset.updateExpiration(); return changesetDiffElements; }
From source file:com.marklogic.dom.NodeImpl.java
/** {@inheritDoc} */ public boolean isEqualNode(Node other) { // Note that normalization can affect equality; to avoid this, // nodes should be normalized before being compared. // For the moment, normalization cannot be done. if (other == null) return false; if (getNodeType() != other.getNodeType()) return false; if (!getLocalName().equals(other.getLocalName())) return false; if (notequals(getNamespaceURI(), other.getNamespaceURI())) return false; if (notequals(getPrefix(), other.getPrefix())) return false; if (notequals(getNodeValue(), other.getNodeValue())) return false; if (hasChildNodes() != other.hasChildNodes()) return false; if (hasAttributes() != other.hasAttributes()) return false; if (hasChildNodes()) { NamedNodeMap thisAttr = getAttributes(); NamedNodeMap otherAttr = other.getAttributes(); if (thisAttr.getLength() != otherAttr.getLength()) return false; for (int i = 0; i < thisAttr.getLength(); i++) if (thisAttr.item(i).isEqualNode(otherAttr.item(i))) return false; }/*from w ww.ja va2s . c o m*/ if (hasAttributes()) { NodeList thisChild = getChildNodes(); NodeList otherChild = other.getChildNodes(); if (thisChild.getLength() != otherChild.getLength()) return false; for (int i = 0; i < thisChild.getLength(); i++) if (thisChild.item(i).isEqualNode(otherChild.item(i))) return false; } return true; }
From source file:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java
/** * * Parses an ALTO stream and returns a list of internal elements * * @param document//from w w w . j av a 2 s .co m * @return */ private List<IntPartInfo> parseAltoInfo(Document document) { List<IntPartInfo> intPartInfoList = new ArrayList<IntPartInfo>(); Node partElement = document.getFirstChild(); NodeList partsList = partElement.getChildNodes(); for (int a = 0; a < partsList.getLength(); a++) { Node node = partsList.item(a); if ((node instanceof Element) && (node.hasAttributes())) { String type = node.getAttributes().getNamedItem("type").getNodeValue(); String alto = node.getAttributes().getNamedItem("alto").getNodeValue(); String begin = node.getAttributes().getNamedItem("begin").getNodeValue(); String order = node.getAttributes().getNamedItem("order").getNodeValue(); IntPartInfo info = new IntPartInfo(type, alto.substring(0, alto.indexOf("/")), begin, order); intPartInfoList.add(info); } } return intPartInfoList; }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public @Nonnull String getOrgName(@Nonnull String href) throws CloudException, InternalException { String id = provider.toID(href); String xml = get("org", id); if (xml == null) { return id; }/*from w w w . j a v a2s . c o m*/ Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList orgs = doc.getElementsByTagName(nsString + "Org"); if (orgs.getLength() < 1) { return id; } Node org = orgs.item(0); if (!org.hasAttributes()) { return id; } Node name = org.getAttributes().getNamedItem("name"); if (name == null) { return id; } return name.getNodeValue().trim(); }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public void checkError(@Nonnull Document xmlDocument) throws CloudException { NodeList tasks;// w ww. j av a 2 s .co m try { tasks = xmlDocument.getElementsByTagName("Task"); } catch (Throwable ignore) { return; } if (tasks.getLength() < 1) { return; } Node task = tasks.item(0); if (task.hasAttributes()) { Node status = task.getAttributes().getNamedItem("status"); if (status != null) { String s = status.getNodeValue().trim(); if (!s.equals("error")) { NodeList elements = task.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node element = elements.item(i); if (element.getNodeName().equalsIgnoreCase("Error")) { parseError(element); return; } } } } } }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public void waitFor(@Nullable String xmlTask) throws CloudException { long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 30L); String taskId = null;/* ww w . j a v a 2 s . co m*/ int passCount = 1; while (timeout > System.currentTimeMillis()) { if (xmlTask == null || xmlTask.equals("")) { return; } NodeList tasks; try { Document doc = parseXML(xmlTask); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); tasks = doc.getElementsByTagName(nsString + "Task"); } catch (Throwable ignore) { return; } if (tasks.getLength() < 1) { return; } Node task = tasks.item(0); if (task.hasAttributes()) { Node status = task.getAttributes().getNamedItem("status"); if (status != null) { String s = status.getNodeValue().trim(); if (s.equals("success")) { return; } else if (s.equals("error")) { NodeList elements = task.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node element = elements.item(i); if (element.getNodeName().equalsIgnoreCase("Error")) { parseError(element); return; } } } } if (taskId == null) { Node href = task.getAttributes().getNamedItem("href"); if (href == null) { return; } taskId = provider.toID(href.getNodeValue().trim()); } } try { if (passCount > 10) { Thread.sleep(10 * CalendarWrapper.SECOND); } else { Thread.sleep(passCount * CalendarWrapper.SECOND); } } catch (InterruptedException ignore) { } try { xmlTask = get("task", taskId); } catch (Throwable ignore) { } passCount += 1; } logger.warn("Task timed out: " + taskId); }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
private void loadOrg(@Nonnull String endpoint, @Nonnull Org org, @Nonnull String orgId) throws CloudException, InternalException { String xml;// w ww.j av a 2s . c o m if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [GET (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { HttpClient client = getClient(false); HttpGet get = new HttpGet(endpoint); get.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(get, org.token); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "GET org"); response = client.execute(get); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code == HttpServletResponse.SC_NOT_FOUND || code == HttpServletResponse.SC_FORBIDDEN) { throw new CloudException("Org URL is invalid"); } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { authenticate(true); loadOrg(endpoint, org, orgId); return; } else if (code == HttpServletResponse.SC_NO_CONTENT) { throw new CloudException("No content from org URL"); } else if (code == HttpServletResponse.SC_OK) { try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } else { xml = null; } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } } else { logger.error("Expected OK for GET request, got " + code); try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } else { xml = null; } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(code, errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, code, response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + code + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (wire.isDebugEnabled()) { wire.debug("<<< [GET (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } if (xml == null) { throw new CloudException("No content from org URL"); } Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList orgList = doc.getElementsByTagName(nsString + "Org"); for (int i = 0; i < orgList.getLength(); i++) { Node orgNode = orgList.item(i); if (orgNode.hasAttributes()) { Node type = orgNode.getAttributes().getNamedItem("type"); if (type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg())) { Node name = orgNode.getAttributes().getNamedItem("name"); if (name != null && name.getNodeValue().trim().equals(orgId)) { Node href = orgNode.getAttributes().getNamedItem("href"); if (href != null) { Region region = new Region(); String url = href.getNodeValue().trim(); region.setActive(true); region.setAvailable(true); if (provider.isCompat()) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/api/org")); org.region = region; org.url = url; return; } } } } } throw new CloudException("Could not find " + orgId + " among listed orgs"); }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
private void loadVDCs(@Nonnull Org org) throws CloudException, InternalException { if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [GET (" + (new Date()) + ")] -> " + org.url + " >--------------------------------------------------------------------------------------"); }/* w w w. java2s.c o m*/ try { HttpClient client = getClient(false); HttpGet method = new HttpGet(org.url); method.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(method, org.token); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { APITrace.trace(provider, "GET org"); response = client.execute(method); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } status = response.getStatusLine(); } catch (IOException e) { throw new CloudException(e); } if (status.getStatusCode() == HttpServletResponse.SC_OK) { HttpEntity entity = response.getEntity(); String body; try { body = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(body); wire.debug(""); } } catch (IOException e) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } try { ByteArrayInputStream bas = new ByteArrayInputStream(body.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); ArrayList<VDC> vdcs = new ArrayList<VDC>(); Document doc = parser.parse(bas); bas.close(); NodeList links = doc.getElementsByTagName("Link"); for (int i = 0; i < links.getLength(); i++) { Node link = links.item(i); if (link.hasAttributes()) { Node type = link.getAttributes().getNamedItem("type"); if (type != null && type.getNodeValue().trim().equals("application/vnd.vmware.vcloud.vdc+xml")) { Node name = link.getAttributes().getNamedItem("name"); if (name != null) { DataCenter dc = new DataCenter(); VDC vdc = new VDC(); vdc.actions = new HashMap<String, String>(); dc.setActive(true); dc.setAvailable(true); dc.setName(name.getNodeValue().trim()); dc.setRegionId(org.region.getProviderRegionId()); Node href = link.getAttributes().getNamedItem("href"); if (href != null) { String id = provider.toID(href.getNodeValue().trim()); dc.setProviderDataCenterId(id); vdc.dataCenter = dc; loadVDC(vdc, id); vdcs.add(vdc); } } } } } org.setVdcs(vdcs); } catch (IOException e) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch (ParserConfigurationException e) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch (SAXException e) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } else { logger.error("Expected OK for GET request, got " + status.getStatusCode()); String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(status.getStatusCode(), errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, status.getStatusCode(), response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + status.getStatusCode() + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (wire.isDebugEnabled()) { wire.debug("<<< [GET (" + (new Date()) + ")] -> " + org.url + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } }
From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java
private void parseDeployment(@Nonnull ProviderContext ctx, @Nonnull String regionId, @Nonnull String serviceName, @Nonnull Node node, @Nonnull List<VirtualMachine> virtualMachines) { ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>(); NodeList attributes = node.getChildNodes(); String deploymentSlot = null; String deploymentId = null;//from www .j a va2s. co m String dnsName = null; String vmRoleName = null; String imageId = null; String vmImageId = null; String diskOS = null; String mediaLink = null; String vlan = null; String subnetName = null; boolean isLocked = false; for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNodeType() == Node.TEXT_NODE) { continue; } if (attribute.getNodeName().equalsIgnoreCase("deploymentslot") && attribute.hasChildNodes()) { deploymentSlot = attribute.getFirstChild().getNodeValue().trim(); } else if (attribute.getNodeName().equalsIgnoreCase("privateid") && attribute.hasChildNodes()) { deploymentId = attribute.getFirstChild().getNodeValue().trim(); } else if (attribute.getNodeName().equalsIgnoreCase("locked") && attribute.hasChildNodes()) { if (attribute.getFirstChild().getNodeValue().trim().equalsIgnoreCase("true")) { isLocked = true; } } else if (attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes()) { try { URI u = new URI(attribute.getFirstChild().getNodeValue().trim()); dnsName = u.getHost(); } catch (URISyntaxException e) { // ignore } } else if (attribute.getNodeName().equalsIgnoreCase("roleinstancelist") && attribute.hasChildNodes()) { NodeList roleInstances = attribute.getChildNodes(); for (int j = 0; j < roleInstances.getLength(); j++) { Node roleInstance = roleInstances.item(j); if (roleInstance.getNodeType() == Node.TEXT_NODE) { continue; } if (roleInstance.getNodeName().equalsIgnoreCase("roleinstance") && roleInstance.hasChildNodes()) { VirtualMachine role = new VirtualMachine(); role.setArchitecture(Architecture.I64); role.setClonable(false); role.setCurrentState(VmState.TERMINATED); role.setImagable(false); role.setPersistent(true); role.setPlatform(Platform.UNKNOWN); role.setProviderOwnerId(ctx.getAccountNumber()); role.setProviderRegionId(regionId); role.setProviderDataCenterId(regionId); NodeList roleAttributes = roleInstance.getChildNodes(); for (int l = 0; l < roleAttributes.getLength(); l++) { Node roleAttribute = roleAttributes.item(l); if (roleAttribute.getNodeType() == Node.TEXT_NODE) { continue; } if (roleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes()) { String vmId = roleAttribute.getFirstChild().getNodeValue().trim(); role.setProviderVirtualMachineId(serviceName + ":" + vmId); role.setName(vmId); } else if (roleAttribute.getNodeName().equalsIgnoreCase("instancesize") && roleAttribute.hasChildNodes()) { role.setProductId(roleAttribute.getFirstChild().getNodeValue().trim()); } else if (roleAttribute.getNodeName().equalsIgnoreCase("instanceupgradedomain") && roleAttribute.hasChildNodes()) { role.setTag("UpgradeDomain", roleAttribute.getFirstChild().getNodeValue().trim()); } else if (roleAttribute.getNodeName().equalsIgnoreCase("instanceerrorcode") && roleAttribute.hasChildNodes()) { role.setTag("ErrorCode", roleAttribute.getFirstChild().getNodeValue().trim()); } else if (roleAttribute.getNodeName().equalsIgnoreCase("instancefaultdomain") && roleAttribute.hasChildNodes()) { role.setTag("FaultDomain", roleAttribute.getFirstChild().getNodeValue().trim()); } else if (roleAttribute.getNodeName().equalsIgnoreCase("fqdn") && roleAttribute.hasChildNodes()) { role.setPrivateDnsAddress(roleAttribute.getFirstChild().getNodeValue().trim()); } else if (roleAttribute.getNodeName().equalsIgnoreCase("ipaddress") && roleAttribute.hasChildNodes()) { role.setPrivateAddresses(new RawAddress[] { new RawAddress(roleAttribute.getFirstChild().getNodeValue().trim()) }); } else if (roleAttribute.getNodeName().equalsIgnoreCase("instanceendpoints") && roleAttribute.hasChildNodes()) { NodeList endpoints = roleAttribute.getChildNodes(); for (int m = 0; m < endpoints.getLength(); m++) { Node endpoint = endpoints.item(m); if (endpoint.hasChildNodes()) { NodeList ea = endpoint.getChildNodes(); for (int n = 0; n < ea.getLength(); n++) { Node a = ea.item(n); if (a.getNodeName().equalsIgnoreCase("vip") && a.hasChildNodes()) { String addr = a.getFirstChild().getNodeValue().trim(); RawAddress[] ips = role.getPublicAddresses(); if (ips == null || ips.length < 1) { role.setPublicAddresses( new RawAddress[] { new RawAddress(addr) }); } else { boolean found = false; for (RawAddress ip : ips) { if (ip.getIpAddress().equals(addr)) { found = true; break; } } if (!found) { RawAddress[] tmp = new RawAddress[ips.length + 1]; System.arraycopy(ips, 0, tmp, 0, ips.length); tmp[tmp.length - 1] = new RawAddress(addr); role.setPublicAddresses(tmp); } } } } } } } else if (roleAttribute.getNodeName().equalsIgnoreCase("PowerState") && roleAttribute.hasChildNodes()) { String powerStatus = roleAttribute.getFirstChild().getNodeValue().trim(); if ("Started".equalsIgnoreCase(powerStatus)) { role.setCurrentState(VmState.RUNNING); } else if ("Stopped".equalsIgnoreCase(powerStatus)) { role.setCurrentState(VmState.STOPPED); role.setImagable(true); } else if ("Stopping".equalsIgnoreCase(powerStatus)) { role.setCurrentState(VmState.STOPPING); } else if ("Starting".equalsIgnoreCase(powerStatus)) { role.setCurrentState(VmState.PENDING); } else { logger.warn("DEBUG: Unknown Azure status: " + powerStatus); } } } if (role.getProviderVirtualMachineId() == null) { continue; } if (role.getName() == null) { role.setName(role.getProviderVirtualMachineId()); } if (role.getDescription() == null) { role.setDescription(role.getName()); } if (role.getPlatform().equals(Platform.UNKNOWN)) { String descriptor = (role.getProviderVirtualMachineId() + " " + role.getName() + " " + role.getDescription() + " " + role.getProviderMachineImageId()) .replaceAll("_", " "); role.setPlatform(Platform.guess(descriptor)); } else if (role.getPlatform().equals(Platform.UNIX)) { String descriptor = (role.getProviderVirtualMachineId() + " " + role.getName() + " " + role.getDescription() + " " + role.getProviderMachineImageId()) .replaceAll("_", " "); Platform p = Platform.guess(descriptor); if (p.isUnix()) { role.setPlatform(p); } } list.add(role); } } } //Contain the information about disk and firewall; else if (attribute.getNodeName().equalsIgnoreCase("rolelist") && attribute.hasChildNodes()) { NodeList roles = attribute.getChildNodes(); for (int k = 0; k < roles.getLength(); k++) { Node role = roles.item(k); if (role.getNodeName().equalsIgnoreCase("role") && role.hasChildNodes()) { if (role.hasAttributes()) { Node n = role.getAttributes().getNamedItem("i:type"); if (n != null) { String val = n.getNodeValue(); if (!"PersistentVMRole".equalsIgnoreCase(val)) { continue; } } } NodeList roleAttributes = role.getChildNodes(); for (int l = 0; l < roleAttributes.getLength(); l++) { Node roleAttribute = roleAttributes.item(l); if (roleAttribute.getNodeType() == Node.TEXT_NODE) { continue; } if (roleAttribute.getNodeName().equalsIgnoreCase("osvirtualharddisk") && roleAttribute.hasChildNodes()) { NodeList diskAttributes = roleAttribute.getChildNodes(); for (int m = 0; m < diskAttributes.getLength(); m++) { Node diskAttribute = diskAttributes.item(m); if (diskAttribute.getNodeName().equalsIgnoreCase("SourceImageName") && diskAttribute.hasChildNodes()) { imageId = diskAttribute.getFirstChild().getNodeValue().trim(); } else if (diskAttribute.getNodeName().equalsIgnoreCase("medialink") && diskAttribute.hasChildNodes()) { mediaLink = diskAttribute.getFirstChild().getNodeValue().trim(); } else if (diskAttribute.getNodeName().equalsIgnoreCase("OS") && diskAttribute.hasChildNodes()) { diskOS = diskAttribute.getFirstChild().getNodeValue().trim(); } } } else if (roleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes()) { vmRoleName = roleAttribute.getFirstChild().getNodeValue().trim(); } else if (roleAttribute.getNodeName().equalsIgnoreCase("VMImageName") && roleAttribute.hasChildNodes()) { vmImageId = roleAttribute.getFirstChild().getNodeValue().trim(); } else if (roleAttribute.getNodeName().equalsIgnoreCase("ConfigurationSets") && roleAttribute.hasChildNodes()) { NodeList configs = ((Element) roleAttribute) .getElementsByTagName("ConfigurationSet"); for (int n = 0; n < configs.getLength(); n++) { boolean foundNetConfig = false; Node config = configs.item(n); if (config.hasAttributes()) { Node c = config.getAttributes().getNamedItem("i:type"); if (c != null) { String val = c.getNodeValue(); if (!"NetworkConfigurationSet".equalsIgnoreCase(val)) { continue; } } } if (config.hasChildNodes()) { NodeList configAttribs = config.getChildNodes(); for (int o = 0; o < configAttribs.getLength(); o++) { Node attrib = configAttribs.item(o); if (attrib.getNodeName().equalsIgnoreCase("SubnetNames") && attrib.hasChildNodes()) { NodeList subnets = attrib.getChildNodes(); for (int p = 0; p < subnets.getLength(); p++) { Node subnet = subnets.item(p); if (subnet.getNodeName().equalsIgnoreCase("SubnetName") && subnet.hasChildNodes()) { subnetName = subnet.getFirstChild().getNodeValue().trim(); } } } } } } } } } } } else if (attribute.getNodeName().equalsIgnoreCase("virtualnetworkname") && attribute.hasChildNodes()) { vlan = attribute.getFirstChild().getNodeValue().trim(); } } if (vmRoleName != null) { for (VirtualMachine vm : list) { if (deploymentSlot != null) { vm.setTag("environment", deploymentSlot); } if (deploymentId != null) { vm.setTag("deploymentId", deploymentId); } if (dnsName != null) { vm.setPublicDnsAddress(dnsName); } if (vmImageId != null) { vm.setProviderMachineImageId(vmImageId); vm.setPlatform(Platform.guess(diskOS)); } else if (imageId != null) { Platform fallback = vm.getPlatform(); vm.setProviderMachineImageId(imageId); vm.setPlatform(Platform.guess(vm.getProviderMachineImageId())); if (vm.getPlatform().equals(Platform.UNKNOWN)) { try { MachineImage img = getProvider().getComputeServices().getImageSupport() .getMachineImage(vm.getProviderMachineImageId()); if (img != null) { vm.setPlatform(img.getPlatform()); } } catch (Throwable t) { logger.warn("Error loading machine image: " + t.getMessage()); } if (vm.getPlatform().equals(Platform.UNKNOWN)) { vm.setPlatform(fallback); } } } if (vlan != null) { String providerVlanId = null; try { providerVlanId = getProvider().getNetworkServices().getVlanSupport().getVlan(vlan) .getProviderVlanId(); vm.setProviderVlanId(providerVlanId); } catch (CloudException e) { logger.error("Error getting vlan id for vlan " + vlan); continue; } catch (InternalException ie) { logger.error("Error getting vlan id for vlan " + vlan); continue; } if (subnetName != null) { vm.setProviderSubnetId(subnetName + "_" + providerVlanId); } } String[] parts = vm.getProviderVirtualMachineId().split(":"); String sName, deploymentName, roleName; if (parts.length == 3) { sName = parts[0]; deploymentName = parts[1]; roleName = parts[2]; } else if (parts.length == 2) { sName = parts[0]; deploymentName = parts[1]; roleName = deploymentName; } else { sName = serviceName; deploymentName = serviceName; roleName = serviceName; } vm.setTag("serviceName", sName); vm.setTag("deploymentName", deploymentName); vm.setTag("roleName", roleName); if (isLocked) { vm.setTag("locked", String.valueOf(isLocked)); } if (mediaLink != null) { vm.setTag("mediaLink", mediaLink); } virtualMachines.add(vm); } } }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
/** * replace elements in originalDom with modifiedDom according to listed * xPaths, if the originalDom has elements not listed in the xPath, it will * be kept untouched. in the HashMap<String, String> xPathPairs, the key is * the path in the source xml, and the value is the xpath for the final * note*: the if the xpath has attributes, it's not going to work... need to * do a custom implementation when that use case happened... * //w ww. j a v a 2s . co m * @param originalDom * @param modifiedDom * @param xPaths * @return * @throws XPathExpressionException */ private Document replaceByXPaths(final Document originalDom, final Document modifiedDom, Map<String, String> xPathPairs) throws XPathExpressionException { Document finalDom = originalDom; Element finalDomRoot = (Element) finalDom.getFirstChild(); Element lastChild = null; for (Entry<String, String> xPathPair : xPathPairs.entrySet()) { /** * basically, this is to copy the element specified in srcXPath, and * replace/add it to the position pointed by destXPath... */ String srcXPath = xPathPair.getKey(); logger.debug("srcXPath: " + srcXPath); String destXPath = xPathPair.getValue(); logger.debug("destXPath: " + destXPath); XPath xPath = getXPathInstance(); // find all the nodes specified by destXPath in the originalDom, and // delete them all NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET)); int el = existingNodeList.getLength(); logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath); for (int i = 0; i < el; i++) { Node c = existingNodeList.item(i); // remove this node from its parent... c.getParentNode().removeChild(c); } // create the node structure first. and return the last child of the // path... the right most node... lastChild = createElementStructureByPath(finalDomRoot, destXPath); List<String> nodeNameList = getNodeList(destXPath); String lastNodeName = nodeNameList.get(nodeNameList.size() - 1); xPath.reset(); // find all the nodes specified by srcXPath in the modifiedDom NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET)); int l = nodeList.getLength(); logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath); Node currentNode = null; for (int i = 0; i < l; i++) { currentNode = nodeList.item(i); // the name of the last node in srcXPath might not be the same // as the name of the last node in destXPath Element lastElement = finalDom.createElement(lastNodeName); // NodeList currentNodeChildNodes = currentNode.getChildNodes(); // int s = currentNodeChildNodes.getLength(); // for(int j = 0; j < s; j++){ // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j), // true)); // } if (currentNode.hasAttributes()) { NamedNodeMap attributes = currentNode.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { String attribute_name = attributes.item(j).getNodeName(); String attribute_value = attributes.item(j).getNodeValue(); lastElement.setAttribute(attribute_name, attribute_value); } } while (currentNode.hasChildNodes()) { Node kid = currentNode.getFirstChild(); currentNode.removeChild(kid); lastElement.appendChild(finalDom.importNode(kid, true)); } lastChild.appendChild(lastElement); } } return finalDom; }