Victor Carvalho

Engenheiro de Software. Focado em arquitetura de aplicações

How to resolve “Invalid signature file digest for Manifest main attributes” in Maven Shade Plugin

Invalid signature file digest for Manifest main attributes

If you get this message on compile using Maven Shade Plugin the solution is exclude .SF, .DSA and .RSA files

My pom.xml file is like that

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <version>2.3</version>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>shade</goal>
      </goals>
      <configuration>
          <filters>
              <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                      <exclude>META-INF/*.SF</exclude>
                      <exclude>META-INF/*.DSA</exclude>
                      <exclude>META-INF/*.RSA</exclude>
                  </excludes>
              </filter>
          </filters>							
      </configuration>
    </execution>
  </executions>
</plugin>

JPA + Hibernate + Interceptor + Auditoria

I will to show a way how to intercept objects that Hibernate keeps in its session.

That communication type is common when you need to audit some objects in your application.

For example, when you need to register the moment after a object to be deleted or updated.

That behavior type can to be used to create your own object cache.

1 – The first step its add the following property in the file persistence.xml (JPA Configuration File)

<property name="hibernate.ejb.interceptor" value="com.titorec.MyInterceptor" />

2 – The next step its create a class extended from org.hibernate.EmptyInterceptor 

public class MyInterceptor extends EmptyInterceptor {
}

3 – After that, you can override the methods below when you to need.

To see the full documentation about the class EmptyInterceptor visit the following link: https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/EmptyInterceptor.html

Method Summary
 void afterTransactionBegin(Transaction tx)
Called when a Hibernate transaction is begun via the Hibernate Transaction API.
 void afterTransactionCompletion(Transaction tx)
Called after a transaction is committed or rolled back.
 void beforeTransactionCompletion(Transaction tx)
Called before a transaction is committed (but not before rollback).
 int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types)
Called from flush().
 Object getEntity(String entityName, Serializable id)
Get a fully loaded entity instance that is cached externally
 String getEntityName(Object object)
Get the entity name for a persistent or transient instance
 Object instantiate(String entityName, EntityMode entityMode, Serializable id)
Instantiate the entity class.
 Boolean isTransient(Object entity)
Called to distinguish between transient and detached entities.
 void onCollectionRecreate(Object collection, Serializable key)
Called before a collection is (re)created.
 void onCollectionRemove(Object collection, Serializable key)
Called before a collection is deleted.
 void onCollectionUpdate(Object collection, Serializable key)
Called before a collection is updated.
 void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
Called before an object is deleted.
 boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types)
Called when an object is detected to be dirty, during a flush.
 boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
Called just before an object is initialized.
 String onPrepareStatement(String sql)
Called when sql string is being prepared.
 boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
Called before an object is saved.
 void postFlush(Iterator entities)
Called after a flush that actually ends in execution of the SQL statements required to synchronize in-memory state with the database.
 void preFlush(Iterator entities)
Called before a flush

4 – After override the methods, your interceptor should work fine. Its all 😉

SQL SERVER DRIVER + JPA

Maven Dependency

<dependency>
  <groupId>com.microsoft</groupId>
  <artifactId>sqljdbc4</artifactId>
  <version>3.0</version>
</dependency>

Maven Repository

<repositories>
  <repository>
    <id>clojars.org</id>
    <url>http://clojars.org/repo</url>
  </repository>
</repositories>

JPA Configuration

javax.persistence.jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
javax.persistence.jdbc.url=jdbc:sqlserver://172.16.200.6\INGESQL:1433;databaseName=myDB
javax.persistence.jdbc.user=admin
javax.persistence.jdbc.password=?????

How to import a WebService WSDL with or without authentication

The wsimport its a tool that import webservices from a given WSDL file. The wsimport is located on the path: \bin in your JDK home. For example C:\Program Files (x86)\Java\jdk1.7.0_79\bin

How to import a webservice withoud autentication

wsimport -keep http://example.com/test?wsdl -s C:\path\to\source\

How to import a webservice with autentication

    1. You need to create a text file for use on autentication. The text file content is below.
    2. http://[login]:[password]@example.com/test?wsdl
    3. I have created this text file on the path c:\auth.txt
    4. Now you need to execute the following command line
      wsimport -Xauthfile C:\auth.txt -keep http://example.com/test?wsdl -s c:\path\to\source\

When the process end you will see on console.

parsing WSDL...



Generating code...


Compiling code...

Its a example how to call the WebService

/**
 * The following snippets shows how to set a custom endpoint for a JAX-WS generated WebClient on runtime
 */

