Apache RAT

Apache RAT, pertenece al proyecto Apache Creadur. Por lo poco que he entendido, es para agregar licencias a todas tus clases, ficheros. Tal y como esta cualquier clase de Apache, donde aparece arriba del todo, despues de la palabra reservada package, la licencia.
Pero para salir de dudas, me he descargado la libreria y he realizado estas pruebas.

Dentro de la carpeta descomprimida, he creado la carpeta «test». En esta carpeta he metido una clase, que ha resultado ser una interfaz de un web service.
Ubicado en la carpeta descomprimida he ejecutado lo siguiente:

 
E01740@ES-D-04744LT /cygdrive/c/Software/apache-rat-0.10
$ java -jar apache-rat-0.10.jar --help
usage: java rat.report [options] [DIR|TARBALL]
Options
 -A,--addLicense                Add the default licence header to any file
                                with an unknown licence that is not in the
                                exclusion list. By default new files will
                                be created with the licence header, to
                                force the modification of existing files
                                use the --force option.
 -a,--addLicence                Add the default licence header to any file
                                with an unknown licence that is not in the
                                exclusion list. By default new files will
                                be created with the licence header, to
                                force the modification of existing files
                                use the --force option.
 -c,--copyright <arg>           The copyright message to use in the
                                licence headers, usually in the form of
                                "Copyright 2008 Foo"
 -d,--dir                       Used to indicate source when using
                                --exclude
 -E,--exclude-file <fileName>   Excludes files matching regular expression
                                in <file> Note that --dir is required when
                                using this parameter.
 -e,--exclude <expression>      Excludes files matching wildcard
                                <expression>. Note that --dir is required
                                when using this parameter. Allows multiple
                                arguments.
 -f,--force                     Forces any changes in files to be written
                                directly to the source files (i.e. new
                                files are not created)
 -h,--help                      Print help for the Rat command line
                                interface and exit
 -s,--stylesheet <arg>          XSLT stylesheet to use when creating the
                                report.  Not compatible with -x
 -x,--xml                       Output the report in raw XML format.  Not
                                compatible with -s

NOTE:
Rat is really little more than a grep ATM
Rat is also rather memory hungry ATM
Rat is very basic ATM
Rat highlights possible issues
Rat reports require intepretation
Rat often requires some tuning before it runs well against a project
Rat relies on heuristics: it may miss issues

Asi que si no lo he entendido mal. Si ejecuto esto:

 
$ java -jar apache-rat-0.10.jar -d test -a

*****************************************************
Summary
-------
Generated at: 2014-04-30T09:39:43+02:00
Notes: 0
Binaries: 0
Archives: 0
Standards: 1

Apache Licensed: 0
Generated Documents: 0

JavaDocs are generated and so license header is optional
Generated files do not required license headers

1 Unknown Licenses

*******************************

Unapproved licenses:

  test/Cargos.java

*******************************

Archives:

*****************************************************
  Files with Apache License headers will be marked AL
  Binary files (which do not require AL headers) will be marked B
  Compressed archives will be marked A
  Notices, licenses etc will be marked N
 !????? test/Cargos.java

*****************************************************
 Printing headers for files without AL header...


=======================================================================
==test/Cargos.java
=======================================================================
package es.depontevedra.soap.cargows.services;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.BindingType;

