Java regular expression examples

Tengo un problema con unos servicios web que me devuelven mal el xml. Cree un Interceptor para ponerlo bien. Pero es que son tan cachondos los del lado del servidor que la premisa me va cambiando.
Error inicial: axis2ns104:Server
Siguiente vez: axis2ns105:Server

Solucion Regex:

.*(axis2ns)(\d{4}|\d{3}|\d{2}|\d{1}):Server.*"
.*(axis2ns)([0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1}):Server.*
	public static final String EXAMPLE_TEST = "<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode xmlns:axis2ns105="http://schemas.xmlsoap.org/soap/envelope/">" +
			"axis2ns105:Server</faultcode><faultstring>0229 La petición ya ha sido tramitada</faultstring><detail><Atributos xmlns="http://www.map.es/scsp/esquemas/V2/soapfaultatributos"><IdPeticion>00000207</IdPeticion><TimeStamp>2014-02-24T16:37:04.967+01:00</TimeStamp><NumElementos>1</NumElementos><Estado><CodigoEstado>0229</CodigoEstado><CodigoEstadoSecundario /><LiteralError>La petición ya ha sido tramitada</LiteralError><TiempoEstimadoRespuesta>0</TiempoEstimadoRespuesta></Estado><CodCertificado>CDISFWS01</CodCertificado></Atributos></detail></soapenv:Fault></soapenv:Body></soapenv:Envelope>";
	public static void main(String[] args) {
		System.out.println(EXAMPLE_TEST.matches(".*(axis2ns)(\d{4}|\d{3}|\d{2}|\d{1}):Server.*"));
		System.out.println(EXAMPLE_TEST.matches(".*(axis2ns)([0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1}):Server.*"));
	}

Asi es como queda en mi interceptor. Con el codigo de antes simplemente sabemos que existe una coincidencia. Pero no sabemos cual. Con el siguiente codigo, descubrimos las posibles coincidencias y transformamos la cadena.

	if((currentEnvelope != null) && (currentEnvelope.matches(".*(axis2ns)(\d{4}|\d{3}|\d{2}|\d{1}):Server.*"))){
		Pattern MY_PATTERN = Pattern.compile("(axis2ns)(\d{4}|\d{3}|\d{2}|\d{1})");
		Matcher m = MY_PATTERN.matcher(currentEnvelope);
		String res = "";
		while (m.find()) {
			res= m.group();
		}
		if( ! res.equals("")){
			LOGGER.info("Debido a un bug en el mensaje SoapFault de este servicio. se procede a cambiar la etiqueta ""+res+"" por "soapenv".");
			currentEnvelope = currentEnvelope.replace(res, "soapenv");
		}
	}

Mirando por internet Vogella tiene un error, desde mi punto de vista. En un momento de su tutorial dice que

 // returns true if the string contains a number less then 300
  public boolean isLessThenThreeHundret(String s){
    return s.matches("[^0-9]*[12]?[0-9]{1,2}[^0-9]*");
  }

yo digo que eso esta mal que es:

 // returns true if the string contains a number less then 300
  public boolean isLessThenThreeHundret(String s){
    return s.matches("[012]{1}[0-9]{1,2}");
  }
Java regular expression examples

Document to String y viceversa

	public static String documentToString(Document doc) {
		return sourceToString(new DOMSource(doc));
	}
	
	public static String sourceToString(Source source) {
		try {
			StringWriter sw = new StringWriter();
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
			transformer.setOutputProperty(OutputKeys.METHOD, "xml");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

			transformer.transform(source, new StreamResult(sw));
			return sw.toString();
		} catch (Exception ex) {
			throw new RuntimeException("Error converting to String", ex);
		}
	}
	
	public static Source toSource(String xml){
		return new StreamSource(new StringReader(xml));
	}
	
	public static Document stringToDocument(String xml) {
		Document doc = null;
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			doc = db.parse( new InputSource( new StringReader( xml ) ) ); 
		} catch (Exception e) {
			throw new RuntimeException("Error converting to String", e);
		}
		return doc;
	}
	
	public static Source stringToDocumentToSource(String xml) {
		return new DOMSource(stringToDocument(xml));
	}
	
	public static Source stringToSource(String xml) {
		return new StreamSource(new StringReader(xml));
	}

