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:org.wso2.carbon.apimgt.migration.client.MigrateFrom18to19.java
/** * This method is used to migrate synapse files * This changes the synapse api and add the new handlers * * @throws APIMigrationException//w w w . j a va 2 s .c o m */ void synapseAPIMigration() { String repository = CarbonUtils.getCarbonRepository(); String tenantRepository = CarbonUtils.getCarbonTenantsDirPath(); for (Tenant tenant : tenantsArray) { log.debug("Start synapseAPIMigration for tenant " + tenant.getId() + "(" + tenant.getDomain() + ")"); String apiFilePath; if (tenant.getId() != MultitenantConstants.SUPER_TENANT_ID) { apiFilePath = tenantRepository + "/" + tenant.getId() + "/synapse-configs/default/api"; } else { apiFilePath = repository + "synapse-configs/default/api"; } File APIFiles = new File(apiFilePath); File[] synapseFiles = APIFiles.listFiles(); if (synapseFiles == null) { log.debug("No api folder " + apiFilePath + " exists for tenant " + tenant.getId() + "(" + tenant.getDomain() + ")"); continue; } for (File synapseFile : synapseFiles) { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); try { DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(synapseFile); doc.getDocumentElement().normalize(); Element rootElement = doc.getDocumentElement(); if (Constants.SYNAPSE_API_ROOT_ELEMENT.equals(rootElement.getNodeName()) && rootElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VERSION)) { ResourceUtil.updateSynapseAPI(doc, synapseFile); } } catch (ParserConfigurationException e) { log.error("Parsing exception encountered for " + synapseFile.getAbsolutePath(), e); } catch (SAXException e) { log.error("SAX exception encountered for " + synapseFile.getAbsolutePath(), e); } catch (IOException e) { log.error("IO exception encountered for " + synapseFile.getAbsolutePath(), e); } catch (APIMigrationException e) { log.error("Updating synapse file failed for " + synapseFile.getAbsolutePath(), e); } } log.debug("End synapseAPIMigration for tenant " + tenant.getId() + "(" + tenant.getDomain() + ")"); } }
From source file:org.wso2.carbon.apimgt.migration.client._200Specific.ResourceModifier200.java
private static void updateInSequence(Element resourceElement, Document doc) { // Find the inSequence Element inSequenceElement = (Element) resourceElement .getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_INSEQUENCE).item(0); // Find the property element in the inSequence NodeList filters = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER); for (int j = 0; j < filters.getLength(); ++j) { Element filterElement = (Element) filters.item(j); if (Constants.SYNAPSE_API_VALUE_AM_KEY_TYPE .equals(filterElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE))) { // Only one <then> element can exist in filter mediator Element thenElement = (Element) filterElement .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_THEN) .item(0);/*from w ww.ja v a2s . c o m*/ NodeList properties = thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY); for (int i = 0; i < properties.getLength(); ++i) { Element propertyElement = (Element) properties.item(i); if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) { if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { thenElement.removeChild(propertyElement); break; } } } //removing bam mediator //for production url NodeList thenFilterElement = thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER); if (thenFilterElement != null && thenFilterElement.getLength() > 0) { for (int i = 0; i < thenFilterElement.getLength(); ++i) { Element filterNode = (Element) thenFilterElement.item(i); if (filterNode.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE) .contains(Constants.SYNAPSE_IS_STAT_ENABLED_PROPERTY_NAME)) { thenElement.removeChild(filterNode); } } } //for sandbox url Element elseElement = (Element) filterElement .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, "else").item(0); NodeList elseFilterElement = elseElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER); if (elseFilterElement != null && elseFilterElement.getLength() > 0) { for (int i = 0; i < elseFilterElement.getLength(); ++i) { Element filterNode = (Element) elseFilterElement.item(i); if (filterNode.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE) .contains(Constants.SYNAPSE_IS_STAT_ENABLED_PROPERTY_NAME)) { elseElement.removeChild(filterNode); } } } //adding endpoint_address property, only for production Element sendElement = (Element) thenElement .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_SEND) .item(0); Element endpointElement = (Element) sendElement .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_ENDPOINT_XML_ELEMENT) .item(0); if (endpointElement != null) { NodeList failOverElements = endpointElement .getElementsByTagName(Constants.SYNAPSE_FAIL_OVER_XML_ELEMENT); NodeList loadBalanceElements = endpointElement .getElementsByTagName(Constants.SYNAPSE_LOAD_BALANCE_XML_ELEMENT); if (failOverElements.getLength() > 0) { Element failOverElement = (Element) failOverElements.item(0); NodeList endpointElements = failOverElement .getElementsByTagName(Constants.SYNAPSE_ENDPOINT_XML_ELEMENT); for (int i = 0; i < endpointElements.getLength(); i++) { addingAddressPropertyToEndpoint((Element) endpointElements.item(i), doc); } } else if (loadBalanceElements.getLength() > 0) { Element loadBalanceElement = (Element) loadBalanceElements.item(0); NodeList endpointElements = loadBalanceElement .getElementsByTagName(Constants.SYNAPSE_ENDPOINT_XML_ELEMENT); for (int i = 0; i < endpointElements.getLength(); i++) { addingAddressPropertyToEndpoint((Element) endpointElements.item(i), doc); } } else { addingAddressPropertyToEndpoint(endpointElement, doc); } } } } boolean isExistProp = false; NodeList properties = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY); for (int i = 0; i < properties.getLength(); ++i) { Element propertyElement = (Element) properties.item(i); if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) { if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { isExistProp = true; log.info("Property '" + Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME + "' already exist"); break; } } } if (!isExistProp) { Element propertyElement = doc.createElementNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_PROPERTY); propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_EXPRESSION, Constants.SYNAPSE_API_VALUE_EXPRESSION); propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME, Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME); if (filters.getLength() > 0) { inSequenceElement.insertBefore(propertyElement, filters.item(0)); } else { inSequenceElement.appendChild(propertyElement); } } }
From source file:org.wso2.carbon.apimgt.migration.client._200Specific.ResourceModifier200.java
/** * adding address_endpoint to endpoints if not available * * @param endpointElement endpoint element * @param doc xml document/*from www .j av a2 s .c o m*/ */ public static void addingAddressPropertyToEndpoint(Element endpointElement, Document doc) { NodeList addressProp = endpointElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY); Element propertyElement, propertyElementExist; boolean exist = false; for (int i = 0; i < addressProp.getLength(); i++) { propertyElement = (Element) addressProp.item(i); if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) { if (Constants.SYNAPSE_ENDPOINT_ADDRESS_XML_ELEMENT .equalsIgnoreCase(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { exist = true; break; } } } if (!exist) { Element uriElement = (Element) endpointElement.getElementsByTagName(Constants.SYNAPSE_HTTP_XML_ELEMENT) .item(0); Element addressElement = (Element) endpointElement.getElementsByTagName("address").item(0); String val; if (uriElement != null) { val = uriElement.getAttribute(Constants.SYNAPSE_URI_TEMPLATE_ATTRIBUTE_NAME); } else if (addressElement != null) { val = addressElement.getAttribute("uri"); } else { return; } propertyElementExist = doc.createElementNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_PROPERTY); propertyElementExist.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VALUE, val); propertyElementExist.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME, Constants.SYNAPSE_ENDPOINT_ADDRESS_XML_ELEMENT); endpointElement.appendChild(propertyElementExist); } }
From source file:org.wso2.carbon.appmgt.migration.util.ResourceUtil.java
public static List<SynapseDTO> getVersionedAPIs(String apiFilePath) { File apiFiles = new File(apiFilePath); File[] files = apiFiles.listFiles(); ArrayList<SynapseDTO> versionedAPIs = new ArrayList<SynapseDTO>(); if (files != null) { for (File file : files) { try { if (!file.getName().endsWith(".xml")) { // Ignore non xml files continue; }//w ww . ja v a 2 s . com Document doc = buildDocument(file, file.getName()); Element rootElement = doc.getDocumentElement(); // Ensure that we skip internal apis such as '_TokenAPI_.xml' and apis // that represent default versions if (Constants.SYNAPSE_API_ROOT_ELEMENT.equals(rootElement.getNodeName()) && rootElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VERSION)) { log.debug("API file name : " + file.getName()); SynapseDTO synapseConfig = new SynapseDTO(doc, file); versionedAPIs.add(synapseConfig); } } catch (APPMMigrationException e) { log.error("Error when passing file " + file.getName(), e); } } } return versionedAPIs; }
From source file:org.wso2.carbon.bpel.b4p.extension.BPEL4PeopleExtensionOperation.java
/** * Called when the response for the above service is received * * @param mexId MessageExchange id/*from w ww .ja v a 2s. c o m*/ */ @Override public void onRequestReceived(String mexId) throws FaultException { if (log.isDebugEnabled()) { log.debug("People Activity Response received : mexId " + mexId); } Element notificationMessageEle = extensionContext.getInternalInstance().getMyRequest(mexId); if ("".equals(outputVarName) || outputVarName == null) { // if output variable is null or empty, these is no way to process the response from the task as we do // not have // a variable from bpel file to assign the values to. Hence what what we can do is to return a fault and // exit. log.error( "Output variable not specified correctly for the remoteTask activity.Hence the error condition." + "Please verify and correct your BPEL process remoteTask"); extensionContext.completeWithFault(cid, new FaultException(BPEL4PeopleConstants.B4P_FAULT, BPEL4PeopleConstants.NON_RECOVERABLE_ERROR)); } else { Node part = extensionContext.getPartData(notificationMessageEle, outputVarName); if (messageTraceLog.isTraceEnabled()) { messageTraceLog.trace("B4P Response Message: " + DOMUtils.domToString(notificationMessageEle)); messageTraceLog.trace("B4P Response Part: " + DOMUtils.domToString(part)); } if (CoordinationConfiguration.getInstance().isHumantaskCoordinationEnabled() && notificationMessageEle.hasChildNodes()) { String taskID = ""; Element correlationHeader = DOMUtils.findChildByName(notificationMessageEle, new QName(BPEL4PeopleConstants.B4P_NAMESPACE, BPEL4PeopleConstants.B4P_CORRELATION_HEADER), true); if (correlationHeader != null) { taskID = correlationHeader.getAttributeNS(BPEL4PeopleConstants.B4P_NAMESPACE, BPEL4PeopleConstants.B4P_CORRELATION_HEADER_ATTRIBUTE); try { deleteCoordinationTaskData(taskID); } catch (Exception e) { log.error("Error occurred while cleaning coordination data for task id " + taskID, e); } } //Checking for fault Element fault = DOMUtils.findChildByName(notificationMessageEle, new QName(WSConstants.WS_HT_COORDINATION_PROTOCOL_FAULT)); if (fault != null) { if (fault.hasAttribute("headerPart")) { if (log.isDebugEnabled()) { log.debug( "Throwing Fault to People Activity Scope since received Fault Protocol Message " + "for task" + taskID + "."); } extensionContext.completeWithFault(cid, new FaultException(BPEL4PeopleConstants.B4P_FAULT, BPEL4PeopleConstants.NON_RECOVERABLE_ERROR)); ; } } //Checking for Skip Element skipped = DOMUtils.findChildByName(notificationMessageEle, new QName(WSConstants.WS_HT_COORDINATION_PROTOCOL_SKIPPED)); if (skipped != null) { if (skipped.hasAttribute("headerPart")) { if (log.isDebugEnabled()) { log.debug("Skipping People Activity since received Skipped Protocol Message for task " + taskID + "."); } //Set extension as complete, since task is skipped. No value write to output variable. extensionContext.complete(cid); return; } } } extensionContext.writeVariable(outputVarName, notificationMessageEle); extensionContext.complete(cid); } }
From source file:org.wso2.carbon.es.migration.client.ProviderMigrationClient.java
private boolean isContentArtifact(String rxtPath, Registry registry) throws RegistryException, IOException, SAXException, ParserConfigurationException { Resource artifactRxt = registry.get(rxtPath); byte[] rxtContent = (byte[]) artifactRxt.getContent(); String rxtContentString = RegistryUtils.decodeBytes(rxtContent); Document dom = stringToDocument(rxtContentString); Element domElement = (Element) dom.getElementsByTagName(Constants.ARTIFACT_TYPE).item(0); return domElement.hasAttribute(Constants.FILE_EXTENSION); }
From source file:org.wso2.carbon.humantask.core.api.rendering.HTRenderingApiImpl.java
/** * Function to retrieve output rendering elements * * @param taskIdentifier interested task identifier * @return set of output renderings wrapped within OutputType * @throws IllegalArgumentFault error occured while retrieving renderings from task definition * @throws IOException If an error occurred while reading from the input source * @throws SAXException If the xml content in the input source is invalid * @throws IllegalOperationFault//from ww w .j av a 2s. c om * @throws IllegalAccessFault * @throws IllegalStateFault * @throws XPathExpressionException If error occurred while xpath evaluation * @throws GetRenderingsFaultException If unable to find unique id for the wso2:output rendering element */ private OutputType getRenderingOutputElements(URI taskIdentifier) throws IllegalArgumentFault, IOException, SAXException, IllegalOperationFault, IllegalAccessFault, IllegalStateFault, XPathExpressionException, GetRenderingsFaultException { QName renderingType = new QName(htRenderingNS, "output", "wso2"); String outputRenderings = (String) taskOps.getRendering(taskIdentifier, renderingType); //create output element OutputType renderingOutputs = null; //HT without output renderings is valid scenario //check availability of output renderings if (outputRenderings != null && outputRenderings.length() > 0) { //parse output renderings Element outputRenderingsElement = DOMUtils.stringToDOM(outputRenderings); //retrieve output rendering elements NodeList outputElementList = outputRenderingsElement.getElementsByTagNameNS(htRenderingNS, "element"); if (outputElementList != null && outputElementList.getLength() > 0) { int outputElementNum = outputElementList.getLength(); OutputElementType[] outputElements = new OutputElementType[outputElementNum]; //TODO get task output message from the cache // (if not in the cache) retrieve saved output using HumanTaskClientAPI String savedOutputMsg = (String) taskOps.getOutput(taskIdentifier, null); //Element to hold parsed saved output message Element savedOutputElement = null; if (savedOutputMsg != null && savedOutputMsg.length() > 0) { savedOutputElement = DOMUtils.stringToDOM(savedOutputMsg); } for (int i = 0; i < outputElementNum; i++) { Element tempElement = (Element) outputElementList.item(i); if (tempElement.hasAttribute("id")) { //Retrieve element data String elementID = tempElement.getAttribute("id"); String label = tempElement.getElementsByTagNameNS(htRenderingNS, "label").item(0) .getTextContent(); String xpath = tempElement.getElementsByTagNameNS(htRenderingNS, "xpath").item(0) .getTextContent(); String defaultValue = tempElement.getElementsByTagNameNS(htRenderingNS, "default").item(0) .getTextContent(); //set the readOnly attribute if Exists, default false String readOnly = "false"; if (tempElement.hasAttribute("readOnly")) { readOnly = tempElement.getAttribute("readOnly"); } //set element data in the response message outputElements[i] = new OutputElementType(); //set ID outputElements[i].setId(elementID); //set label outputElements[i].setLabel(label); //set xpath outputElements[i].setXpath(xpath); //set value Element valueElement = (Element) tempElement.getElementsByTagNameNS(htRenderingNS, "value") .item(0); outputElements[i].setValue(createOutRenderElementValue(valueElement)); if (readOnly.equals("true")) { outputElements[i].setReadOnly(true); } else { outputElements[i].setReadOnly(false); } if (savedOutputElement != null) { //resolve default value String savedOutMessageValue = evaluateXPath(xpath, savedOutputElement, outputRenderingsElement.getOwnerDocument()); if (savedOutMessageValue == null) { outputElements[i].set_default(defaultValue); } else { outputElements[i].set_default(savedOutMessageValue); } } else { //add default value specified in the HT rendering definition outputElements[i].set_default(defaultValue); } } else { //no unique id for the element log.error("Unable to find unique id for the wso2:output rendering element"); throw new GetRenderingsFaultException( "Unable to find unique id for the wso2:output rendering element"); } } renderingOutputs = new OutputType(); renderingOutputs.setElement(outputElements); } } //NOTE : //HT without output renderings is valid scennario in such scennario return zero length output renderings will be returned return renderingOutputs; }
From source file:org.wso2.developerstudio.eclipse.esb.impl.MediatorSequenceImpl.java
/** * {@inheritDoc}//from ww w.ja va2s . c o m */ public void doLoad(Element self) throws Exception { // Extract the name attribute. if (self.hasAttribute("name")) { setSequenceName(self.getAttribute("name")); } else { setAnonymous(true); } // Extract the on error attribute if (self.hasAttribute("onError")) { getOnError().setKeyValue(self.getAttribute("onError")); } Element descriptionElem = getChildElement(self, "description"); if (null != descriptionElem) { if (getDescription() == null) { Description description = getEsbFactory().createDescription(); description.setValue(descriptionElem.getTextContent()); setDescription(description); } else { getDescription().setValue(descriptionElem.getTextContent()); } } else { //TODO } //Description tag will be unrecognized since it is not a mediator. So we remove it now and we add description tag manually. Node node = null; Element elementForMedator = (Element) self.cloneNode(true); NodeList list = elementForMedator.getChildNodes(); for (int i = 0; i < list.getLength(); ++i) { node = list.item(i); if ("description".equals(node.getLocalName())) { elementForMedator.removeChild(node); break; } } // Load all the children. loadObjects(elementForMedator, Mediator.class, new ObjectHandler<Mediator>() { public void handle(Mediator object) { getMediators().add(object); } }); super.doLoad(self); }
From source file:org.wso2.developerstudio.eclipse.esb.impl.ModelObjectImpl.java
/** * {@inheritDoc}//from www. ja v a2 s. com */ public Element save(Element parent) throws Exception { if (getObjectState().equals(ModelObjectState.NORMAL)) { Element self = doSave(parent); // Save additional namespace declarations. if (null != self) { for (Namespace additionalNs : getAdditionalNamespaces()) { String nsAttributeName = String.format("xmlns:%s", additionalNs.getPrefix()); // Do not override. if (!self.hasAttribute(nsAttributeName)) { self.setAttribute(nsAttributeName, additionalNs.getUri()); } } } return self; } else { // Append the source text as a comment node. org.w3c.dom.Comment comment = parent.getOwnerDocument().createComment(getSourceText()); parent.appendChild(comment); return parent; } }
From source file:org.wso2.developerstudio.eclipse.esb.impl.NamespacedPropertyImpl.java
/** * {@inheritDoc}//from w w w. j a v a2s .c om */ public void doLoad(Element self) throws Exception { if (self.hasAttribute(getPropertyName())) { setPropertyValue(self.getAttribute(getPropertyName())); } // Clear namespace declarations. getNamespaces().clear(); // Load all declared additional namespaces on this element. Map<String, String> additionalNamespaces = extractNamespaces(self); if (!StringUtils.isBlank(self.getPrefix())) { // Do not include the namespace corresponding to current element itself. additionalNamespaces.remove(self.getPrefix()); } getNamespaces().putAll(additionalNamespaces); super.doLoad(self); }