Install brew

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

The command curl with options:
-f, –fail
(HTTP) Fail silently (no output at all) on server errors. This is mostly done to better enable scripts etc to better deal with failed attempts. In normal cases when an HTTP
server fails to deliver a document, it returns an HTML document stating so (which often also describes why and more). This flag will prevent curl from outputting that and
return error 22.

This method is not fail-safe and there are occasions where non-successful response codes will slip through, especially when authentication is involved (response codes 401
and 407).

-L, –location
(HTTP/HTTPS) If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will
make curl redo the request on the new place. If used together with -i, –include or -I, –head, headers from all requested pages will be shown. When authentication is used,
curl only sends its credentials to the initial host. If a redirect takes curl to a different host, it won’t be able to intercept the user+password. See also –location-
trusted on how to change this. You can limit the amount of redirects to follow by using the –max-redirs option.

When curl follows a redirect and the request is not a plain GET (for example POST or PUT), it will do the following request with a GET if the HTTP response was 301, 302, or
303. If the response code was any other 3xx code, curl will re-send the following request using the same unmodified method.

-s, –silent
Silent or quiet mode. Don’t show progress meter or error messages. Makes Curl mute.

-S, –show-error
When used with -s it makes curl show an error message if it fails.

rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
MacBook-Pro-de-Jose:~ jmprieto$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
==> This script will install:
/usr/local/bin/brew
/usr/local/Library/...
/usr/local/share/man/man1/brew.1
==> The following directories will be made group writable:
/usr/local/include
/usr/local/lib
/usr/local/share/man/man3
/usr/local/share/man/man5
/usr/local/share/man/man7
==> The following directories will have their group set to admin:
/usr/local/include
/usr/local/lib

Press RETURN to continue or any other key to abort
==> /usr/bin/sudo /bin/chmod g+rwx /usr/local/include /usr/local/lib /usr/local/share/man/man3 /usr/local/share/man/man5 /usr/local/share/man/man7
Password:
==> /usr/bin/sudo /usr/bin/chgrp admin /usr/local/include /usr/local/lib
==> /usr/bin/sudo /bin/chmod g+rwx /Library/Caches/Homebrew
==> Downloading and installing Homebrew...
remote: Counting objects: 189633, done.
remote: Compressing objects: 100% (51766/51766), done.
remote: Total 189633 (delta 136736), reused 189572 (delta 136694)
Receiving objects: 100% (189633/189633), 37.81 MiB | 2.62 MiB/s, done.
Resolving deltas: 100% (136736/136736), done.
From https://github.com/Homebrew/homebrew
 * [new branch]      master     -> origin/master
HEAD is now at 5d4034d utils: use the $stderr global variable.
==> Installation successful!
==> Next steps
Run `brew doctor` before you install anything
Run `brew help` to get started
Install brew

Get spring context

	    @Autowired  
	    ApplicationContext applicationContext; 

	    // ...
	    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
	    // ...
	    ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
	    // ...
	    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-webservices.xml");//, "spring/spring-ddbb.xml", "spring/spring-properties.xml" );
	    // ...
	    ApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-webservices.xml");//, "spring/spring-ddbb.xml", "spring/spring-properties.xml" );	
	    // ...
Get spring context

Change connection pool at runtime