¿Porque es importante el Source?. A la hora de realizar el marshall/unmarshall de objetos y strings JAXB siempre quiere datos de tipo Source.

	public Object xmlToObject(String xml) throws Exception {
		ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(getEncoding()));
		StreamSource source = new StreamSource(bais);
		return xmlToObject(source);
	}
	
	public Object xmlToObject(Source source) throws Exception {
		return jaxb2Marshaller.unmarshal(source);
	}
Document to String y viceversa

Listar el classpath

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.IOUtils;

import es.depontevedra.soap.interoperabilidad.identidad.services.reflections.ClassSearchUtils;
import es.depontevedra.soap.interoperabilidad.identidad.services.reflections.ReflectionsLibrary;

/*
 * Utilizacion para comprobar qué clases y librerias se cargan en el classpath de la aplicación.
 * Cuando tienes problemas con librerias, puedes listar el classpath y comprobar las clases que se llaman igual
 * o las librerias que son similares pero con diferentes versiones.
 * 
 *  	<dependencies>
		<!-- listar classpath -->
		<dependency>
			<groupId>org.reflections</groupId>
			<artifactId>reflections</artifactId>
			<version>0.9.9-RC1</version>
		</dependency>
		<!-- fin -->
 */
public class ClasspathLog {
	
	private static final String FILE_PATH = "./repository/deployment/server/webapps/STRATOS_ROOT/wso2Classpath.log";

	public static void listaLibrerias() throws IOException {
		FileOutputStream fop = null;
		try{
			IOUtils.write("======================================================n", fop);
			File file = new File(FILE_PATH);
			fop = new FileOutputStream(file);
			List<?> list = ClassSearchUtils.searchClassPath("", "");
			for(Object object: list){
				if(null != object){
					IOUtils.write(object.toString() + "n", fop);
				}
			}
			IOUtils.write("======================================================n", fop);
			IOUtils.write(ReflectionsLibrary.getAllResources(""), fop);
			IOUtils.write("======================================================n", fop);
			IOUtils.write(ReflectionsLibrary.getAllClasses(""), fop);
			IOUtils.write("======================================================n", fop);	
		}finally{
			if(fop != null) IOUtils.closeQuietly(fop);
		}
	}
}
public class ReflectionsLibrary {
	
	public static String getAllResources(String packageStr){
		String str = "";
		Reflections reflections = new Reflections(new ConfigurationBuilder()
			.setUrls(ClasspathHelper.forPackage(packageStr))
			.setScanners(new ResourcesScanner()));

		Store store= reflections.getStore();
		str += "============= Existen " + store.getValuesCount() + ", elementos.n";
		str = print(str, store);
		
		return str;
	}
	
	public static String getAllClasses(String packageStr){
		String str = "";
		
		Reflections reflections = new Reflections(new ConfigurationBuilder()
			.setUrls(ClasspathHelper.forPackage(packageStr))
			.setScanners(new ClassScanner()));

		Store store= reflections.getStore();
		str += "============= Existen " + store.getValuesCount() + ", clases.n";
		str = print(str, store);
		
		return str;
	}

	private static String print(String str, Store store) {
		Map<String, Multimap<String, String>> map = store.getStoreMap();
		for(Entry<String, Multimap<String, String>> entry: map.entrySet()){
			str += "==================";
			Multimap<String, String> value = entry.getValue();
			for( Entry<String, String> entry2: value.entries()){
				str += entry2.getValue() + "n";
			}
			str += "==================================================";
		}
		return str;
	}

}
public class ClassScanner extends AbstractScanner{

	@Override public void scan(Object cls) {
		@SuppressWarnings("unchecked")
		final String className = getMetadataAdapter().getClassName(cls);
		if(className != null) getStore().put(className, className);
    }
	

}
package es.depontevedra.soap.interoperabilidad.identidad.services.reflections;

import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Logger;

@SuppressWarnings("rawtypes")
public class ClassSearchUtils {

    private static final Logger log = Logger.getAnonymousLogger();

    /**
     * Classloader to be used to obtain resources from file system.
     */
    private ClassLoader classloader;

    /**
     * List of the resource found in the classpath.
     */
	private ArrayList list;

    /**
     * Extension of the resource to be found in the classpath.
     */
    private String extension;

    private String prefix;

