Tomcat error APR version 1.1.22

¿Como solucionar este error?

26-mar-2014 9:21:21 org.apache.catalina.core.AprLifecycleListener init
GRAVE: Se encuentra instalada una versión incompatible 1.1.22 de la biblioteca nativa APR de Apache Tomcat, mientras que Tomcat necesita la versión 1.1.24

Para Windows:
te descargas de aqui, la «tomcat-native-1.1.29-win32-bin.zip». Descomprimes y copias en la carpeta tomcat/bin el tcnative-1.dll

En esta pagina dicen como compilar e instalar las fuentes.

Para linux (no lo he probado)

#!/bin/bash
# By Guido Medina
# http://stackoverflow.com/questions/18109722/an-incompatible-version-1-1-22-of-the-apr-based-apache-tomcat-native-library-is

export APR_PATH=/usr/bin/apr-1-config
export JAVA_HOME=/opt/java
export TOMCAT_HOME=/opt/tomcat
export INSTALL_PREFIX=/usr

wajig install libaprutil1-dev make

cd /tmp
rm -Rf tomcat-native-*
tar -zxf $TOMCAT_HOME/bin/tomcat-native.tar.gz
cd /tmp/tomcat-native-*/jni/native

./configure --with-apr=$APR_PATH --with-java-home=$JAVA_HOME --prefix=$INSTALL_PREFIX
make && make install

sacado de sourceforge

Tomcat error APR version 1.1.22

Cliente Socket Web Service

No es lo mas recomendable ni lo mas refactorizable, escalable, etc. Pero quiza si es lo mas rapido.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import javax.net.ssl.SSLSocketFactory;
import sun.misc.BASE64Encoder;

public class SendSMS_Soap {

	public static void main(String[] args) { 
		try { 
			String driver = "DRIVER-DATA; 
			String number = "NUMER-DATA"; 
			String login = "USER:PASS"; 
			String aut = (new BASE64Encoder().encodeBuffer(login.getBytes())).trim(); 

			String mensaje = "Probando envio de SMS con SOAP.."; 

			// ******************* Construimos el XML ******************* 
			String xmldata = //"<?xml version="1.0" encoding="UTF-8"?>"+ 
					"<soap:Envelope " +
					"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" " + 
					// "xmlns:xsd="http://www.w3.org/2001/XMLSchema"  " +
					// "xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"" +
					">"+ 
			"<soap:Body>"+ 
			"<ns2:OPERACION xmlns:ns2="http://www.dominio.es/ruta/schemas">"+ 
			"<Version>1.0</Version>"+ 
			"<Authorization>"+aut+"</Authorization>"+ 
			"<Sender>"+driver+"</Sender>"+ 
			"<Recipients>" + 
			"<To>"+number+"</To>" + 
			"</Recipients>"+ 
			"<SMSText>"+mensaje+"</SMSText>"+ 
			"</ns2:OPERACION>"+ 
			"</soap:Body>"+ 
			"</soap:Envelope>"; 

			System.out.println("Mensaje a enviar: " + xmldata);
			// ******************* Creamos el Socket ******************* 
		
			System.setProperty("javax.net.ssl.trustStore", "trustStore.jks");
			SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
		    Socket s = ssf.createSocket(SERVIDOR, PUERTO);
		    OutputStream outs = s.getOutputStream();
		    InputStream ins = s.getInputStream();

			// ******************* Enviamos la cabecera ******************* 
			BufferedWriter wr = new BufferedWriter(new 
					OutputStreamWriter(outs,"UTF-8")); 

			wr.write("POST /RUTA HTTP/1.1rn"); 
			wr.write("Content-Type: text/xml; charset=utf-8rn"); 
			wr.write("Accept: */*rn"); 
			//wr.write("Authorization: Basic "+aut+"rn"); 
			wr.write("User-Agent: Java/1.7rn"); 
			wr.write("Host: https://SERVIDOR:PUERTO/RUTA" + "rn"); 
			wr.write("Cache-Control: no-cachern"); 
			wr.write("Pragma: no-cachern"); 
			wr.write("SOAPAction: ''rn"); 
			wr.write("Connection: keep-alivern"); 
			wr.write("Content-Length: " + xmldata.length() + "rn"); 
			wr.write("rn"); 

			// ******************* Enviamos el XML ******************* 
			wr.write(xmldata); 
			wr.flush(); 
			
			// ******************* Esperamos respuesta y la sacamos por pantalla ******************* 
			BufferedReader rd = new BufferedReader(new InputStreamReader(ins)); 
			String line; 
			while((line = rd.readLine()) != null){
				System.out.println(line); 
			}

		} catch (Exception e) { 
			System.err.println(e.getMessage()); 
		} 
	}
	
}
Cliente Socket Web Service