Retrieve pool data source, from spring context.

	com.mchange.v2.c3p0.ComboPooledDataSource pool = (com.mchange.v2.c3p0.ComboPooledDataSource) context.getBean("idDataSource");
	pool.setJdbcUrl("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=pepe.host.es) (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)))");
	try {
		Connection con = pool.getConnection();
		if(con != null){
 			// TODO check database connection
		}else{
			throw new ConnectionException("Can't load new URL database connection");
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}

The method setJdbcUrl(), do resetPoolManager. The true atribute means that not broke the actual connections.

    public void setJdbcUrl( String jdbcUrl )
    { 
        dmds.setJdbcUrl( jdbcUrl ); 
        this.resetPoolManager( false );
//      System.err.println("setting jdbcUrl: " + jdbcUrl + " [dmds@" + C3P0ImplUtils.identityToken( dmds ) + "]"); 
//      if (jdbcUrl == null)
//      new Exception("*** NULL SETTER ***").printStackTrace();
    }
Change connection pool at runtime

cxf client code

	public static void main(String[] args) {
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.getInInterceptors().add(new LoggingInInterceptor());
		factory.getOutInterceptors().add(new LoggingOutInterceptor());
		factory.setServiceClass(es.depontevedra.soa.facturae.search.FacturaeSearch.class);
		factory.setAddress("http://HOST:PORT/serviciows/servicio?wsdl");
		HelloWorld client = (HelloWorld ) factory.create();
		 
		List<EstadoFactura> reply = client.setHi("Hola");
		System.out.println("Size: " + reply.size());
	}
cxf client code

WSO2 proxy con secuencias

Tenemos un WS que tienen tres operaciones insertar, consultar(query) y actualizar. Cuando damos de alta, no devuelve todos los datos que quisieramos. Muchos de estos datos se encuentran en la consulta. Lo que vamos a hacer, es, en un mismo proxy, realizar dos llamadas: insertar y consultar. Elmensaje de salida sera un compendio de las dos acciones.

1.- Consumidor del BUS de WSO2 realiza una llamada de inserccion.
2.- El proxy realiza la llamada de inserccion, recupera el xml resultante.
3.- El proxy recupera datos del xml resultante.
4.- El proxy crea un nuevo xml de peticion de consulta.
5.- El proxy lanza la consulta y recupera el xml de respuesta.
6.- El proxy recupera datos del xml de respuesta del apartado 5 y 3
7.- El proxy crea y envia un xml de respuesta para la llamada 1.

para todo esto necesitamos dar de alta:
– Endpoint
– Secuencias
– Proxy

Definicion del Endpoint

<endpoint xmlns="http://ws.apache.org/ns/synapse" name="pepe.crud">
   <address uri="http://host:port/pepe/crudws" format="soap11">
      <suspendOnFailure>
         <progressionFactor>1.0</progressionFactor>
      </suspendOnFailure>
      <markForSuspension>
         <retriesBeforeSuspension>0</retriesBeforeSuspension>
         <retryDelay>0</retryDelay>
      </markForSuspension>
   </address>
</endpoint>

Definicion del proxy

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="pepe.crud.proxy"
       transports="https,http"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target faultSequence="fault" endpoint="pepe.crud">
<!-- definimos una secuendcia de entrada. Aqui vamos a indicar que queremos hacer -->
      <inSequence>
<!-- Recuperamos el tipo de operacion que se esta ejecutando. Pueden ser: insertRegisty, updateRegistry, queryRegistry -->
         <property name="Operation" expression="get-property('Action')"/>
<!-- filtramos por el resultado de la operacion. Si es igual al patron regex=".*newRegistry" -->
         <filter source="get-property('Operation')" regex=".*newRegistry">
            <then>
<!-- incvocamos la secuencia añadir -->
               <sequence key="crud.addRegistry.sequence"/>
            </then>
            <else>
<!-- Sino es la operacion de añadir, continuamos por aqui -->
               <send>
<!-- enviamos al WebService la peticion-->
                  <endpoint key="wspepe.crud"/>
               </send>
            </else>
         </filter>
      </inSequence>
<!-- Tratamos la respuesta del servidor -->
      <outSequence>
         <filter source="get-property('Operation')" regex=".*newRegistry">
            <then>
<!-- Si era una operacion de insercion en registro. Realizamos la siguiente secuencia de operaciones. -->
               <sequence key="crud.outRegistry.sequence"/>
            </then>
            <else>
<!-- Sino, logeamos -->
               <log level="full">
                  <property name="Operation" expression="get-property('Operation')"/>
               </log>
            </else>
         </filter>
<!-- enviamos el mensaje a nuestro consumidor -->
         <send buildmessage="true"/>
      </outSequence>
   </target>
   <publishWSDL key="conf:/WSDL/crud.crudws/crudWS.wsdl">
      <resource location="typeapplicant.xsd"
                key="conf:/WSDL/crud.crudws/typeapplicant.xsd"/>
      <resource location="typeattachment.xsd"
                key="conf:/WSDL/crud.crudws/typeattachment.xsd"/>
      <resource location="typecommon.xsd"
                key="conf:/WSDL/crud.crudws/typecommon.xsd"/>
      <resource location="typecrud.xsd"
                key="conf:/WSDL/crud.crudws/typecrud.xsd"/>
   </publishWSDL>
   <description/>
</proxy>

Definicion de las secuencias

<sequence xmlns="http://ws.apache.org/ns/synapse" name="crud.addRegistry.sequence">
<!-- logeamos -->
   <log level="full">
      <property name="SEQ" value="Accediendo a la secuencia ADD"/>
   </log>
   <!-- invocamos a otro endpoint  -->
   <send receive="crud.queryRegistry.sequence" buildmessage="true">
      <endpoint key="pepe.crudws"/>
   </send>
</sequence>
<sequence xmlns="http://ws.apache.org/ns/synapse" name="crud.outRegistry.sequence">
   <log level="full">
      <property name="SEQ" value="Accediendo a la secuencia OUT"/>
      <property xmlns:ns="http://org.apache.synapse/xsd" name="RegistryCode" expression="get-property('RegistryCode')"/>
      <property xmlns:ns="http://org.apache.synapse/xsd" name="IdRegistry" expression="get-property('IdRegistry')"/>
   </log>
</sequence>
<sequence xmlns="http://ws.apache.org/ns/synapse" name="crud.queryRegistry.sequence">
   <!-- Obtenemos los datos del alta del nuevo registro para poder realizar la consulta  -->
   <property name="IdRegistry" expression="$body/ns6:RIResponse/body/idcrud" xmlns:ns2="http://ws.pepe.com/types/attachment" xmlns:ns4="http://ws.pepe.com/types/common" xmlns:ns="http://org.apache.synapse/xsd" xmlns:ns5="http://ws.pepe.com/types/crud" xmlns:ns6="http://ws.pepe.com/crudws" />
   <property name="RegistryCode" expression="$body/ns6:RIResponse/body/crudcode" xmlns:ns2="http://ws.pepe.com/types/attachment" xmlns:ns4="http://ws.pepe.com/types/common" xmlns:ns="http://org.apache.synapse/xsd" xmlns:ns5="http://ws.pepe.com/types/crud" xmlns:ns6="http://ws.pepe.com/crudws" />
   <log level="full">
      <property name="SEQ" value="Accediendo a la secuencia QUERY 1"/>
      <property name="RegistryCode" expression="get-property('RegistryCode')" xmlns:ns="http://org.apache.synapse/xsd" />
      <property name="IdRegistry" expression="get-property('IdRegistry')" xmlns:ns="http://org.apache.synapse/xsd" />
   </log>
   <!-- creamos un xml a medida para enviar al endpoint -->
   <payloadFactory media-type="xml">
      <format>
         <reg:RQRequest xmlns:reg="http://ws.pepe.com/crudws" xmlns:reg1="http://ws.pepe.com/types/crud">
            <header xmlns="" version="0"/>
            <body xmlns="">
               <crudcode>$1</crudcode>
               <input>1</input>
            </body>
         </reg:RQRequest>
      </format>
      <args>
         <arg xmlns:ns="http://org.apache.synapse/xsd" expression="get-property('RegistryCode')" evaluator="xml"/>
      </args>
   </payloadFactory>
   <!-- enviamos el xml creado al endpoint -->
   <header name="Action" value="http://ws.pepe.com/crudws/queryRegistry"/>
   <send>
      <endpoint key="pepe.crudws"/>
   </send>
   <log level="full">
      <property name="SEQ" value="Accediendo a la secuencia QUERY 2"/>
   </log>
</sequence>

Este codigo ha sido elaborado por Rafael Udaondo. Con su permiso he publicado esta entrada.

WSO2 proxy con secuencias

CXF jaxb send string as CData

From http://cxf.547215.n5.nabble.com/CXF-jaxb-send-string-as-CData-td5524523.html
Finalmente no he necesitado usarlo, pero lo guardo por si algún día…

public class CdataWriterInterceptor extends AbstractPhaseInterceptor<Message> { 

        public CdataWriterInterceptor() { 
                super(Phase.PRE_STREAM); 
                addAfter(AttachmentOutInterceptor.class.getName()); 
        } 

        @Override 
        public void handleMessage(Message message) { 
                message.put("disable.outputstream.optimization", Boolean.TRUE); 
                XMLStreamWriter writer = 
StaxUtils.createXMLStreamWriter(message.getContent(OutputStream.class)); 
                message.setContent(XMLStreamWriter.class, new CDataXMLStreamWriter(writer)); 
        } 
} 
public class CDataXMLStreamWriter extends DelegatingXMLStreamWriter { 

        private String currentElementName; 

        public CDataXMLStreamWriter(XMLStreamWriter del) { 
                super(del); 
        } 

        @Override 
        public void writeCharacters(String text) throws XMLStreamException { 
                boolean useCData = checkIfCDATAneededForCurrentElement(); 
                if (useCData) { 
                        System.out.println("WritingCData" + text); 
                        super.writeCData(text); 
                }else { 
                super.writeCharacters(text); 
                } 
        } 

        private boolean checkIfCDATAneededForCurrentElement() { 
                if("MessageBody".equals(currentElementName)) return true; 
                return false; 
        } 

        public void writeStartElement(String prefix, String local, String 
uri) throws XMLStreamException { 
                currentElementName = local; 
                super.writeStartElement(prefix, local, uri); 
        } 
}
CXF jaxb send string as CData

listar librerias java del servidor

Con este comando listamos todas las librerias del servidor y quitamos la ruta, nos quedamos solo con el nombre del jar.

locate *.jar | sed 's/// /g' | sed '/[a-z]*.jar$/ s/[a-z]* //g' | sort

comando locate *.jar : busca todos los ficheros que acaben por .jar
comando sed ‘s/// /g’ : elimina la barra y la sustituye por ‘ ‘(espacio en blanco).
comando sed ‘/[a-z]*.jar$/ s/[a-z]* //g’ : de todas las lineas que cumplan el patrón (la linea termina por .jar) elimina cualquier elemento que contemple el patron (letras seguidas de un espacio). Es decir, elimino la ruta de los ficheros.

listar librerias java del servidor

Java UNICODE

Recientemente el eclipse ha dejado de convertir de UTF-8 a unicode mis properties de i18n. En lugar de intentar arreglarlo (acierto), me he puesto a configurar los acentos y eñes en los distintos lenguajes con los que trabajamos, a mano (error).

Aquí esta la tabla con los caracteres específicos del castellano.

Como no tengo tiempo a mas, aquí pongo unos blogs y tutoriales sobre como maneja Java el UNICODE:

Java UNICODE