Por ejemplo, al hacer el maven install del siguiente proyecto: https://svn.apache.org/repos/asf/cxf/tags/cxf-2.7.7/distribution/src/main/release/samples/sts/
Buscar este blog
miércoles, 18 de febrero de 2015
Maven WSDLException: faultCode=PARSER_ERROR: java.lang.RuntimeException: Cannot create a secure XMLInputFactory
Este error se produce al intentar generar una aplicación que contiene servicios CXF.
Por ejemplo, al hacer el maven install del siguiente proyecto: https://svn.apache.org/repos/asf/cxf/tags/cxf-2.7.7/distribution/src/main/release/samples/sts/
Por ejemplo, al hacer el maven install del siguiente proyecto: https://svn.apache.org/repos/asf/cxf/tags/cxf-2.7.7/distribution/src/main/release/samples/sts/
sábado, 24 de enero de 2015
Java Servlet bypassFilter - Filter exclude path pattern - Filter wrapper
Servlet Filters are very useful components to check request parameters, authentication status, resource authorization, etc. But the main problem they have (at least one very big) is that you only can specify which URLs (patterns) are processed by de filter, but not which you don't want to apply.
For example, with this configuration the filter will intercept all '/secure/' and '/services/' paths.
But, what I need is to have a filter which intercepts all paths, except some ones.
I found this great solution in gitHub, https://gist.github.com/superbob/5005291, developed by this superbob guy ;), but it was quite specific. So I decided to enhanced it and give some more config options.
The idea is the same, one filter, wrapper, wich has inside a inner filter. The wrapper filter is responsible of instanciate and initialize the inner filter.
There is a special class called FilterWrapperCondition which evaluate if the inner filter should be called or not. This is in fact an interface, and the particular implementations are configured with the filter config of the wrapper.
These are the main classes. The complete code is in github: https://github.com/evazquezma/JEE6/tree/master/wrapperFilter
WrapperFilter
ExclusionFilterWrapperCondition
web.xml
For example, with this configuration the filter will intercept all '/secure/' and '/services/' paths.
<filter> <filter-name>OneFilter</filter-name> <filter-class>com.MyFilterClass</filter-class> </filter> <filter-mapping> <filter-name>OneFilter</filter-name> <url-pattern>/secure/**</url-pattern> <url-pattern>/services/**</url-pattern> </filter-mapping>
But, what I need is to have a filter which intercepts all paths, except some ones.
I found this great solution in gitHub, https://gist.github.com/superbob/5005291, developed by this superbob guy ;), but it was quite specific. So I decided to enhanced it and give some more config options.
The idea is the same, one filter, wrapper, wich has inside a inner filter. The wrapper filter is responsible of instanciate and initialize the inner filter.
There is a special class called FilterWrapperCondition which evaluate if the inner filter should be called or not. This is in fact an interface, and the particular implementations are configured with the filter config of the wrapper.
These are the main classes. The complete code is in github: https://github.com/evazquezma/JEE6/tree/master/wrapperFilter
WrapperFilter
package es.pruebas.jee6.filter.wrapper;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This filter wrapp a inner filter and decides when invoke it.
*
* If you are using Spring, you can get Spring beans by using "WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());".
* In this way you will not need instanciate class by hand.
*
* @author SISIFO
*
*/
public class WrapperFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(WrapperFilter.class);
private static final String FILTER_PARAM_INNER_FILTER_CLASS = "wrapper.param.filterClass";
private static final String FILTER_PARAM_WRAPPER_CONDITION_CLASS = "wrapper.param.wrapperConditionClass";
private Filter innerFilter;
private FilterWrapperCondition filterWrapperCondition;
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
LOGGER.info("Initializing filter inhibitor");
this.innerFilter = createAndInitInnerFilter(filterConfig);
this.filterWrapperCondition = createAndInitFilterWrapperCondition(filterConfig);
LOGGER.info("Inhibitor engaged !");
}
private Filter createAndInitInnerFilter(final FilterConfig filterConfig) throws ServletException {
Filter filter = null;
try {
LOGGER.info("Loading inner filter: "+ filterConfig.getInitParameter(FILTER_PARAM_INNER_FILTER_CLASS));
filter = (Filter) Class.forName(filterConfig.getInitParameter(FILTER_PARAM_INNER_FILTER_CLASS)).newInstance();
} catch (InstantiationException | RuntimeException | ClassNotFoundException | IllegalAccessException e) {
LOGGER.error("exception while creating inner filter", e);
throw new RuntimeException(e);
}
filter.init(filterConfig);
return filter;
}
private FilterWrapperCondition createAndInitFilterWrapperCondition(FilterConfig filterConfig) {
FilterWrapperCondition wrapperCondition = null;
try {
LOGGER.info("Loading filter condition: "+ filterConfig.getInitParameter(FILTER_PARAM_WRAPPER_CONDITION_CLASS));
wrapperCondition = (FilterWrapperCondition) Class.forName(filterConfig.getInitParameter(FILTER_PARAM_WRAPPER_CONDITION_CLASS)).newInstance();
} catch (InstantiationException | RuntimeException | ClassNotFoundException | IllegalAccessException e) {
LOGGER.error("exception while creating filter condition", e);
throw new RuntimeException(e);
}
wrapperCondition.init(filterConfig);
return wrapperCondition;
}
@Override
public void destroy() {
LOGGER.info("Destroying wrapper filter");
LOGGER.info("Destroying inner filter");
innerFilter.destroy();
LOGGER.info("Destroyed !");
}
@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
if (filterWrapperCondition.allowInnerFilterCall(req, res)) {
innerFilter.doFilter(req, res, chain);
} else {
chain.doFilter(req, res);
}
}
}
ExclusionFilterWrapperCondition
package es.pruebas.jee6.filter.wrapper;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
* Example basic implementation.
*
* @author SISIFO
*
*/
public class ExclusionFilterWrapperCondition implements FilterWrapperCondition {
private static final String PARAM_EXCLUSION_PREFIX = "wrapper.exclusionFilterWrapperCondition.param";
private String[] exclusionsRules;
@Override
public void init(FilterConfig filterConfig) {
exclusionsRules = filterConfig.getInitParameter(PARAM_EXCLUSION_PREFIX).split(",");
for (int i=0; i<exclusionsRules.length; i++) {
exclusionsRules[i] = filterConfig.getServletContext().getContextPath() + exclusionsRules[i].trim();
}
}
@Override
public boolean allowInnerFilterCall(ServletRequest req, ServletResponse res) {
HttpServletRequest httpReq = (HttpServletRequest) req;
for (String pattern : exclusionsRules) {
if (httpReq.getRequestURI().startsWith(pattern)) {
return false;
}
}
return true;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>wrapperFilter</display-name>
<filter>
<display-name>wrapperFilter</display-name>
<filter-name>wrapperFilter</filter-name>
<filter-class>es.pruebas.jee6.filter.wrapper.WrapperFilter</filter-class>
<init-param>
<param-name>wrapper.param.filterClass</param-name>
<param-value>es.pruebas.jee6.filter.SayHelloFilter</param-value>
</init-param>
<init-param>
<param-name>wrapper.param.wrapperConditionClass</param-name>
<param-value>es.pruebas.jee6.filter.wrapper.ExclusionFilterWrapperCondition</param-value>
</init-param>
<init-param>
<param-name>wrapper.exclusionFilterWrapperCondition.param</param-name>
<param-value>
/dontCallFilter/,
/neitherInThisURL/
</param-value>
</init-param>
<!-- Any other params for the inner filter -->
<!-- .... -->
</filter>
<filter-mapping>
<filter-name>wrapperFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<display-name>SayWorldFilter</display-name>
<filter-name>SayWorldFilter</filter-name>
<filter-class>es.pruebas.jee6.filter.SayWorldFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SayWorldFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
martes, 20 de enero de 2015
JSP, TAG - Remove whitespaces
Para eliminar los espacios en blanco generados dentro de una JSP:
Dentro del web.xml
O, dentro de cada JSP:
Para eliminar los espacios en blanco generados dentro de un TAG:
Dentro del web.xml
<jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <trim-directive-whitespaces>true</trim-directive-whitespaces> </jsp-property-group> </jsp-config>
O, dentro de cada JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
Para eliminar los espacios en blanco generados dentro de un TAG:
<%@ tag pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
sábado, 17 de enero de 2015
JBoss, Apache mod-cluster - Configure SSL to read client certificates
Update:
Tras un tiempo trabajando con este tipo de configuración he visto que no es la más adecuada. He creado una nueva entrada donde se especifica un mejor solución. Se puede consultar aquí: http://trabajosdesisifo.blogspot.com.es/2015/04/jboss-modcluster-ssl-windows.html
Tras un tiempo trabajando con este tipo de configuración he visto que no es la más adecuada. He creado una nueva entrada donde se especifica un mejor solución. Se puede consultar aquí: http://trabajosdesisifo.blogspot.com.es/2015/04/jboss-modcluster-ssl-windows.html
Instalación y configuración de SQLServer 2008 - Transacciones distribuidas
Sofware necesario
Se emplearán las siguientes versiones:
- Windows Server 2008 R2
- SQLServer 2008 R2 - Express - SP2
- SQL Server JDBC Driver versión 4
En la página de descarga de SQL server hay que seleccionar el idioma de instalación de Windows Server, así como la arquitectura (x86 o x64). De los distintos paquetes a descargar, se optará por la versión ADV (Advance) que ya también trae el Management Studio.
Instalación y Configuración
Instalar SQLServer con todas las opciones por defecto. Tardará aproximadamente 30 minutos.
Crear usuario (login)
Para crear un usuario:
- Acceder al Management Studio empleando la autenticación de windows.
- Dentro de la instancia, acceder a Security > Logins, y pulsar sobre nuevo.
- Crear un nuevo usuario indicando login y password (marcar la opción de usar contraseña deshabilitando las comprobaciones de seguridad)
- En la opción de User Mapping, asignarle las bases de datos que correspondan. En principio se le añadirá master
Una vez creado se cierra sesión, y se vuelve a conectar seleccionando autenticación de SQL Server e indicando el login y password.
Permitir conexiones desde otras máquinas
Para que ese usuario se pueda conectar desde otra máquina, hay que configurar una serie de parámetros tanto en el PC como en el servicio:
- Permitir conexiones remotas
En el Management Studio, una vez logeado, pulsar sobre la instancia para ver sus propiedades. Seleccionar la pestaña de connections y asegurarse de que está marcado el check de "Allow remote connections to this server"
- Permitir autentiación con usuario y contraseña
En el Management Studio, una vez logeado, pulsar sobre la instancia para ver sus propiedades. Seleccionar la pestaña de Security y, dentro del grupo de Server authentication, marcar "SQL Server and Windows Authentication mode" - Activar protocolo TCP/IP
Ejecutar el programa "Sql Server Configuration Manager". Está dentro del directorio de Configuration Tools en el menú de inicio del SQL Server 2008 R2.
Ir a SQL Server Network Configuration > Protocols for SQLEXPRESS. Activar el protocolo TCP/IP.
Dentro de ese mismo, ir a propiedades, pestaña IP Addresses. Ahí hay que asegurarse de que existe un grupo IP con la dirección IP de la máquina cliente, que esté Active y Enabled, y con el puerto 1433.
En el grupo de IPAll, asignar el puerto 1433 a TCP port.
Finalmente, reiniciar el servicio. - Desactivar firewall de windows
En la máquina servidor lo más rápido es deshabilitar el firewall de windows, o abrir específicamente el puerto TCP 1433.
Para comprobar que el fierewall no interfiere, hacer un ping desde la máquina cliente al servidor y ver que se obtiene respuesta.
Permitir transacciones distribuidas
El servicio MS DTC debe estar marcado como Automático en el Administrador de servicios para asegurarse de que esté en ejecución cuando se inicia el servicio de SQL Server. Para habilitar MS DTC para transacciones XA, debe seguir estos pasos:
- Inicio > Administrative Tools > Component Services
- Seleccionar Component Services > Computers > My Compunter > Distributed Transaction Coordinator > Local DTC > properties
- Dentro de las propiedades > pestaña Security > Enable XA Transactions
- Reiniciar el servicio SQL Server (SQLEXPRESS)
Descargar SQL Server JDBC Driver.
- Valen las versiones 3 y 4.
- Se descarga:
- Microsoft JDBC Driver 4.0 for SQL Server
- Sistemas operativos: Linux, Unix, Windows 7, Windows Server 2008 R2, Windows Server 2012, Windows Vista
- Versiones SQL Server:
- Microsoft® SQL Server® 2012
- Microsoft® SQL Server® 2008 R2
- Microsoft® SQL Server® 2008
- Microsoft® SQL Server® 2005
- Microsoft® SQL Azure
- Copiar la extensión de procedimientos almacenados en el directorio del SQL Server:
- En la carpeta del driver descargado ir a enu > xa > x64 > sqljdbc_xa.dll
- Copiar el fichero en C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\Binn
Esta dll no existía antes.
- Reiniciar el servicio SQL Server (SQLEXPRESS)
Instalar los procedimientos almacenados extendendidos que vienen con el driver:
- En la carpeta del driver descargado ir a enu > xa > xa_install.sql
- Abrir y ejecutar ese archivo desde el Management Studio:
- Crea los procedimientos almacenados. Si ya existieran, primero los borrar
- Crea un nuevo rol y le asigna permisos sobre esos procedimientos
- Opcionalmente, se podrían indicar los usuarios a los que darles ese rol, si no, se hace más tarde manualmente
Asignar a un usuario el rol SqlJDBCXAUser en la tabla base de datos master:
- Desde el Management Studio, navegar a Security > Logins en el panel lateral, y pulsar sobre las propiedades del usuario
- Ir a User Mapping y seleccionar la base de datos master. En la parte inferior, asignar el rol correspondiente.
También se puede hacer ejectuando el siguiente script (en este 'xumco-java' es el nombre del usuario de la conexión):
Asginar rol
USE master GO EXEC sp_addrolemember [SqlJDBCXAUser], 'xumco-java' |
Suscribirse a:
Entradas (Atom)