You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by la...@apache.org on 2011/09/08 21:34:00 UTC

svn commit: r1166871 [2/2] - in /incubator/airavata/trunk/modules/commons: ./ utils/ utils/src/ utils/src/main/ utils/src/main/java/ utils/src/main/java/org/ utils/src/main/java/org/apache/ utils/src/main/java/org/apache/airavata/ utils/src/main/java/o...

Added: incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/WSDLUtil.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/WSDLUtil.java?rev=1166871&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/WSDLUtil.java (added)
+++ incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/WSDLUtil.java Thu Sep  8 19:33:59 2011
@@ -0,0 +1,551 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.common.utils;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+import org.xmlpull.infoset.XmlAttribute;
+import org.xmlpull.infoset.XmlBuilderException;
+import org.xmlpull.infoset.XmlElement;
+import org.xmlpull.infoset.XmlNamespace;
+import org.apache.airavata.common.exception.UtilsException;
+import xsul.XmlConstants;
+import xsul5.MLogger;
+import xsul5.wsdl.WsdlBinding;
+import xsul5.wsdl.WsdlDefinitions;
+import xsul5.wsdl.WsdlPortType;
+import xsul5.wsdl.WsdlPortTypeOperation;
+import xsul5.wsdl.WsdlUtil;
+
+public class WSDLUtil {
+
+    private static final MLogger logger = MLogger.getLogger();
+
+    /**
+     * @param wsdlString
+     * @return The WSDL
+     * @throws UtilsException
+     */
+    public static WsdlDefinitions stringToWSDL(String wsdlString) throws UtilsException {
+        try {
+            XmlElement wsdlElement = XMLUtil.stringToXmlElement(wsdlString);
+            WsdlDefinitions definitions = new WsdlDefinitions(wsdlElement);
+            return definitions;
+        } catch (RuntimeException e) {
+            throw new UtilsException(e);
+        }
+    }
+
+    /**
+     * @param definitions3
+     * @return The WsdlDefinitions (XSUL5)
+     */
+    public static xsul5.wsdl.WsdlDefinitions wsdlDefinitions3ToWsdlDefintions5(xsul.wsdl.WsdlDefinitions definitions3) {
+
+        return new xsul5.wsdl.WsdlDefinitions(XMLUtil.xmlElement3ToXmlElement5(definitions3));
+    }
+
+    /**
+     * @param definitions5
+     * @return The WsdlDefinitions (XSUL3)
+     */
+    public static xsul.wsdl.WsdlDefinitions wsdlDefinitions5ToWsdlDefintions3(xsul5.wsdl.WsdlDefinitions definitions5) {
+
+        return new xsul.wsdl.WsdlDefinitions(XMLUtil.xmlElement5ToXmlElement3(definitions5.xml()));
+    }
+
+    /**
+     * @param definitions
+     * @return The name of the WSDL.
+     */
+    public static String getWSDLName(WsdlDefinitions definitions) {
+        String wsdlName = definitions.xml().attributeValue(WSConstants.NAME_ATTRIBUTE);
+        if (wsdlName == null) {
+            // name is optional.
+            wsdlName = "";
+        }
+        return wsdlName;
+    }
+
+    /**
+     * @param definitions
+     * @return The QName of the WSDL.
+     */
+    public static QName getWSDLQName(WsdlDefinitions definitions) {
+        String targetNamespace = definitions.getTargetNamespace();
+        String wsdlName = getWSDLName(definitions);
+        return new QName(targetNamespace, wsdlName);
+    }
+
+    /**
+     * @param definitions
+     * @return The first portType
+     * @throws UtilsException
+     */
+    public static WsdlPortType getFirstPortType(WsdlDefinitions definitions) throws UtilsException {
+        for (WsdlPortType portType : definitions.portTypes()) {
+            return portType;
+        }
+        throw new UtilsException("No portType is defined in WSDL");
+    }
+
+    public static WsdlPortTypeOperation getFirstOperation(WsdlDefinitions definitions) throws UtilsException {
+        for (WsdlPortTypeOperation operation : getFirstPortType(definitions).operations()) {
+            return operation;
+        }
+        throw new UtilsException("No portType is defined in WSDL");
+    }
+
+    /**
+     * @param definitions
+     * @return The QName of the first portType.
+     * @throws UtilsException
+     */
+    public static QName getFirstPortTypeQName(WsdlDefinitions definitions) throws UtilsException {
+        String targetNamespace = definitions.getTargetNamespace();
+        for (WsdlPortType portType : definitions.portTypes()) {
+            String portTypeName = portType.getName();
+            QName portTypeQName = new QName(targetNamespace, portTypeName);
+            return portTypeQName;
+        }
+        throw new UtilsException("No portType is defined.");
+    }
+
+    /**
+     * @param definitions
+     * @param portTypeQName
+     * @return The name of the first operation in a given portType.
+     * @throws UtilsException
+     */
+    public static String getFirstOperationName(WsdlDefinitions definitions, QName portTypeQName)
+            throws UtilsException {
+        WsdlPortType portType = definitions.getPortType(portTypeQName.getLocalPart());
+        for (WsdlPortTypeOperation operation : portType.operations()) {
+            String operationName = operation.getOperationName();
+
+            // XXX Temporary solution to skip some GFac specific operations.
+            if ("Shutdown".equals(operationName)) {
+                continue;
+            } else if ("Kill".equals(operationName)) {
+                continue;
+            } else if ("Ping".equals(operationName)) {
+                continue;
+            }
+
+            return operationName;
+        }
+        throw new UtilsException("No operation is defined");
+    }
+
+    /**
+     * @param definitions
+     * @return The cloned WsdlDefinitions
+     */
+    public static WsdlDefinitions deepClone(WsdlDefinitions definitions)throws UtilsException {
+        return new WsdlDefinitions(XMLUtil.deepClone(definitions.xml()));
+    }
+
+    /**
+     * @param definitions
+     * @param paramType
+     * @return The schema that includes the type definition
+     */
+    public static XmlElement getSchema(WsdlDefinitions definitions, QName paramType) throws UtilsException {
+        XmlElement types = definitions.getTypes();
+
+        Iterable<XmlElement> schemas = types.elements(WSConstants.XSD_NS, WSConstants.SCHEMA_TAG);
+        for (XmlElement schema : schemas) {
+            if (isTypeDefinedInSchema(paramType, schema)) {
+                return schema;
+            }
+        }
+
+        // ok we didnt find the type in the schema in first level
+        // now we try try to see if it exist in schema imports.
+        // we loop in two step because its better to avoid the network
+        // connection if possible
+        for (XmlElement schema : schemas) {
+            Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG);
+            for (XmlElement importEle : imports) {
+                String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE);
+                if (null != schemaLocation && !"".equals(schemaLocation)) {
+                    try {
+                        // connect using a url connection
+                        URL url = new URL(schemaLocation);
+                        URLConnection connection = url.openConnection();
+                        connection.connect();
+                        XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection
+                                .getInputStream());
+                        if (isTypeDefinedInSchema(paramType, importedSchema)) {
+                            // still return the parent schema
+                            return schema;
+                        }
+                    } catch (MalformedURLException e) {
+                        throw new UtilsException(e);
+                    } catch (XmlBuilderException e) {
+                        throw new UtilsException(e);
+                    } catch (IOException e) {
+                        throw new UtilsException(e);
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    private static boolean isTypeDefinedInSchema(QName paramType, XmlElement schema) {
+        String schemaTargetNamespace = schema.attributeValue(WSConstants.TARGET_NAMESPACE_ATTRIBUTE);
+        if (schemaTargetNamespace.equals(paramType.getNamespaceURI())) {
+            for (XmlElement complexType : schema.elements(WSConstants.XSD_NS, WSConstants.COMPLEX_TYPE_TAG)) {
+                String complexTypeName = complexType.attributeValue(WSConstants.NAME_ATTRIBUTE);
+                if (complexTypeName.equals(paramType.getLocalPart())) {
+                    return true;
+                }
+            }
+            for (XmlElement simpleType : schema.elements(WSConstants.XSD_NS, WSConstants.SIMPLE_TYPE_TAG)) {
+                String simpleTypeName = simpleType.attributeValue(WSConstants.NAME_ATTRIBUTE);
+                if (simpleTypeName.equals(paramType.getLocalPart())) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * @param definitions
+     * @param paramType
+     * @return The type definition
+     */
+    public static XmlElement getTypeDefinition(WsdlDefinitions definitions, QName paramType) throws UtilsException {
+        XmlElement types = definitions.getTypes();
+        XmlElement returnType = null;
+        types.element(null, WSConstants.SCHEMA_TAG);
+        Iterable<XmlElement> schemas = types.elements(null, WSConstants.SCHEMA_TAG);
+        for (XmlElement schema : schemas) {
+
+            returnType = findTypeInSchema(paramType, schema);
+            if (returnType != null) {
+                return returnType;
+            }
+        }
+        // ok we didnt find the type in the schemas
+        // try to find it in the schema imports.
+
+        // if not found it will return null so we would return null
+        return findTypeDefinitionInImports(definitions, paramType);
+
+    }
+
+    /**
+     *
+     * @param definitions
+     * @param paramType
+     * @return
+     */
+
+    public static XmlElement getImportContainingTypeDefinition(WsdlDefinitions definitions, QName paramType)throws UtilsException{
+        XmlElement types = definitions.getTypes();
+        XmlElement returnType = null;
+        Iterable<XmlElement> schemas = types.elements(WSConstants.XSD_NS, WSConstants.SCHEMA_TAG);
+        for (XmlElement schema : schemas) {
+            Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG);
+            for (XmlElement importEle : imports) {
+                String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE);
+                if (null != schemaLocation && !"".equals(schemaLocation)) {
+                    try {
+                        // connect using a url connection
+                        URL url = new URL(schemaLocation);
+                        URLConnection connection = url.openConnection();
+                        connection.connect();
+                        XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection
+                                .getInputStream());
+                        returnType = findTypeInSchema(paramType, importedSchema);
+                        if (returnType != null) {
+                            return importEle;
+                        }
+
+                    } catch (MalformedURLException e) {
+                        throw new UtilsException(e);
+                    } catch (XmlBuilderException e) {
+                        throw new UtilsException(e);
+                    } catch (IOException e) {
+                        throw new UtilsException(e);
+                    }
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+     *
+     * @param definitions
+     * @param paramType
+     * @return
+     */
+
+    public static XmlElement findTypeDefinitionInImports(WsdlDefinitions definitions, QName paramType)throws UtilsException {
+        XmlElement types = definitions.getTypes();
+        XmlElement returnType = null;
+        Iterable<XmlElement> schemas = types.elements(null, WSConstants.SCHEMA_TAG);
+        for (XmlElement schema : schemas) {
+            Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG);
+            for (XmlElement importEle : imports) {
+                String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE);
+                if (null != schemaLocation && !"".equals(schemaLocation)) {
+                    try {
+                        // connect using a url connection
+                        URL url = new URL(schemaLocation);
+                        URLConnection connection = url.openConnection();
+                        connection.connect();
+                        XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection
+                                .getInputStream());
+                        returnType = findTypeInSchema(paramType, importedSchema);
+                        if (returnType != null) {
+                            return returnType;
+                        }
+
+                    } catch (MalformedURLException e) {
+                        throw new UtilsException(e);
+                    } catch (XmlBuilderException e) {
+                        throw new UtilsException(e);
+                    } catch (IOException e) {
+                        throw new UtilsException(e);
+                    }
+                }
+            }
+        }
+        return null;
+
+    }
+
+    private static XmlElement findTypeInSchema(QName paramType, XmlElement schema) {
+        String schemaTargetNamespace = schema.attributeValue(WSConstants.TARGET_NAMESPACE_ATTRIBUTE);
+        if (null != schemaTargetNamespace && schemaTargetNamespace.equals(paramType.getNamespaceURI())) {
+            for (XmlElement complexType : schema.elements(WSConstants.XSD_NS, WSConstants.COMPLEX_TYPE_TAG)) {
+                String complexTypeName = complexType.attributeValue(WSConstants.NAME_ATTRIBUTE);
+                if (complexTypeName.equals(paramType.getLocalPart())) {
+                    return complexType;
+
+                }
+            }
+            for (XmlElement simpleType : schema.elements(WSConstants.XSD_NS, WSConstants.SIMPLE_TYPE_TAG)) {
+                String simpleTypeName = simpleType.attributeValue(WSConstants.NAME_ATTRIBUTE);
+                if (simpleTypeName.equals(paramType.getLocalPart())) {
+                    return simpleType;
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+     * @param wsdl
+     * @return true if the WSDL is AWSDL; false otherwise.
+     */
+    public static boolean isAWSDL(WsdlDefinitions wsdl) {
+        if (wsdl.services().iterator().hasNext()) {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * @param definitions
+     * @return true if the service supports asynchronous invocation; false otherwise;
+     */
+    public static boolean isAsynchronousSupported(WsdlDefinitions definitions) {
+        for (WsdlBinding binding : definitions.bindings()) {
+            XmlElement element = binding.xml().element(WSConstants.USING_ADDRESSING_TAG);
+            if (element != null) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Converts a specified AWSDL to CWSDL using DSC URI.
+     * 
+     * @param definitions
+     *            The specified AWSDL. This will be modified.
+     * @param url
+     *            The URL of the service
+     * @return The CWSDL converted.
+     */
+    public static WsdlDefinitions convertToCWSDL(WsdlDefinitions definitions, URI url) {
+        for (WsdlPortType portType : definitions.portTypes()) {
+            WsdlUtil.createCWSDL(definitions, portType, url);
+        }
+        return definitions;
+    }
+
+    /**
+     * @param uri
+     * @return The URI with "?wsdl" at the end.
+     */
+    public static String appendWSDLQuary(String uri) {
+        URI wsdlURI = appendWSDLQuary(URI.create(uri));
+        return wsdlURI.toString();
+    }
+
+    public static List<XmlNamespace> getNamespaces(XmlElement element) {
+        LinkedList<XmlNamespace> namespaces = new LinkedList<XmlNamespace>();
+        namespaces.add(element.getNamespace());
+        Iterable<XmlAttribute> attributes = element.attributes();
+        for (XmlAttribute xmlAttribute : attributes) {
+            if (xmlAttribute.getNamespace() != null && !namespaces.contains(xmlAttribute.getNamespace())) {
+                namespaces.add(xmlAttribute.getNamespace());
+            }
+            int index = xmlAttribute.getValue().indexOf(':');
+            if (-1 != index) {
+                String prefix = xmlAttribute.getValue().substring(0, index);
+                if (element.lookupNamespaceByPrefix(prefix) != null) {
+                    namespaces.add(element.lookupNamespaceByPrefix(prefix));
+                }
+            }
+        }
+        Iterable children = element.children();
+        for (Object object : children) {
+            if (object instanceof XmlElement) {
+                List<XmlNamespace> newNSs = getNamespaces((XmlElement) object);
+                for (XmlNamespace xmlNamespace : newNSs) {
+                    if (!namespaces.contains(xmlNamespace)) {
+                        namespaces.add(xmlNamespace);
+                    }
+                }
+            }
+        }
+        return namespaces;
+    }
+
+    /**
+     * @param uri
+     * @return The URI with "?wsdl" at the end.
+     */
+    public static URI appendWSDLQuary(URI uri) {
+        if (uri.toString().endsWith("?wsdl")) {
+            logger.warning("URL already has ?wsdl at the end: " + uri.toString());
+            // Don't throw exception to be more error tolerant.
+            return uri;
+        }
+        String path = uri.getPath();
+        if (path == null || path.length() == 0) {
+            uri = uri.resolve("/");
+        }
+        uri = URI.create(uri.toString() + "?wsdl");
+        return uri;
+    }
+
+
+
+    /**
+     * @param valueElement
+     * @return
+     */
+    public static org.xmlpull.v1.builder.XmlElement xmlElement5ToXmlElementv1(XmlElement valueElement) {
+
+        return XmlConstants.BUILDER.parseFragmentFromReader(new StringReader(xsul5.XmlConstants.BUILDER
+                .serializeToStringPretty(valueElement)));
+    }
+
+    /**
+     *
+     * @param vals
+     * @param <T>
+     * @return
+     */
+    public static <T extends Object> T getfirst(Iterable<T> vals) {
+        for (T class1 : vals) {
+            return class1;
+        }
+        throw new RuntimeException("Iterator empty");
+
+    }
+
+    /**
+     * @param serviceSchema
+     */
+    public static void print(XmlElement serviceSchema) {
+        System.out.println(xsul5.XmlConstants.BUILDER.serializeToStringPretty(serviceSchema));
+    }
+
+    /**
+     * @param workflowID
+     * @return
+     */
+    public static String findWorkflowName(URI workflowID) {
+        String[] splits = workflowID.toString().split("/");
+        return splits[splits.length - 1];
+
+    }
+
+    /**
+     * 
+     * @param element
+     * @param name
+     * @param oldValue
+     * @param newValue
+     */
+    public static void replaceAttributeValue(XmlElement element, String name, String oldValue, String newValue) {
+        XmlAttribute attribute = element.attribute(name);
+        if (null != attribute && oldValue.equals(attribute.getValue())) {
+            element.removeAttribute(attribute);
+            element.setAttributeValue(name, newValue);
+        }
+        Iterable iterator = element.children();
+        for (Object object : iterator) {
+            if (object instanceof XmlElement) {
+                replaceAttributeValue((XmlElement) object, name, oldValue, newValue);
+            }
+        }
+
+    }
+
+    public static boolean attributeExist(XmlElement element, String name, String value) {
+        XmlAttribute attribute = element.attribute(name);
+        if (null != attribute && value.equals(attribute.getValue())) {
+            return true;
+        }
+        Iterable iterator = element.children();
+        boolean ret = false;
+        for (Object object : iterator) {
+            if (object instanceof XmlElement) {
+                ret = ret || attributeExist((XmlElement) object, name, value);
+            }
+        }
+        return ret;
+
+    }
+
+}
\ No newline at end of file

Added: incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/XMLUtil.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/XMLUtil.java?rev=1166871&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/XMLUtil.java (added)
+++ incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/XMLUtil.java Thu Sep  8 19:33:59 2011
@@ -0,0 +1,494 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.common.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedList;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.airavata.common.exception.UtilsException;
+import org.apache.xmlbeans.XmlError;
+import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlOptions;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Text;
+import org.xml.sax.SAXException;
+import org.xmlpull.infoset.XmlDocument;
+import org.xmlpull.infoset.XmlElement;
+import org.xmlpull.infoset.XmlNamespace;
+import org.xmlpull.mxp1.MXParserFactory;
+import org.xmlpull.mxp1_serializer.MXSerializer;
+
+import xsul5.MLogger;
+
+public class XMLUtil {
+
+    /**
+     * The XML builder for XPP5
+     */
+    public static final org.xmlpull.infoset.XmlInfosetBuilder BUILDER = org.xmlpull.infoset.XmlInfosetBuilder
+            .newInstance();
+
+    /**
+     * The XML builder for XPP3.
+     */
+    public static final org.xmlpull.v1.builder.XmlInfosetBuilder BUILDER3 = org.xmlpull.v1.builder.XmlInfosetBuilder
+            .newInstance(new MXParserFactory());
+
+    private static final MLogger logger = MLogger.getLogger();
+
+    private final static String PROPERTY_SERIALIZER_INDENTATION = "http://xmlpull.org/v1/doc/properties.html#serializer-indentation";
+
+    private final static String INDENT = "    ";
+
+    /**
+     * Parses a specified string and returns the XmlElement (XPP3).
+     * 
+     * @param string
+     * @return The XmlElement (XPP3) parsed.
+     */
+    public static org.xmlpull.v1.builder.XmlElement stringToXmlElement3(String string) {
+        return BUILDER3.parseFragmentFromReader(new StringReader(string));
+    }
+
+    /**
+     * Parses a specified string and returns the XmlElement (XPP5).
+     * 
+     * @param string
+     * @return The XmlElement (XPP5) parsed.
+     */
+    public static org.xmlpull.infoset.XmlElement stringToXmlElement(String string) {
+        XmlDocument document = BUILDER.parseString(string);
+        org.xmlpull.infoset.XmlElement element = document.getDocumentElement();
+        return element;
+    }
+
+    /**
+     * Converts a specified XmlElement (XPP3) to the XmlElement (XPP5).
+     * 
+     * @param element
+     * @return The XmlElement (XPP5) converted.
+     */
+    public static org.xmlpull.infoset.XmlElement xmlElement3ToXmlElement5(org.xmlpull.v1.builder.XmlElement element) {
+        String string = xmlElementToString(element);
+        return stringToXmlElement(string);
+    }
+
+    /**
+     * Converts a specified XmlElement (XPP5) to the XmlElement (XPP3).
+     * 
+     * @param element
+     * @return The XmlElement (XPP3) converted.
+     */
+    public static org.xmlpull.v1.builder.XmlElement xmlElement5ToXmlElement3(org.xmlpull.infoset.XmlElement element) {
+        String string = xmlElementToString(element);
+        return stringToXmlElement3(string);
+    }
+
+    /**
+     * Returns the XML string of a specified XmlElement.
+     * 
+     * @param element
+     *            The specified XmlElement
+     * @return The XML string
+     */
+    public static String xmlElementToString(org.xmlpull.v1.builder.XmlElement element) {
+        MXSerializer serializer = new MXSerializer();
+        StringWriter writer = new StringWriter();
+        serializer.setOutput(writer);
+        serializer.setProperty(PROPERTY_SERIALIZER_INDENTATION, INDENT);
+        BUILDER3.serialize(element, serializer);
+        String xmlText = writer.toString();
+        return xmlText;
+    }
+
+    /**
+     * Returns the XML string as a specified XmlElement (XPP5).
+     * 
+     * @param element
+     *            The specified XmlElement
+     * @return The XML string
+     */
+    public static String xmlElementToString(org.xmlpull.infoset.XmlElement element) {
+        String string;
+        if (element == null) {
+            string = "";
+        } else {
+            string = BUILDER.serializeToStringPretty(element);
+        }
+        return string;
+    }
+
+    /**
+     * Converts a specified XPP5 XML element to a DOM element under a specified document.
+     * 
+     * @param xppElement
+     * @param document
+     * @return The converted DOM element.
+     */
+    public static Element xppElementToDomElement(org.xmlpull.infoset.XmlElement xppElement, Document document) {
+        Element domElement = document.createElement(xppElement.getName());
+
+        for (org.xmlpull.infoset.XmlNamespace namespace : xppElement.namespaces()) {
+            logger.finest("namespace: " + namespace);
+        }
+
+        for (org.xmlpull.infoset.XmlAttribute attribute : xppElement.attributes()) {
+            domElement.setAttribute(attribute.getName(), attribute.getValue());
+        }
+
+        for (Object object : xppElement.children()) {
+            if (object instanceof org.xmlpull.infoset.XmlElement) {
+                domElement.appendChild(xppElementToDomElement((org.xmlpull.infoset.XmlElement) object, document));
+            } else if (object instanceof String) {
+                Text text = document.createTextNode((String) object);
+                domElement.appendChild(text);
+            } else {
+                logger.finest("object.getClass(): " + object.getClass());
+            }
+        }
+        return domElement;
+    }
+
+    /**
+     * @param definitions3
+     * @return The WsdlDefinitions (XSUL5)
+     */
+    @Deprecated
+    public static xsul5.wsdl.WsdlDefinitions wsdlDefinitions3ToWsdlDefintions5(xsul.wsdl.WsdlDefinitions definitions3) {
+        return WSDLUtil.wsdlDefinitions3ToWsdlDefintions5(definitions3);
+    }
+
+    /**
+     * @param definitions5
+     * @return The WsdlDefinitions (XSUL3)
+     */
+    @Deprecated
+    public static xsul.wsdl.WsdlDefinitions wsdlDefinitions5ToWsdlDefintions3(xsul5.wsdl.WsdlDefinitions definitions5) {
+        return WSDLUtil.wsdlDefinitions5ToWsdlDefintions3(definitions5);
+    }
+
+    /**
+     * Converts a specified XPP3 XML element to a DOM element under a specified document.
+     * 
+     * @param xppElement
+     * @param document
+     * @return The converted DOM element.
+     */
+    public static Element xppElementToDomElement(org.xmlpull.v1.builder.XmlElement xppElement, Document document) {
+        Element domElement = document.createElement(xppElement.getName());
+
+        Iterator nsIt = xppElement.namespaces();
+        while (nsIt.hasNext()) {
+            org.xmlpull.v1.builder.XmlNamespace namespace = (org.xmlpull.v1.builder.XmlNamespace) nsIt.next();
+            logger.finest("namespace: " + namespace);
+            // TODO
+        }
+
+        Iterator attrIt = xppElement.attributes();
+        while (attrIt.hasNext()) {
+            org.xmlpull.v1.builder.XmlAttribute attribute = (org.xmlpull.v1.builder.XmlAttribute) attrIt.next();
+            // TODO namespace
+            domElement.setAttribute(attribute.getName(), attribute.getValue());
+        }
+
+        Iterator elementIt = xppElement.children();
+        while (elementIt.hasNext()) {
+            Object object = elementIt.next();
+            if (object instanceof org.xmlpull.v1.builder.XmlElement) {
+                domElement.appendChild(xppElementToDomElement((org.xmlpull.v1.builder.XmlElement) object, document));
+            } else if (object instanceof String) {
+                Text text = document.createTextNode((String) object);
+                domElement.appendChild(text);
+            } else {
+                logger.finest("object.getClass(): " + object.getClass());
+            }
+        }
+        return domElement;
+    }
+
+    /**
+     * @param element
+     * @return The cloned XmlElement.
+     */
+    public static org.xmlpull.infoset.XmlElement deepClone(org.xmlpull.infoset.XmlElement element)throws UtilsException{
+        try {
+            XmlElement clonedElement = element.clone();
+            clonedElement.setParent(null);
+            return clonedElement;
+        } catch (CloneNotSupportedException e) {
+            // This should not happen because we don't put any special Objects.
+            throw new UtilsException(e);
+        }
+    }
+
+    /**
+     * Saves a specified XmlElement to a specified file.
+     * 
+     * @param element
+     * @param file
+     * @throws IOException
+     */
+    public static void saveXML(org.xmlpull.infoset.XmlElement element, File file) throws IOException {
+        XmlDocument document = BUILDER.newDocument();
+        document.setDocumentElement(element);
+        String xmlText = BUILDER.serializeToStringPretty(document);
+        IOUtil.writeToFile(xmlText, file);
+    }
+
+    /**
+     * Saves a specified XmlElement to a specified file.
+     * 
+     * @param element
+     * @param file
+     * @throws IOException
+     */
+    public static void saveXML(org.xmlpull.v1.builder.XmlElement element, File file) throws IOException {
+        saveXML(xmlElement3ToXmlElement5(element), file);
+    }
+
+    /**
+     * @param file
+     * @return The XmlElement in the document.
+     * @throws IOException
+     */
+    public static org.xmlpull.infoset.XmlElement loadXML(File file) throws IOException {
+        String xmlText = IOUtil.readFileToString(file);
+        XmlDocument document = BUILDER.parseString(xmlText);
+        return document.getDocumentElement();
+    }
+
+    /**
+     * @param string
+     * @return true if the specified string is XML, false otherwise
+     */
+    public static boolean isXML(String string) {
+        try {
+            stringToXmlElement(string);
+            return true;
+        } catch (RuntimeException e) {
+            logger.caught(e);
+            return false;
+        }
+    }
+
+    /**
+     * Validates a specified XmlObject along with logging errors if any.
+     * 
+     * @param xmlObject
+     */
+    public static void validate(XmlObject xmlObject) throws UtilsException {
+        XmlOptions validateOptions = new XmlOptions();
+        ArrayList errorList = new ArrayList();
+        validateOptions.setErrorListener(errorList);
+
+        boolean isValid = xmlObject.validate(validateOptions);
+        if (isValid) {
+            // Valid
+            return;
+        }
+
+        // Error
+        StringBuilder stringBuilder = new StringBuilder();
+        for (int i = 0; i < errorList.size(); i++) {
+            XmlError error = (XmlError) errorList.get(i);
+            logger.warning("Message: " + error.getMessage());
+            logger.warning("Location of invalid XML: " + error.getCursorLocation().xmlText());
+            stringBuilder.append("Message:" + error.getMessage());
+            stringBuilder.append("Location of invalid XML: " + error.getCursorLocation().xmlText());
+        }
+        throw new UtilsException(stringBuilder.toString());
+    }
+
+    /**
+     * Returns the local part of a specified QName.
+     * 
+     * @param qname
+     *            the specified QName in string, e.g. ns:value
+     * @return the local part of the QName, e.g. value
+     */
+    public static String getLocalPartOfQName(String qname) {
+        int index = qname.indexOf(':');
+        if (index < 0) {
+            return qname;
+        } else {
+            return qname.substring(index + 1);
+        }
+    }
+
+    /**
+     * Returns the prefix of a specified QName.
+     * 
+     * @param qname
+     *            the specified QName in string, e.g. ns:value
+     * @return the prefix of the QName, e.g. ns
+     */
+    public static String getPrefixOfQName(String qname) {
+        int index = qname.indexOf(':');
+        if (index < 0) {
+            return null;
+        } else {
+            return qname.substring(0, index);
+        }
+    }
+
+    /**
+     * @param prefixCandidate
+     * @param uri
+     * @param alwaysUseSuffix
+     * @param element
+     * @return The namespace found or declared.
+     */
+    public static XmlNamespace declareNamespaceIfNecessary(String prefixCandidate, String uri, boolean alwaysUseSuffix,
+            XmlElement element) {
+        XmlNamespace namespace = element.lookupNamespaceByName(uri);
+        if (namespace == null) {
+            return declareNamespace(prefixCandidate, uri, alwaysUseSuffix, element);
+        } else {
+            return namespace;
+        }
+    }
+
+    /**
+     * @param prefixCandidate
+     * @param uri
+     * @param alwaysUseSuffix
+     * @param element
+     * @return The namespace declared.
+     */
+    public static XmlNamespace declareNamespace(String prefixCandidate, String uri, boolean alwaysUseSuffix,
+            XmlElement element) {
+        if (prefixCandidate == null || prefixCandidate.length() == 0) {
+            prefixCandidate = "a";
+        }
+        String prefix = prefixCandidate;
+        if (alwaysUseSuffix) {
+            prefix += "0";
+        }
+        if (element.lookupNamespaceByPrefix(prefix) != null) {
+            int i = 1;
+            prefix = prefixCandidate + i;
+            while (element.lookupNamespaceByPrefix(prefix) != null) {
+                i++;
+            }
+        }
+        XmlNamespace namespace = element.declareNamespace(prefix, uri);
+        return namespace;
+    }
+
+    /**
+     *
+     * @param xml
+     * @param name
+     */
+    public static void removeElements(XmlElement xml, String name) {
+
+        Iterable<XmlElement> removeElements = xml.elements(null, name);
+        LinkedList<XmlElement> removeList = new LinkedList<XmlElement>();
+        for (XmlElement xmlElement : removeElements) {
+            removeList.add(xmlElement);
+        }
+        for (XmlElement xmlElement : removeList) {
+            xml.removeChild(xmlElement);
+        }
+        Iterable children = xml.children();
+        for (Object object : children) {
+            if (object instanceof XmlElement) {
+                XmlElement element = (XmlElement) object;
+                removeElements(element, name);
+            }
+        }
+    }
+
+    /**
+     * @param url
+     * @return Document
+     */
+    public static Document retrievalXMLDocFromUrl(String url) {
+        try {
+            URL xmlUrl = new URL(url);
+            InputStream in = xmlUrl.openStream();
+            Document ret = null;
+            DocumentBuilderFactory domFactory;
+            DocumentBuilder builder;
+
+            domFactory = DocumentBuilderFactory.newInstance();
+            domFactory.setValidating(false);
+            domFactory.setNamespaceAware(false);
+            builder = domFactory.newDocumentBuilder();
+
+            ret = builder.parse(in);
+
+            return ret;
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } catch (ParserConfigurationException e) {
+            e.printStackTrace();
+        } catch (SAXException e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
+    /**
+     * @param url
+     * @return Document
+     */
+    public static Document retrievalXMLDocForParse(String url) {
+        try {
+            URL xmlUrl = new URL(url);
+            InputStream in = xmlUrl.openStream();
+            DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
+            xmlFact.setNamespaceAware(true);
+            DocumentBuilder builder = xmlFact.newDocumentBuilder();
+            Document doc = builder.parse(in);
+
+            return doc;
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } catch (ParserConfigurationException e) {
+            e.printStackTrace();
+        } catch (SAXException e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
+}
\ No newline at end of file

Added: incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/XmlFormatter.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/XmlFormatter.java?rev=1166871&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/XmlFormatter.java (added)
+++ incubator/airavata/trunk/modules/commons/utils/src/main/java/org/apache/airavata/common/utils/XmlFormatter.java Thu Sep  8 19:33:59 2011
@@ -0,0 +1,82 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.common.utils;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.xml.serialize.OutputFormat;
+import org.apache.xml.serialize.XMLSerializer;
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ * Pretty-prints xml, supplied as a string.
+ * <p/>
+ * eg. <code>
+ * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
+ * </code>
+ */
+public class XmlFormatter {
+
+    /**
+     * @param unformattedXml
+     * @return formattedXml
+     */
+    public static String format(String unformattedXml) {
+        try {
+            final Document document = parseXmlFile(unformattedXml);
+            OutputFormat format = new OutputFormat(document);
+            format.setLineWidth(65);
+            format.setIndenting(true);
+            format.setIndent(2);
+            Writer out = new StringWriter();
+            XMLSerializer serializer = new XMLSerializer(out, format);
+            serializer.serialize(document);
+            return out.toString();
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private static Document parseXmlFile(String in) {
+        try {
+            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            InputSource is = new InputSource(new StringReader(in));
+            return db.parse(is);
+        } catch (ParserConfigurationException e) {
+            throw new RuntimeException(e);
+        } catch (SAXException e) {
+            throw new RuntimeException(e);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+}
\ No newline at end of file