### Eclipse Workspace Patch 1.0
#P appCatalogAndGazetteerClient
Index: src/es/gva/cit/catalog/csw/parsers/CSWConstants.java
===================================================================
--- src/es/gva/cit/catalog/csw/parsers/CSWConstants.java	(revision 38883)
+++ src/es/gva/cit/catalog/csw/parsers/CSWConstants.java	(working copy)
@@ -67,6 +67,10 @@
 	public static final String OPERATIONS_METADATA= "OperationsMetadata";
 	public static final String SERVICE_TYPE_VERSION = "ServiceTypeVersion";
 	
+	// Capabilities 2.0.1
+	public static final String VERSION_2_0_2 = "2.0.2";
+	public static final String CONSTRAINT_VERSION_2_0_2 = "1.1.0";
+	
 	//Service identification
 	public static final String TITLE = "Title";	
 	public static final String ABSTRACT = "Abstract";
Index: src/es/gva/cit/catalog/csw/drivers/CSWCatalogServiceDriver.java
===================================================================
--- src/es/gva/cit/catalog/csw/drivers/CSWCatalogServiceDriver.java	(revision 38883)
+++ src/es/gva/cit/catalog/csw/drivers/CSWCatalogServiceDriver.java	(working copy)
@@ -45,6 +45,8 @@
 import java.net.URL;
 import java.util.Collection;
 
+import org.apache.log4j.Logger;
+
 import com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable;
 
 import es.gva.cit.catalog.csw.drivers.profiles.CSWAbstractProfile;
@@ -121,6 +123,7 @@
 					firstRecord);
 		} catch (NotSupportedVersionException e) {
 			//This exception never will be thrown
+			Logger.getLogger(this.getClass()).error("Unsupported protocol version", e);
 		}           	
 		
 		if (nodes == null) 
Index: src/es/gva/cit/catalog/csw/messages/CSWMessagesFactory.java
===================================================================
--- src/es/gva/cit/catalog/csw/messages/CSWMessagesFactory.java	(revision 38883)
+++ src/es/gva/cit/catalog/csw/messages/CSWMessagesFactory.java	(working copy)
@@ -65,6 +65,7 @@
 		messages.put(CSWConstants.VERSION_0_9_0, CSWMessages0_9_0.class);
 		messages.put(CSWConstants.VERSION_2_0_0, CSWMessages2_0_0.class);
 		messages.put(CSWConstants.VERSION_2_0_1, CSWMessages2_0_1.class);
+		messages.put(CSWConstants.VERSION_2_0_2, CSWMessages2_0_2.class);
 	}
 	
 	/**
Index: src/es/gva/cit/catalog/csw/messages/CSWAbstractMessages.java
===================================================================
--- src/es/gva/cit/catalog/csw/messages/CSWAbstractMessages.java	(revision 38883)
+++ src/es/gva/cit/catalog/csw/messages/CSWAbstractMessages.java	(working copy)
@@ -130,9 +130,9 @@
 				":" + CSWConstants.CSW_GET_RECORDS);
 		buffer.append(" " + CSWConstants.CSW_SERVICE + "=\"" + ServerData.SERVER_SUBTYPE_CATALOG_CSW + "\" ");
 		buffer.append(CSWConstants.CSW_VERSION + "=\"" + capabilities.getVersion() + "\" ");
-		buffer.append(CatalogConstants.XML_NS + "=\"" +CSWConstants.CSW_NAMESPACE_URI + "\" ");
+		buffer.append(CatalogConstants.XML_NS + "=\"" + getCswNamespace() + "\" ");
 		buffer.append(CatalogConstants.XML_NS + ":" + CSWConstants.CSW_NAMESPACE + 
-				"=\"" + CSWConstants.CSW_NAMESPACE_URI + "\" ");
+				"=\"" + getCswNamespace() + "\" ");
 		buffer.append(CatalogConstants.XML_NS + ":" + CSWConstants.OGC_NAMESPACE + 
 				"=\"" + CSWConstants.OGC_NAMESPACE_URI + "\" ");
 		buffer.append(CatalogConstants.XML_NS + ":" + CSWConstants.GML_NAMESPACE + 
@@ -155,19 +155,22 @@
 	}
 
 	/**
-	 * Returns a common reslut type if the getCapabilities doesn't have
-	 * one. Sometimes it works.
+	 * Returns a common result type if the getCapabilities doesn't have
+	 * one. If several result types are available, prefer "results" type.
+	 * Otherwise, return the first available one. If none is declared, return
+	 * "results" type, which sometimes works.
 	 * 
 	 * 
 	 * @return Just one String
 	 * @param resultType The array of result types parsed.
 	 */
 	protected String getResultType(String[] resultType) {        
-		if (resultType == null)
+		if (resultType == null || resultType.length==0)
 			return "results";
-
 		for (int i=0 ; i<resultType.length ; i++){
-
+			if (resultType[i].toLowerCase().equals("results")) {
+				return resultType[i];
+			}
 		}
 		return resultType[0];
 	} 