    /**
     * Search for the resource with the extension in the classpath. Method
     * self-instantiate factory for every call to ensure thread safety.
     * @param extension Mandatory extension of the resource. If all resources
     * are required extension should be empty string. Null extension is not
     * allowed and will cause method to fail.
     * @return List of all resources with specified extension.
     */
    @SuppressWarnings("unchecked")
	public static List<Class<?>> searchClassPath(String prefix) {
        return searchClassPath(prefix, ".class");
    }
    /**
     * Search for the resource with the extension in the classpath. Method
     * self-instantiate factory for every call to ensure thread safety.
     * @param extension Mandatory extension of the resource. If all resources
     * are required extension should be empty string. Null extension is not
     * allowed and will cause method to fail.
     * @return List of all resources with specified extension.
     */
    public static List searchClassPath(String prefix, String extension) {
        ClassSearchUtils factory = new ClassSearchUtils();
        factory.prefix = prefix;
        return factory.find(extension);
    }

    /**
     * Search for the resource with the extension in the classpath.
     * @param extension Mandatory extension of the resource. If all resources
     * are required extension should be empty string. Null extension is not
     * allowed and will cause method to fail.
     * @return List of all resources with specified extension.
     */
    @SuppressWarnings("unchecked")
	private List<Class<?>> find(String extension) {
        this.extension = extension;
        this.list = new ArrayList();
        this.classloader = this.getClass().getClassLoader();
        String classpath = System.getProperty("java.class.path");

        try {
            Method method =
                this.classloader.getClass().getMethod("getClassPath", (Class<?>) null);
            if (method != null) {
                classpath = (String) method.invoke(this.classloader, (Object) null);
            }
        } catch (Exception e) {
            // ignore
        }
        if (classpath == null) {
            classpath = System.getProperty("java.class.path");
        }

        StringTokenizer tokenizer =
            new StringTokenizer(classpath, File.pathSeparator);
        String token;
        File dir;
        String name;
        while (tokenizer.hasMoreTokens()) {
            token = tokenizer.nextToken();
            dir = new File(token);
            if (dir.isDirectory()) {
                lookInDirectory("", dir);
            }
            if (dir.isFile()) {
                name = dir.getName().toLowerCase();
                if (name.endsWith(".zip") || name.endsWith(".jar")) {
                    this.lookInArchive(dir);
                }
            }
        }
        return this.list;
    }

    /**
     * @param name Name of to parent directories in java class notation (dot
     * separator)
     * @param dir Directory to be searched for classes.
     */
    @SuppressWarnings("unchecked")
	private void lookInDirectory(String name, File dir) {
        log.fine( "Looking in directory [" + dir.getName() + "].");
        File[] files = dir.listFiles();
        File file;
        String fileName;
        final int size = files.length;
        for (int i = 0; i < size; i++) {
            file = files[i];
            fileName = file.getName();
            if (file.isFile()
                && fileName.toLowerCase().endsWith(this.extension)) {
                try {
                    if (this.extension.equalsIgnoreCase(".class")) {
                        fileName = fileName.substring(0, fileName.length() - 6);
                        // filter ignored resources
                        if (!(name + fileName).startsWith(this.prefix)) {
                            continue;
                        }

                        log.fine(
                            "Found class: [" + name + fileName + "].");
                        this.list.add(Class.forName(name + fileName));
                    } else {
                        this.list.add(
                            this.classloader.getResource(
                                name.replace('.', File.separatorChar)
                                    + fileName));
                    }
                } catch (ClassNotFoundException e) {
                    // ignore
                } catch (NoClassDefFoundError e) {
                        //ignore too
                } catch (ExceptionInInitializerError e) {
                    if (e.getCause() instanceof HeadlessException) {
                        // running in headless env ... ignore 
                    } else {
                        throw e;
                    }
                }
            }
            // search recursively.
            // I don't like that but we will see how it will work.
            if (file.isDirectory()) {
                lookInDirectory(name + fileName + ".", file);
            }
        }

    }