Message Queue vs. Web Services?

En este post de stackoverflow. Copio y pego literalmente, para no perder esta informacion.

When you use a web service you have a client and a server:
– If the server fails the client must take responsibility to handle the error.
– When the server is working again the client is responsible of resending it.
– If the server gives a response to the call and the client fails the operation is lost.
– You don’t have contention, that is: if million of clients call a web service on one server in a second, most probably your server will go down.
– You can expect an immediate response from the server, but you can handle asynchronous calls too.
When you use a message queue like RabbitMQ, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:
– If the server fails, the queue persist the message (optionally, even if the machine shutdown).
– When the server is working again, it receives the pending message.
– If the server gives a response to the call and the client fails, if the client didn’t acknowledge the response the message is persisted.
– You have contention, you can decide how many requests are handled by the server (call it worker instead).
– You don’t expect an immediate synchronous response, but you can implement/simulate synchronous calls.
Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.

En programmers.stackexchange.com encontre este otro post buscando cuando implementar RabbitMQ.

When to use Advanced Message Queuing Protocol like RabbitMQ?
Imagine that you have a web service that can accept many requests per second. You also have a accounting system that does a lot of things, one of which is processing the requests coming from the web service.
If you put a queue between the web service and the accounting system, you will be able to:
have less coupling between the two applications, because now both applications have to know the configuration parameters of the queue management system and the name of the queue. Here the catch is that usually you are more likely to move to another server some application than move the queue management system
if you have a lot of requests coming in a short amount of time, the accounting system will be able to process them all anyway
persist some requests if their number becomes really huge
Of course, you could have more complex situations where the number of your applications is much bigger than two and you need to manage the communication between them.
Message Queue vs. Web Services?

Servidor de Mensajes

Basado en Message-oriented middleware (MOM) existe el Message queue. Que implementa los siguientes protocolos: Advanced Message Queuing Protocol (AMQP) y Simple (or Streaming) Text Oriented Message Protocol (STOMP).

Ventajas

(de este blog)
Redundancia – Si tu aplicación falla mientras está procesando alguna petición no te debes preocupar de que esta se pierda para siempre ya que esta estrategia le permite a la cola persistir el mensaje hasta que el mismo sea procesado por completo.
Naturaleza asíncrona – Dependiendo de la manera en que funcione tu sistema puedes necesitar que los mensajes se vayan acumulando para procesarlos en lotes, la cola irá manteniendo tus mensajes para cuando decidas (o programes) su procesamiento.
Garantía de entrega y ordenamiento – Se garantiza que el orden en el que llegan los mensajes será el orden en el que sean procesados, de igual manera un emisor y/o consumidor puede estar seguro de que este ha sido recibido y se procesará una única vez mediante la implementación de intercambio de banderas de reconocimiento.
Disponibilidad – Si parte de tu arquitectura falla, los mensajes no se perderán ya que estos seguirán en la cola hasta que se les indique lo contrario, al mismo tiempo la cola podrá seguir recibiendo mensajes para el procesamiento posterior a la recuperación del sistema.
Elasticidad – En situaciones donde tu sistema pudiera llegar al tope de su capacidad de recepción de peticiones y volverse incapaz de responder por un anormal flujo de mensajes, el hecho de tener una cola o buffer de peticiones permitirá balancear, filtrar y normalizar el flujo, lo cual evitará que tu sistema sea inundado de peticiones que no pueda responder causando perdida de los mismos o incluso el colapso del sistema.
Desacoplamiento – El hecho de tener una capa intermedia de comunicación entre procesos nos da la flexibilidad en la definición de arquitectura de cada uno de ellos de manera separada, mientras cada uno se mantenga alineado a los mismos requerimientos de interfaz que representa la cola de mensajes no abran mayores problemas de compatibilidad ni mucho que cambiar de lado y lado.
Escalabilidad – Por la misma ventaja de desacoplamiento podemos escalar fácilmente nuestro sistema, solo debemos agregar más unidades de procesamiento y el sistema de colas se encargará de balancear la carga entre ellos.

Software
RabbitMQ. get started.

Standar de la industria AMQP.

STOMP

Servidor de Mensajes

Como usar una libreria que no esta en el classpath

package org.wso2.carbon.classloading;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    public static void main(String[] args) throws ClassNotFoundException, MalformedURLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("file:///home/shameera/Desktop/gson-2.2.4.jar")});
        Class gsonClass = urlClassLoader.loadClass("com.google.gson.Gson");
        Constructor constructor = gsonClass.getConstructor();
        Object gsonObj = constructor.newInstance();
        Method method = gsonClass.getMethod("toJson",Object.class);
        Object returnObj =  method.invoke(gsonObj, new Person());
        String jsonString = (String)returnObj;
        System.out.println(jsonString);
    }
}

