/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.cosmos.internal.dr.drs.service.handler.common;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLUtil {
	  public static String xmlToString(Element elem) throws Exception
	  {
	      StringWriter sw = new StringWriter();
	      Transformer serializer = TransformerFactory.newInstance().newTransformer();
          serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
          serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");	      	       //$NON-NLS-1$ //$NON-NLS-2$
	      serializer.transform(new DOMSource(elem), new StreamResult(sw));
	      return sw.toString();
	  }
	  public static Document createDocument(String xml) throws Exception
	  {				  
		  DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
		  Document XMLDoc = builder.parse(new InputSource(new StringReader(xml)));
		  return XMLDoc;
	  }
	  
	  public static Element createElement(QName qname) throws Exception
	  {				  
		  DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
		  Document XMLDoc = builder.newDocument();
		  Element elem = XMLDoc.createElementNS(qname.getNamespaceURI(), qname.getLocalPart());
		  elem.setPrefix(qname.getPrefix());		  
		  return elem;
	  }
	  
	  public static String extractText(Element elem){
		  NodeList list = elem.getChildNodes();
		  String returnStr = null;
		  for (int x = 0; x < list.getLength(); x++){
			  if (list.item(x).getNodeType() == Node.TEXT_NODE){
				  returnStr = list.item(x).getTextContent();
				  break;
			  }
		  }
		  elem.getTextContent();
		  return returnStr;
	  }
}