    /**
     * Search archive files for required resource.
     * @param archive Jar or zip to be searched for classes or other resources.
     */
    @SuppressWarnings("unchecked")
	private void lookInArchive(File archive) {
        log.fine(
            "Looking in archive ["
                + archive.getName()
                + "] for extension ["
                + this.extension
                + "].");
        JarFile jarFile = null;
        try {
            jarFile = new JarFile(archive);
        } catch (IOException e) {
            log.warning(
                "Non fatal error. Unable to read jar item.");
            return;
        }
        Enumeration entries = jarFile.entries();
        JarEntry entry;
        String entryName;
        while (entries.hasMoreElements()) {
            entry = (JarEntry) entries.nextElement();
            entryName = entry.getName();
            if (entryName.toLowerCase().endsWith(this.extension)) {
                try {
                    if (this.extension.equalsIgnoreCase(".class")) {
                        // convert name into java classloader notation
                        entryName =
                            entryName.substring(0, entryName.length() - 6);
                        entryName = entryName.replace('/', '.');

                        // filter ignored resources
                        if (!entryName.startsWith(this.prefix)) {
                            continue;
                        }

                        log.fine(
                            "Found class: [" + entryName + "]. ");
                        this.list.add(Class.forName(entryName));
                    } else {
                        this.list.add(this.classloader.getResource(entryName));
                        log.fine(
                            "Found appropriate resource with name ["
                                + entryName
                                + "]. Resource instance:"
                                + this.classloader.getResource(entryName));
                    }
                } catch (Throwable e) {
                    // ignore
                    log.warning(
                        "Unable to load resource ["
                            + entryName
                            + "] form file ["
                            + archive.getAbsolutePath()
                            + "].");
                }
            }
        }
    }
    
    public static void main(String[] args) {
    	List list = ClassSearchUtils.searchClassPath("", "");
    	for(Object object: list){
    		System.out.println(object);
    	}
	}
}

fuente

Listar el classpath

JAXB y CXF

Recientemente me encuentro en proyectos donde por un lado tengo unos XSD que he transformado en clases y un servicio web que usa estas clases para comunicarse.

En mi modulo de generacion de clases, para poder realizar el marshal/unmarshal he usado spring con OXM. Mediante configuracion he indicado a Spring, donde estaban los XSD, para las validaciones y donde estaban las clases que tenia que tener en el contexto. Estos son los application context:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/util 
		http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
        
    <import resource="classpath*:spring/spring-xsd-marshall.xml" />
    
	<util:constant id="m_jaxbFormattedOutput" static-field="javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT" />
	<util:constant id="m_jaxbEncoding" static-field="javax.xml.bind.Marshaller.JAXB_ENCODING" />

	<util:map id="marshallerPropertiesMap">
		<entry key-ref="m_jaxbEncoding" value="UTF-8" />
		<entry key-ref="m_jaxbFormattedOutput">
			<value type="java.lang.Boolean">true</value>
		</entry>
	</util:map>

	<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" >
		<property name="marshallerProperties" ref="marshallerPropertiesMap" />
		<property name="classesToBeBound" ref="classesToBeBoundList" />
		<property name="schemas" ref="schemasList" />
	</bean>
	
	<bean id="xmlB64Binder" class ="es.depontevedra.soa.xsd.spi.XmlB64Binder">
		<property name="encoding" value="UTF-8" />
	</bean>
	
	<bean id="xmlBinder" class ="es.depontevedra.soa.xsd.spi.XmlBinder">
		<property name="encoding" value="UTF-8" />
	</bean>

</beans>

Cada modulo en el que necesite serializar objetos, tiene que desarrollar su propio fichero de configuracion de serializacion para Spring:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/util 
		http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