Visto en….

Como usar una libreria que no esta en el classpath

Creando un script para carbondump

# !/bin/sh
#
# ejemplo de ejecucion:
# sudo ./workerDump.sh 26638
# el numero 26638 se corresponde con el pid del servidor. se puede sacar con 'ps -ef | grep java'
# en este caso habria que buscar el proceso del worker

JAVA_HOME=/usr/lib/jvm/jdk1.7.0_40
export JAVA_HOME
cd /home/wso2/wso2worker/bin/
./carbondump.sh -carbonHome /home/tecnocom/wso2/wso2worker/ -pid $1

hay que tener instalado en el sistema:
zip (sudo apt-get install zip)
– jmap

https://docs.wso2.org/display/AS510/Capturing+the+State+of+the+System+in+Error+Situations

Creando un script para carbondump

Monitorizar con JConsole un Worker de wso2

En algun lado estamos teniendo problemas con los despliegues de las aplicaciones. Es frecuente que al desplegar una aplicacion en los test, halla fallos. Al mirar el log comprobamos que es debido a que no encuentra una determinada clase. Al volver a reiniciar el problema esta solucionado.

Para encontrar un ¿porque? voy a monitorizar el worker.

Tenemos un ELB (balanceador), un manager (administracion web, replicacion app) y dos nodos (worker).

Para monitorizar wso2 tienes que

1.- Ir a wso2/wso2worker/repository/conf/etc/jmx.xml, y hay que sustituir la linea resaltada, por la IP correcta.

<JMX xmlns="http://wso2.org/projects/carbon/jmx.xml">
    <StartRMIServer>true</StartRMIServer>

    <!-- HostName, or Network interface to which this RMI server should be bound -->
    <HostName>IP del servidor</HostName>

    <!--  ${Ports.JMX.RMIRegistryPort} is defined in the Ports section of the carbon.xml-->
    <RMIRegistryPort>${Ports.JMX.RMIRegistryPort}</RMIRegistryPort>

    <!--  ${Ports.JMX.RMIRegistryPort} is defined in the Ports section of the carbon.xml-->
    <RMIServerPort>${Ports.JMX.RMIServerPort}</RMIServerPort>
</JMX>

2.- En la documentación indican que si estas detrás de un Firewall, posiblemente no puedas ver los puertos en los que esta levantado. Es por ello que sugieren que comentes estos puertos. En el fichero de configuración de wso2, ubicado en: wso2/wso2worker/repository/conf/carbon.xml existen los campos:

        <JMX>
            <!--The port RMI registry is exposed-->
            <RMIRegistryPort>9999</RMIRegistryPort>
            <!--The port RMI server should be exposed-->
            <RMIServerPort>11111</RMIServerPort>
        </JMX>

Sugieren comentar primero el RMIServerPort y si no puedes acceder entonces que comentes el RMIRegistryPort.

3.-Arrancas el worker y te vas al log: wso2worker/repository/logs/wso2carbon.log. Esperas a que diga que ya esta levantado y todas las aplicaciones:

TID: [0] [AS] [2014-03-13 10:57:50,742]  INFO {org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl} -  Task service starting in CLUSTERED mode... {org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl}
TID: [0] [AS] [2014-03-13 10:57:50,871]  INFO {org.wso2.carbon.core.init.JMXServerManager} -  JMX Service URL  : service:jmx:rmi://IP-servidor:1/jndi/rmi://IP-servidor:10001/jmxrmi {org.wso2.carbon.core.init.JMXServerManager}
TID: [0] [AS] [2014-03-13 10:57:50,883]  INFO {org.wso2.carbon.core.internal.StartupFinalizerServiceComponent} -  Server           :  Application Server-5.2.0 {org.wso2.carbon.core.internal.StartupFinalizerServiceComponent}
TID: [0] [AS] [2014-03-13 10:57:50,884]  INFO {org.wso2.carbon.core.internal.StartupFinalizerServiceComponent} -  WSO2 Carbon started in 111 sec {org.wso2.carbon.core.internal.StartupFinalizerServiceComponent}
TID: [0] [AS] [2014-03-13 10:57:51,580]  INFO {org.wso2.carbon.ui.internal.CarbonUIServiceComponent} -  Mgt Console URL  : https://IP-servidor:8243/carbon/ {org.wso2.carbon.ui.internal.CarbonUIServiceComponent}

3.- Abre en local, jconsole. En una consola escribe jconsole y espera.
En conexión pon service:jmx:rmi://IP-servidor:1/jndi/rmi://IP-servidor:10001/jmxrmi y el usuario/contraseña del administrador web (admin/admin).

Monitorizar con JConsole un Worker de wso2