// Get the service and the port
SampleService service = new SampleService();
Sample port = service.getESamplePort();

// Use the BindingProvider's context to set the endpoint
BindingProvider bp = (BindingProvider)port;

/* Optional if you to need to change the endpoint */
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://www.aviramsegal.com/ws/sample");

/* Optional  credentials */
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "user");
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "password");

/* calling the webservice method */
port.callSampleMethod();

fonte: http://stackoverflow.com/questions/5158537/jaxws-how-to-change-the-endpoint-address

Its all 😉

How to convert DMS (degrees, minutes, secondes) to DD (decimal degrees) Geographic Coordinates

DMS(degrees, minutes, secondes) -> DD(Latitude, Longitude)

public static Double[] dmsToLatLong(String emisferioLatitude, Double latitude_degres, Double  latitude_minutes, Double latitude_secondes, String emisferioLongitude, Double longitude_degres, Double longitude_minutes, Double longitude_secondes) throws Exception {

    int nordsud = 0;
    int estouest = 0;

    Double lat, lng;

    Double latitude, longitude;

    int S = -1;
    int N = 1;
    int W = -1;
    int E = 1;

    if (emisferioLatitude.equals("S")) {
      nordsud = S;
    } else if (emisferioLatitude.equals("N")) {
      nordsud = N;
    }

    if (emisferioLongitude.equals("W")) {
      estouest = W;
    } else if (emisferioLongitude.equals("E")) {
      estouest = E;
    }

    if (nordsud == 0) {
      throw new Exception("Error!");
    }

    if (estouest == 0) {
      throw new Exception("Error!");
    }

    lat = nordsud * (latitude_degres + latitude_minutes / 60 + latitude_secondes / 3600);
    lng = estouest * (longitude_degres + longitude_minutes / 60 + longitude_secondes / 3600);

    latitude = (double) (lat * 10000000) / 10000000;
    longitude = lng;

    return new Double[]{latitude, longitude};
  }

How to call the function

public static void main(String[] args) throws NumberFormatException, Exception {
  dmsToLatLong("S", Double.parseDouble("08"), Double.parseDouble("00"), Double.parseDouble("54.598"), "W", Double.parseDouble("35"), Double.parseDouble("07"), Double.parseDouble("58.853"));
}

How to execute Shell Script from Java

process = Runtime.getRuntime().exec("ping google.com");
process.waitFor();

BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader readerError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

String retornoSucess = "";
String retornoError = "";

while ((retornoSucess = reader.readLine()) != null) {
    sb.append(retornoSucess + "\n");
}

while ((retornoError = readerError.readLine()) != null) {
    sb.append(retornoError + "\n");
}

System.out.println(retornoSucess);
System.out.println(retornoError);

How to use sequence generator on Hibernate (Be careful with unique constraint violation)

Sequences are used to generate a ID when you do insert into a table on your database.

Use the following command to create a sequence on your Oracle database.

CREATE SEQUENCE mySequence START WITH 1 INCREMENT BY 1;

How to map on Hibernate

@Id
@SequenceGenerator(name = "mySequence", sequenceName = "mySequence", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="mySequence")
private Long id;

Pay attention to “allocationSize”, that param need to be equal the “INCREMENT BY”,
otherwise may to show errors like “unique constraint violation”.

With the “allocationSize” larger then “INCREMENT BY”, you will generate a gap between the application sequence mapped by Hibernate with your database.