<!-- ESTE ES EL FICHERO QUE CONTIENE LAS CLASES QUE REALIZARAN LA SERIALIZACION -->
<!-- <import resource="classpath*:spring/spring-xsd.xml" /> -->
<!-- EN ESTE FICHERO SOLO SE INDICA LO QUE SE QUIERE SERIALIZAR -->
    
    <util:list id="schemasList">
		<value>classpath:wsdl/confirmacion-peticion.xsd</value>
		<value>classpath:wsdl/datos-especificos.xsd</value>
		<value>classpath:wsdl/peticion.xsd</value>
		<value>classpath:wsdl/respuesta.xsd</value>
		<value>classpath:wsdl/soapfaultatributos.xsd</value>
		<value>classpath:wsdl/solicitud-respuesta.xsd</value>
	</util:list>
	
	<util:list id="classesToBeBoundList">
		<value>es.map.scsp.esquemas.datosespecificos.DatosDireccionType</value>
		<value>es.map.scsp.esquemas.datosespecificos.DatosEspecificos</value>
		<value>es.map.scsp.esquemas.datosespecificos.DatosNacimiento</value>
		<value>es.map.scsp.esquemas.datosespecificos.DatosNacimientoType</value>
		<value>es.map.scsp.esquemas.datosespecificos.DatosTitular</value>
		<value>es.map.scsp.esquemas.datosespecificos.EstadoResultado</value>
		<value>es.map.scsp.esquemas.datosespecificos.Organizacion</value>
		<value>es.map.scsp.esquemas.datosespecificos.SolicitanteDatos</value>
		<value>es.map.scsp.esquemas.datosespecificos.Solicitud</value>
		
		<value>es.map.scsp.esquemas.v2.confirmacionpeticion.Atributos</value>
		<value>es.map.scsp.esquemas.v2.confirmacionpeticion.ConfirmacionPeticion</value>
		<value>es.map.scsp.esquemas.v2.confirmacionpeticion.Estado</value>
		
		<value>es.map.scsp.esquemas.v2.peticion.Atributos</value>
		<value>es.map.scsp.esquemas.v2.peticion.DatosGenericos</value>
		<value>es.map.scsp.esquemas.v2.peticion.Emisor</value>
		<value>es.map.scsp.esquemas.v2.peticion.Estado</value>
		<value>es.map.scsp.esquemas.v2.peticion.Funcionario</value>
		<value>es.map.scsp.esquemas.v2.peticion.Peticion</value>
		<value>es.map.scsp.esquemas.v2.peticion.Solicitante</value>
		<value>es.map.scsp.esquemas.v2.peticion.Solicitudes</value>
		<value>es.map.scsp.esquemas.v2.peticion.SolicitudTransmision</value>
		<value>es.map.scsp.esquemas.v2.peticion.Titular</value>
		<value>es.map.scsp.esquemas.v2.peticion.Transmision</value>
		
		<value>es.map.scsp.esquemas.v2.respuesta.Atributos</value>
		<value>es.map.scsp.esquemas.v2.respuesta.DatosGenericos</value>
		<value>es.map.scsp.esquemas.v2.respuesta.Emisor</value>
		<value>es.map.scsp.esquemas.v2.respuesta.Estado</value>
		<value>es.map.scsp.esquemas.v2.respuesta.Funcionario</value>
		<value>es.map.scsp.esquemas.v2.respuesta.Respuesta</value>
		<value>es.map.scsp.esquemas.v2.respuesta.Solicitante</value>
		<value>es.map.scsp.esquemas.v2.respuesta.Titular</value>
		<value>es.map.scsp.esquemas.v2.respuesta.Transmision</value>
		<value>es.map.scsp.esquemas.v2.respuesta.TransmisionDatos</value>
		<value>es.map.scsp.esquemas.v2.respuesta.Transmisiones</value>
		
		<value>es.map.scsp.esquemas.v2.soapfaultatributos.Atributos</value>
		<value>es.map.scsp.esquemas.v2.soapfaultatributos.Estado</value>

		<value>es.map.scsp.esquemas.v2.solicitudrespuesta.Atributos</value>
		<value>es.map.scsp.esquemas.v2.solicitudrespuesta.Estado</value>
		<value>es.map.scsp.esquemas.v2.solicitudrespuesta.SolicitudRespuesta</value>
	</util:list>

</beans>

Tengo una clase en este modulo que es la encargada de realizar el Marshall/UnMarshall:

package es.depontevedra.soa.xsd.spi;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.beans.factory.annotation.Autowired;

import es.depontevedra.soa.xsd.XmlObjectBinder;

public abstract class MarshalUnmarshal implements XmlObjectBinder {

	private String encoding;

	@Autowired
	private org.springframework.oxm.jaxb.Jaxb2Marshaller jaxb2Marshaller;

	public MarshalUnmarshal() {
		super();
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public Object xmlToObject(String xml) throws Exception {
		ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(getEncoding()));
		StreamSource source = new StreamSource(bais);
		return jaxb2Marshaller.unmarshal(source);
	}

	public String objectToXml(Object object) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		StreamResult result = new StreamResult(baos);
		jaxb2Marshaller.marshal(object, result);
		String xml = baos.toString(getEncoding()); 
		return xml;
	}

}
package es.depontevedra.soa.xsd.spi;

public class XmlBinder extends MarshalUnmarshal {

	public XmlBinder() {}
	
	public Object unmarshal(String xml) throws Exception {
		return xmlToObject(xml);
	}
	
	public String marshal(Object object) throws Exception {
		return objectToXml(object);
	}

}

Tambien esta la clase es.depontevedra.soa.xsd.spi.XmlB64Binder que hace lo mismo que XmlBinder pero los String son en BASE64.