@WebService
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@BindingType(javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
public interface Cargos {

        @WebMethod(action="crearCargo")
        public String crearCargo(String xml);

        @WebMethod(action="modificarCargo")
        public String modificarCargo(String xml);

        @WebMethod(action="anularCargo")
        public String anularCargo(String xml);

        @WebMethod(action="consultarCargo")
        public String consultarCargo(String xml);

        @WebMethod(action="consultarConceptos")
        public String consultarConceptos(String xml);

        @WebMethod(action="consultarTributos")
        public String consultarTributos(String xml);

        @WebMethod(action="obtenerRecibo")
        public String obtenerRecibo(String xml);

}

Parece que ha tocado algo en mi clase. La reviso:

 
package es.depontevedra.soap.cargows.services;
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.BindingType;

@WebService
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@BindingType(javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
public interface Cargos {

	@WebMethod(action="crearCargo")
	public String crearCargo(String xml);
	
	@WebMethod(action="modificarCargo")
	public String modificarCargo(String xml);
	
	@WebMethod(action="anularCargo")
	public String anularCargo(String xml);
	
	@WebMethod(action="consultarCargo")
	public String consultarCargo(String xml);
	
	@WebMethod(action="consultarConceptos")
	public String consultarConceptos(String xml);
	
	@WebMethod(action="consultarTributos")
	public String consultarTributos(String xml);
	
	@WebMethod(action="obtenerRecibo")
	public String obtenerRecibo(String xml);
	
}

Me ha gustado eso del copyright que aparece en la ayuda. Voy a probar:

 
$ java -jar apache-rat-0.10.jar -d test -a -c "Jose Manuel Prieto Palacios"

Mi clase se queda:

 
package es.depontevedra.soap.cargows.services;
/*
 *
 * Jose Manuel Prieto Palacios
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.BindingType;

@WebService
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@BindingType(javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
public interface Cargos {

	@WebMethod(action="crearCargo")
	public String crearCargo(String xml);
	
	@WebMethod(action="modificarCargo")
	public String modificarCargo(String xml);
	
	@WebMethod(action="anularCargo")
	public String anularCargo(String xml);
	
	@WebMethod(action="consultarCargo")
	public String consultarCargo(String xml);
	
	@WebMethod(action="consultarConceptos")
	public String consultarConceptos(String xml);
	
	@WebMethod(action="consultarTributos")
	public String consultarTributos(String xml);
	
	@WebMethod(action="obtenerRecibo")
	public String obtenerRecibo(String xml);
	
}

Configurarlo con maven

Uso basico
En la fase de verificacion
Añadiendo un informe cuando el proyecto se compila
Aplicar una licencia personalizada

En maven simplemente se comprueba que todos los ficheros tienen licencia. Usar solo como verificador.

Apache RAT

Java Proxy

Sacado de esta pagina.

Para salir a internet mediante un proxy con Java tienes las siguientes opciones:

HTTP

En la llamada a la JVM, al invocar la clase:

$ java -Dhttp.proxyHost=webcache.mydomain.com MiClaseConMetodoMain
$ java -Dhttp.proxyHost=webcache.mydomain.com -Dhttp.proxyPort=8080 MiClaseConMetodoMain
$ java -Dhttp.proxyHost=webcache.mydomain.com -Dhttp.proxyPort=8080-Dhttp.noProxyHosts=”localhost|host.mydomain.com” MiClaseConMetodoMain

En el codigo de la clase:

System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setPropery("http.proxyPort", "8080");

// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();

// Now, let's 'unset' the proxy.
System.setProperty("http.proxyHost", null); // From now on http connections will be done directly.

HTTPS

htttps.proxyHost
https.proxyPort
http.nonProxyHosts

FTP

ftp.proxHost
ftp.proxyPort
ftp.nonProxyHosts

Configurando mas de un proxy:

$ java -Dhttp.proxyHost=webcache.mydomain.com -Dhttp.proxyPort=8080 -Dftp.proxyHost=webcache.mydomain.com -Dftp.proxyPort=8080 MiClaseConMetodoMain

SOCKS

socksProxyHost
socksProxyPort (default 1080)

Si defines un proxy HTTP y uno SOCKS,

  • tiene preferencia el HTTP.
  • El proxy SOCKS sera ignorado, para conexiones HTTP y SOCKS
  • Una conexion FTP, en esta configuracion, iria por SOCKS.

LA CLASE: java.net.Proxy

//creamos proxy HTTP
SocketAddress addr = new InetSocketAddress("webcache.mydomain.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);

// lo invocamos
URL url = new URL("http://java.sun.com/");
URConnection conn = url.openConnection(proxy);

// no queremos invocarlo
URL url2 = new URL("http://infos.mydomain.com/");
URLConnection conn2 = url2.openConnection(Proxy.NO_PROXY);

//creamos proxy SOCK
SocketAddress addr = new InetSocketAddress("socks.mydomain.com", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);

// lo invocamos
URL url = new URL("ftp://ftp.gnu.org/README");
URLConnection conn = url.openConnection(proxy);


// Invocacion especifica de proxy para una conexion Socket
Socket socket = new Socket(proxy);
InetSocketAddress dest = new InetSocketAddress("server.foo.com", 1234);
socket.connect(dest);

// no queremos invocarlo
Socket socket = new Socket(Proxy.NO_PROXY);
socket.connect(new InetAddress("localhost", 1234));

LA CLASE: java.net.ProxySelector

Determina para que conexiones usar un proxy u otro

public abstract class ProxySelector {
        public static ProxySelector getDefault();
        public static void setDefault(ProxySelector ps);
        public abstract List<Proxy> select(URI uri);
        public abstract void connectFailed(URI uri,
                SocketAddress sa, IOException ioe);
}
Java Proxy

Java Hibernate DDBB, Date

En java tenemos:

  1. el paquete java.util
    • Date: representa el tiempo con precision de milisegundos
    • Calendar: clase abstrapta que provee metodos para convertir instantes de tiempo en un conjunto de campos del calendario.
    • GregorianCalendar: es una clase concreta de Calendar.
  2. el paquete java.sql
    • Date: solo guarda la fecha
    • Time: solo guarda la hora
    • Timestamp: guarda la fecha y la hora

En las bases de datos Oracle tenemos:

  • Date: guarda fecha y hora pero solo con una precision de 1 segundo
  • Time: guarda la hora.
  • Timestamp: guarda fecha y hora.

Si tratas de convertir un tipo de dato SQL.DATE en java.util.Date: tienes que usar la anotacion de JPA: @Temporal que indica que se debe hacer una conversion temporal al tipo (indicado en la anotacion), para tranformarlo al tipo especificado en la clase.

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "FECHA_DATE", nullable = false)
	public java.util.Date getFechaDate() {
		return this.fechaDate;
	}

De esta manera conservamos la fecha y la hora.

Solucion a errores:
jpa-2-0-oracle-date-has-null-time

Java Hibernate DDBB, Date

ejecutar eCoFirma en local

Existe esta aplicacion desde el Ministerio, para firmar/comprobar si una firma es valida/refirmar

Si la utilizas frecuentemente no la vas a estar ejecutando siempre desde internet pues puede tardar y depender de tu configuracion de internet. Es mucho mejor descargarla a local.

1.- Lo que te ofrece la pagina es un java JNLP. Te lo descargas y lo abres con un editor de textos. Los apartados que nos interesan son:

  <application-desc main-class="es.mityc.firmaJava.cliente.Lanzador" />
 <j2se version="1.6+" initial-heap-size="100m" max-heap-size="512m" java-vm-args="-Xms128M -Xmx900M -Dfile.encoding=utf-8"/>
    <jar href="eCoFirma.jar" main="true"/>
    <jar href="lib/ClienteXADES-1.4.jar"/>
    ... mas librerias

2.- tenemos que recuperar todas las librerias que son obligatorias para su ejecucion y es muy facil. Hay que construir una URL por cada libreria con la parte inicial de la URL y el nombre y ubicacion de la libreria en la pagina web.
«http://oficinavirtual.mityc.es/javawebstart/soc_info/ecofirma/» mas la libreria «eCoFirma.jar»
http://oficinavirtual.mityc.es/javawebstart/soc_info/ecofirma/eCoFirma.jar
http://oficinavirtual.mityc.es/javawebstart/soc_info/ecofirma/lib/ClienteXADES-1.4.jar
asin sucesivamente.

3.- Lo copio a una carpeta, dejo las librerias en la carpeta lib y el eCoFirma.jar en la raiz.
4.- Genero un script de ejecucion:

java -Xms128M -Xmx900M -Dfile.encoding=utf-8 -cp "eCoFirma.jar;lib/*" es.mityc.firmaJava.cliente.Lanzador >> eCoFirma.log

Tambien tienes launch4j, para lanzar cosas.
Para la ejecucion en consola, te recomiendo que mires este otro post.

ejecutar eCoFirma en local

Generar el MANIFEST.MF

En referencia al post anterior. Ahora vamos a ver como se genera el manifest.

En consola

jar cfm jar-file manifest-addition input-file(s)
  • c: indica que quieres crear un fichero JAR.
  • m: indica que quieres unir informacion de un fichero en el manifest que estas creando.
  • f: indica salida a un fichero en lugar de por consola
  • manifest-addition: nombre del fichero que contiene la informacion a agregar al manifest.
  • jar-file: nombre del JAR resultante.
  • input-file(s): lista de ficheros que quieres que esten en tu JAR.

El contenido del manifest estara en UTF-8
Referencia.

Con Maven

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
				  <archive>
				    <index>true</index>
		            <manifest>
		              <addClasspath>true</addClasspath>
		            </manifest>
		            <manifestEntries>
		              <Permissions>all-permissions</Permissions>
		              <Codebase>*.prietopalacios.net</Codebase>
		              <Application-Library-Allowable-Codebase>*.prietopalacios.net</Application-Library-Allowable-Codebase>
		              <Caller-Allowable-Codebase>*.prietopalacios.net</Caller-Allowable-Codebase>
		              <Trusted-Library>true</Trusted-Library>
		              <Trusted-Library>true</Trusted-Library>
		            </manifestEntries>
		          </archive>
				</configuration>
			  </plugin>
Generar el MANIFEST.MF

Aumentar la seguridad de los MANIFEST.MF

Atributos:
Permissions: utilice el atributo «Permissions» para ayudar a evitar que alguien utilice su jar firmado en otra aplicacion y lo pueda ejecutar en un nivel de privilegio diferencte. Establezca este atributo en uno de los siguientes valores:

  • sandbox – Indica que la RIA se ejecuta en el entorno limitado de seguridad y no requiere de permisos adicionales.
  • all-permissions: todos los permisos, indica que el RIA requiere el acceso a los recursos del sistema del usuario.

RIA: Rich Internet Applications

Codebase: restringe el uso del jar a un dominio especifico:
Codebase: * todos
Codebase: *.example.com todos los subdominios del dominio example.com. Esto incluye http://www.example.com. www es un subdominio.
Codebase: 127.0.0.1, en el servidor local en todos los puertos.
Codebase: 127.0.0.1:8080, solo en el puerto 8080 del servidor local.
Application-Name: nombre de la aplicacion. Es recomendable para que el usuario pueda confiar en la aplicacion. Aparece una ventana mostrando el nombre de la aplicacion, indicando si la quieres ejecutar o no.

Application-Library-Allowable-Codebase: identifica la localizacion donde el jar sera ejecutado. Este atributo se utiliza para determinar lo que aparece en el campo Ubicación de la pregunta de seguridad que se muestra a los usuarios cuando el archivo JAR para su RIA está en una ubicación diferente a la página del archivo JNLP o HTML que se inicia el RIA.
Application-Library-Allowable-Codebase: https://host.example.com *.samplehost.com/apps
Caller-Allowable-Codebase: identifica el dominio desde el cual el codigo JavaScript puede hacer llamadas a la RIA sin indicaciones de seguridad. Establezca este atributo en el dominio que aloja el código JavaScript.
Caller-Allowable-Codebase: host.example.com 127.0.0.1
Trusted-Only: solo clases de confianaz. No ejecuta clases que no esten firmadas.
Trusted-Library: solo librerias de confianza. Firmadas.

Referencia

Aumentar la seguridad de los MANIFEST.MF

Firmar un JAR

para firmar un jar es muy sencillo, basta tener la JDK, un «key store» con su user/pass/alias/private pass.

A la hora de firmar un jar lo que se hace es:
1.- generar un hash de cada clase en SHA y lo agrega al manifest de la siguiente manera

Manifest-Version: 1.0
Implementation-Vendor: Gobierno de Espana
Implementation-Title: es.gob.afirma
Implementation-Version: build01
Application-Library-Allowable-Codebase: *
Specification-Vendor: Gobierno de Espana
Application-Name: Applet Cliente Afirma
Name: es/gob/afirma
Permissions: all-permissions
Specification-Title: Applet Cliente Afirma
Specification-Version: 3.3.1 u5
Caller-Allowable-Codebase: *
Codebase: *

Name: org/bouncycastle/jcajce/provider/digest/Whirlpool$Digest.class
SHA-256-Digest: FKks3RbQC/oJ2jlI2P9GKwYkEQdZNBOUW6dFI8uVdmM=

...

2.- Agrega unos ficheros que contienen el certificado, con el que se ha firmado, en la misma carpeta donde esta el MANIFEST.MF

En consola

jarsigner -keystore keystore.jks -storepass keystore_pass -keypass keystore_pass -signedjar jarsfirmados/LO_QUE_SEA.jar -verbose jars/LO_QUE_SEA.jar keystore_alias

Maven

			  <plugin>
				    <groupId>org.apache.maven.plugins</groupId>
				    <artifactId>maven-jarsigner-plugin</artifactId>
				    <version>1.2</version>
				    <executions>
				        <execution>
				            <id>sign</id>
				            <goals>
				                <goal>sign</goal>
				            </goals>
				        </execution>
				    </executions>
				    <configuration>
				        <keystore>/path/to/testkeystore</keystore>
				        <alias>myalias</alias>
				        <storepass>depo.root</storepass>
				    </configuration>
				</plugin>
Firmar un JAR

Time Intervals

P[n]Y[n]M[n]DT[n]H[n]M[n]S
P[n]W

PT

Hay que reemplazar [n] por el dato correcto

P periodo, precede a los componentes de duracion.
Y is the año .
M is the mes.
W is the semana .
D is the día .

T is the time precede a los componentes de designacion del tiempo
H is the horas .
M is the minutos .
S is the segundos .

EJEMPLOS:
dentro de 20 minutos: PT20M
dentro de una hora: PT1H

El dia 05/04/2014: P2014Y04M05D
El dia 05/04/2014, 20 minutos después: P2014Y04M05DT20M

Referencias:
Wikipedia

Time Intervals

Client Soap1.2 CXF

	<bean id="clientOtrasConsultasFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
		<property name="serviceClass" value="es.depontevedra.soap.cargows.services.OtrasConsultas" />
		<property name="address" value="#{url}otrasconsultasws" />
		<property name="bindingId" value="http://www.w3.org/2003/05/soap/bindings/HTTP/" />
	</bean>
	<bean id="clientOtrasConsultas" 
		class="es.depontevedra.soap.cargows.services.OtrasConsultas"
		factory-bean="clientOtrasConsultasFactory" factory-method="create" />
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:jaxws="http://cxf.apache.org/jaxws" 
	xmlns:soap="http://cxf.apache.org/bindings/soap" 
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://cxf.apache.org/jaxws 
	http://cxf.apache.org/schemas/jaxws.xsd
	http://cxf.apache.org/bindings/soap
	http://cxf.apache.org/schemas/configuration/soap.xsd">

	<jaxws:client id="clientVR" address="http:/host:port/realizarVerificacion" 
		serviceClass="es.una.ruta.a.una.Interfaz"
		serviceName="VerificacionResidenciaFecha" >
		<jaxws:binding>
			<soap:soapBinding version="1.2"/>
		</jaxws:binding> 
	</jaxws:client>
Client Soap1.2 CXF

Diferencias Soap1.1 vs Soap 1.2

Sobre las peticiones que estoy haciendo en mis servicios:

---------------------------
ID: 1
Address: https://host:port/services/cargos.otrasconsultasws
Encoding: UTF-8
Content-Type: text/xml
Headers: {Accept=[*/*], Connection=[Keep-Alive], SOAPAction=["consultarMaestrosGenericos"]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>...</soap:Body></soap:Envelope>
--------------------------------------
---------------------------
ID: 1
Address: https://host:port/services/cargos.otrasconsultasws
Encoding: UTF-8
Content-Type: application/soap+xml; action="consultarMaestrosGenericos"
Headers: {Accept=[*/*], Connection=[Keep-Alive]}
Payload: <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Body>....</soap:Body></soap:Envelope>
--------------------------------------

DIFERENCIAS

Estas dos lineas son las mismas para ambos:
SOAP1.1 = SOAP1.2 = Address: https://elb.esb.wso2.com:8243/services/cargos.otrasconsultasws
SOAP1.1 = SOAP1.2 = Encoding: UTF-8

SOAP1.1 = Content-Type: text/xml
SOAP1.2 = Content-Type: application/soap+xml; action=»consultarMaestrosGenericos»

SOAP1.1 = Headers: {Accept=[*/*], Connection=[Keep-Alive], SOAPAction=[«consultarMaestrosGenericos»]}
SOAP1.2 = Headers: {Accept=[*/*], Connection=[Keep-Alive]}

SOAP1.1 = xmlns:soap=»http://schemas.xmlsoap.org/soap/envelope/»
SOAP1.2 = xmlns:soap=»http://www.w3.org/2003/05/soap-envelope»

Diferencias Soap1.1 vs Soap 1.2