@@ -338,5 +341,9 @@
 			return false;
 
 		return true; 
-	} 
+	}
+	
+	protected String getCswNamespace() {
+		return CSWConstants.CSW_NAMESPACE_URI;
+	}
 }
Index: src/es/gva/cit/catalog/csw/messages/CSWMessages2_0_2.java
===================================================================
--- src/es/gva/cit/catalog/csw/messages/CSWMessages2_0_2.java	(revision 0)
+++ src/es/gva/cit/catalog/csw/messages/CSWMessages2_0_2.java	(revision 0)
@@ -0,0 +1,77 @@
+package es.gva.cit.catalog.csw.messages;
+
+import com.iver.utiles.swing.jcomboServer.ServerData;
+
+import es.gva.cit.catalog.csw.drivers.profiles.CSWAbstractProfile;
+import es.gva.cit.catalog.csw.parsers.CSWConstants;
+import es.gva.cit.catalog.utils.CatalogConstants;
+
+/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
+ *
+ * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
+ *
+ * For more information, contact:
+ *
+ *  Generalitat Valenciana
+ *   Conselleria d'Infraestructures i Transport
+ *   Av. Blasco Ibáñez, 50
+ *   46010 VALENCIA
+ *   SPAIN
+ *
+ *      +34 963862235
+ *   gvsig@gva.es
+ *      www.gvsig.gva.es
+ *
+ *    or
+ *
+ *   IVER T.I. S.A
+ *   Salamanca 50
+ *   46005 Valencia
+ *   Spain
+ *
+ *   +34 963163400
+ *   dac@iver.es
+ */
+/* CVS MESSAGES:
+ *
+ * $Id$
+ * $Log$
+ *
+ */
+/**
+ * @author Jorge Piera LLodrá (jorge.piera@iver.es)
+ */
+public class CSWMessages2_0_2 extends CSWAbstractMessages{
+	public static final String CSW_NAMESPACE_URI = "http://www.opengis.net/cat/csw/2.0.2";
+	
+	public CSWMessages2_0_2(CSWAbstractProfile profile) {
+		super(profile);		
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * @see es.gva.cit.catalog.csw.messages.CSWAbstractMessages#getContraintVersion()
+	 */
+	protected String getContraintVersion() {
+		return CSWConstants.CONSTRAINT_VERSION_2_0_2;
+	}
+
+	protected String getCswNamespace() {
+		return CSW_NAMESPACE_URI;
+	}
+
+}
Index: src/es/gva/cit/catalog/protocols/HTTPPostProtocol.java
===================================================================
--- src/es/gva/cit/catalog/protocols/HTTPPostProtocol.java	(revision 38883)
+++ src/es/gva/cit/catalog/protocols/HTTPPostProtocol.java	(working copy)
@@ -40,18 +40,24 @@
 *   dac@iver.es
 */
 package es.gva.cit.catalog.protocols;
+import java.io.BufferedReader;
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.net.HttpURLConnection;
 import java.net.URL;
 import java.util.Collection;
 
+import org.apache.log4j.Logger;
+
+import com.iver.utiles.xml.XMLEncodingUtils;
+
+import es.gva.cit.catalog.metadataxml.XMLNode;
 import es.gva.cit.catalog.metadataxml.XMLTree;
-import es.gva.cit.catalog.utils.Strings;
 
 /**
  * This class implement the HTTP Post protocol.
@@ -61,57 +67,65 @@
  */
 public class HTTPPostProtocol implements IProtocols {
 
+	private static Logger logger = Logger.getLogger(HTTPPostProtocol.class);
 /**
  * @return 
  * @param url 
  * @param message 
  * @param firstRecord 
  */
-    public Collection doQuery(URL url, Object message, int firstRecord) {        
-        String body = (String) message;
-        ByteArrayInputStream output = null;
-            
-        try {
-            HttpURLConnection c = (HttpURLConnection) url.openConnection();
-            
-         c.setRequestProperty("SOAPAction","post");
-         c.setRequestMethod("POST");
-         c.setDoOutput(true);
-         c.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
-                 
-        // Write the request.
-        OutputStreamWriter w =
-            new OutputStreamWriter(c.getOutputStream(), "UTF-8");
-        
-        w.write(body);
-        w.flush();
-              
-        InputStream is = c.getInputStream();
-        byte[] buf = new byte[1024];
-        int len;
-        String str = "";
-        
-        while ((len = is.read(buf)) > 0) {
-            str = str + new String(buf, 0, len);
-        }
-            
-        str = Strings.replace(str,
-				  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
-		  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
-        System.out.println(str);
-        output = new ByteArrayInputStream(str.getBytes());
-            
-        }  catch (IOException e) {
-            // TODO Auto-generated catch block
-            //e.printStackTrace();
-            return null;
-        } 
-        
-        Collection col = new java.util.ArrayList();
-        col.add(XMLTree.xmlToTree(output));
-        return col;            
-    }    
+	public Collection doQuery(URL url, Object message, int firstRecord) {        
+		String body = (String) message;
+		Collection col = new java.util.ArrayList();;
+		try {
+			HttpURLConnection c = (HttpURLConnection) url.openConnection();
 
+			c.setRequestProperty("SOAPAction","post");
+			c.setRequestMethod("POST");
+			c.setDoOutput(true);
+			c.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
+
+			// Write the request.
+			OutputStreamWriter w =
+					new OutputStreamWriter(c.getOutputStream(), "UTF-8");
+
+			w.write(body);
+			w.flush();
+
+			if (logger.isDebugEnabled()) {
+				// read the stream as a String to allow logging it before parsing it to XMLTree object
+				InputStream is = c.getInputStream();
+				char[] buf = new char[1024];
+				int len;
+				StringBuilder strBuilder = new StringBuilder();
+
+				XMLEncodingUtils xmlEnc = new XMLEncodingUtils(is);
+				InputStreamReader isReader = xmlEnc.getReader();
+				String encoding = isReader.getEncoding();
+				BufferedReader bufReader = new BufferedReader(isReader);
+				strBuilder.append(xmlEnc.getBytesRead());
+
+				while ((len = bufReader.read(buf))>0) {
+					strBuilder.append(buf, 0, len);
+				}
+
+				String str = strBuilder.toString();
+				System.out.println(str);
+				ByteArrayInputStream output = new ByteArrayInputStream(str.getBytes(encoding));
+
+				col.add(XMLTree.xmlToTree(output));
+			}
+			else {
+				// when no logging is necessary, we can directly pass the connection IS to the parser, which will deal with encodings
+				XMLNode node = XMLTree.xmlToTree(c.getInputStream());
+				col.add(node);
+			}
+		}  catch (IOException e) {
+			logger.error(e.getMessage(), e);
+		} 
+		return col;            
+	}    
+
     public void doQuery(URL url, Object message, int firstRecord, String fileName) {        
     	String body = (String) message;
     	FileOutputStream output = null;
@@ -147,7 +161,7 @@
     	
     		
     	}  catch (IOException e) {
-    		e.printStackTrace();           
+    		logger.error(e.getMessage(), e);    
     	}           
              
     }    
#P libIverUtiles
Index: src/com/iver/utiles/xml/XMLEncodingUtils.java
===================================================================
--- src/com/iver/utiles/xml/XMLEncodingUtils.java	(revision 38884)
+++ src/com/iver/utiles/xml/XMLEncodingUtils.java	(working copy)
@@ -53,6 +53,7 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
 
 /**
  * A set of methods to detect XML encoding. The class is able to autodetect
@@ -62,7 +63,8 @@
  *
  */
 public class XMLEncodingUtils {
-	InputStream _is;
+	protected InputStream _is;
+	protected String bytesRead = null;
 	
 	/**
 	 * Creates a new XMLEncodingUtils object.
@@ -185,10 +187,152 @@
 		catch (IOException ex) {
 			return null;
 		}
+
 		return enc;
 	}
 	
 	/**
+	 * Gets the encoding of the XML file.
+	 * 
+	 * The following encodings can be detected: UTF-32BE, UTF-32LE,
+	 * UTF-16BE, UTF-16-LE, UTF-8. The rest of the encodings are
+	 * read from the XML header.
+	 * 
+	 * @return Returns the encoding of the XML file, or null if the
+	 * encoding couldn't be correctly detected or read from the XML
+	 * header.
+	 */
+	private String getEncodingSavingBytes() {
+		int srcCount = 0;
+		String enc=null;
+		char[] srcBuf = new char[128];
+		
+		// read four bytes 
+		int chk = 0;
+		try {
+			while (srcCount < 4) {
+				int i = _is.read();
+				if (i == -1)
+					break;
+				chk = (chk << 8) | i;
+				srcBuf[srcCount++] = (char) i;
+			}
+			
+			if (srcCount == 4) {
+				switch (chk) {
+				case 0x00000FEFF :
+					enc = "UTF-32BE";
+					srcCount = 0;
+					break;
+					
+				case 0x0FFFE0000 :
+					enc = "UTF-32LE";
+					srcCount = 0;
+					break;
+					
+				case 0x03c :
+					enc = "UTF-32BE";
+					srcBuf[0] = '<';
+					srcCount = 1;
+					break;
+					
+				case 0x03c000000 :
+					enc = "UTF-32LE";
+					srcBuf[0] = '<';
+					srcCount = 1;
+					break;
+					
+				case 0x0003c003f :
+					enc = "UTF-16BE";
+					srcBuf[0] = '<';
+					srcBuf[1] = '?';
+					srcCount = 2;
+					break;
+					
+				case 0x03c003f00 :
+					enc = "UTF-16LE";
+					srcBuf[0] = '<';
+					srcBuf[1] = '?';
+					srcCount = 2;
+					break;
+					
+				case 0x03c3f786d :
+					while (true) {
+						int i = _is.read();
+						if (i == -1)
+							break;
+						srcBuf[srcCount++] = (char) i;
+						if (i == '>') {
+							String s = new String(srcBuf, 0, srcCount);
+							int i0 = s.indexOf("encoding");
+							if (i0 != -1) {
+								while (s.charAt(i0) != '"'
+									&& s.charAt(i0) != '\'')
+									i0++;
+								char deli = s.charAt(i0++);
+								int i1 = s.indexOf(deli, i0);
+								enc = s.substring(i0, i1);
+							}
+							break;
+						}
+					}
+					
+				default :
+					if ((chk & 0x0ffff0000) == 0x0FEFF0000) {
+						enc = "UTF-16BE";
+						srcBuf[0] =
+							(char) ((srcBuf[2] << 8) | srcBuf[3]);
+						srcCount = 1;
+					}
+					else if ((chk & 0x0ffff0000) == 0x0fffe0000) {
+						enc = "UTF-16LE";
+						srcBuf[0] =
+							(char) ((srcBuf[3] << 8) | srcBuf[2]);
+						srcCount = 1;
+					}
+					else if ((chk & 0x0ffffff00) == 0x0EFBBBF00) {
+						enc = "UTF-8";
+						srcBuf[0] = srcBuf[3];
+						srcCount = 1;
+					}
+				}
+			}
+		}
+		catch (IOException ex) {
+			return null;
+		}
+		
+		if (!enc.equals(Charset.defaultCharset())) {
+			/**
+			 * Now we need to convert back the read chars to bytes, to read
+			 * them again as String using the right character set
+			 */
+			byte[] bytes = new byte[srcBuf.length];
+			for(int i = 0; i < srcBuf.length; i++) {
+				bytes[i] = (byte) srcBuf[i];
+			}
+			try {
+				bytesRead = new String(bytes, 0, srcCount, enc);
+			} catch (UnsupportedEncodingException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+		}
+		return enc;
+	}
+	
+	/**
+	 * Some bytes are read to detect the encoding. Those bytes are not
+	 * available on the reader anymore, so they are stored and made available
+	 * on this method.
+	 * 
+	 * @return
+	 */
+	public String getBytesRead() {
+		return bytesRead;
+	}
+	
+	/**
 	 * Gets an InputStreamReader for the provided XML file.
 	 * The reader uses the right encoding, as specified in
 	 * the XML header (or autodetected). 
@@ -198,7 +342,7 @@
 	 * from the XML header.
 	 */
 	public InputStreamReader getReader() {
-		String encoding = getEncoding();
+		String encoding = getEncodingSavingBytes();
 		if (encoding==null)
 			return null;
 		try {
#P extCatalogAndGazetteer
Index: src/es/gva/cit/gvsig/catalog/loaders/WCSLayerLoader.java
===================================================================
--- src/es/gva/cit/gvsig/catalog/loaders/WCSLayerLoader.java	(revision 38883)
+++ src/es/gva/cit/gvsig/catalog/loaders/WCSLayerLoader.java	(working copy)
@@ -46,7 +46,9 @@
 
 import org.gvsig.i18n.Messages;
 
+import com.iver.andami.PluginServices;
 import com.iver.cit.gvsig.fmap.layers.FLayer;
+import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
 import com.iver.utiles.extensionPoints.ExtensionPoint;
 import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
 
@@ -122,6 +124,10 @@
 		if ((name != null) && (!name.equals(""))){
 			map.put("COVERAGE",name);
 		}
+		BaseView activeView = 
+				(BaseView) PluginServices.getMDIManager().getActiveWindow();
+		map.put("CRS", activeView.getProjection().getAbrev());
+		map.put("FORMAT", "GEOTIFF");
 		return map;
 	}	
 	