Bien pues todo esto se puede hacer mucho mas sencillo:

	public String objectToXml(Object object) throws Exception {
		JAXBContext jc = JAXBContext.newInstance( "es.map.scsp.esquemas.v2.peticion:es.map.scsp.esquemas.datosespecificos:es.map.scsp.esquemas.v2.respuesta.Respuesta" );
		Marshaller marshaller = jc.createMarshaller();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		marshaller.marshal(peticion, baos);
		
		return new String( baos.toByteArray(), "UTF-8" );
	}

	public Object xmlToObject(String xml) throws Exception {
		JAXBContext jc = JAXBContext.newInstance( "es.map.scsp.esquemas.v2.peticion:es.map.scsp.esquemas.datosespecificos:es.map.scsp.esquemas.v2.respuesta.Respuesta" );
		Unmarshaller unmarshaller = jc.createUnmarshaller();
		ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(getEncoding()));
		StreamSource source = new StreamSource(bais);
		return (Peticion) unmarshaller.unmarshal(source);
	}

Nota que los paquetes del contexto estan separados por dos puntos.

Habria que añadir mas codigo para las validaciones, generar clases, interfaces para las llamadas…
Cada vez que quieras realizar una accion puedes llamar a estos metodos de manera estatica, pasando por parametros los paquetes.

JAXB y CXF

Android, debug en el telefono

1.- En el movil:
1.1- Activar las opiones de desarrollador: Ajustes > Sobre el telefono y pulsa siete veces sobre «Build number». Vuelves a la anterior pantalla y ya tienes las Opciones de desarrollo.
1.2- Ajustes > Opciones de desarrollo.
1.2.1- Como trabajo con OSX, no tengo que instalar ningun driver para el USB.
1.2.2- Ajustes > Opciones de desarrollo > Depuracion > Depuracion por USB.

A partir de ahora cuando estes desarrollando y conectes el mvl, te aparecera una pantalla en el movil indicando si aceptas una clave RSA del ordenador al que te has enchufado.

2.- Si te has descargado el sdk, si te vas a la carpeta sdk/platform-tools puedes ejecutar el siguiente comando para comprobar que el dispositivo esta activo.

mbp-de-jose:platform-tools jmprieto$ pwd
/Users/jmprieto/dev/bin/android/adt-bundle-mac-x86_64-20131030/sdk/platform-tools
mbp-de-jose:platform-tools jmprieto$ ./adb devices
List of devices attached 
01a1b785da4f8c88	device

3.- En el fichero AndroidManifest.xml, añade a mano android:debuggable=»true» dentro de la etiqueta «application».

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      android:versionCode="1"
      android:versionName="1.0" package="net.pp.jm.android.curso.app3">
    <uses-sdk android:minSdkVersion="3" />

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
        <activity android:name=".Actividad"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Es muy importante que no publiques ninguna aplicacion con este cambio.

4.- Para ejecutar la aplicacion, sobre la carpeta de la aplicacion/proyecto boton derecho «Run As» >»Run Configurations» > Target > Launch on all compatible devices/ADV’s. Selecciona «Active devices».
Debug en los dispositivos activos

Referencias:
Android developer, tools, device. enlace.

Android, debug en el telefono

Gradle y el UTF-8

Estaba haciendo el tutorial de Gradle. Cuando en el primer script: ERROR

$ gradle hello --info
Starting Build
Settings evaluated using empty settings script.
Projects loaded. Root project using build file 'C:Proyectosutilsgradle_tutobuild.gradle'.
Included projects: [root project 'gradle_tuto']
Evaluating root project 'gradle_tuto' using build file 'C:Proyectosutilsgradle_tutobuild.gradle'.
Compiling build file 'C:Proyectosutilsgradle_tutobuild.gradle' using StatementExtractingScriptTransformer.

FAILURE: Build failed with an exception.

* Where:
Build file 'C:Proyectosutilsgradle_tutobuild.gradle' line: 1

* What went wrong:
Could not compile build file 'C:Proyectosutilsgradle_tutobuild.gradle'.
> startup failed:
  build file 'C:Proyectosutilsgradle_tutobuild.gradle': 1: unexpected char: 0xBB @ line 1, column 2.
     task hello << {
      ^

  1 error


* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

BUILD FAILED

Total time: 8.75 secs

Este es el script de Gradle:

task hello << {
println "Hello, World!"
}

Cual era el problema. Pues que tengo por defecto en Notepad++ UTF. Lo he cambiado a Codificacion/ANSI y funciona.

$ gradle -q hello
Hello, World!

En este blog una descripcion del porque.

Gradle y el UTF-8