How to run a background task using Spring Framework ThreadPoolTaskExecutor

Sometimes we need to execute a task in background in our application
We can use the class ThreadPoolTaskExecutor of Spring Framework to do that

To do it work we just need declare this bean in spring.xml config file as below

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.thread.ThreadPoolTaskExecutor">
  <property name="corePoolSize" value="5000" />
  <property name="maxPoolSize" value="5000" />
  <property name="queueCapacity" value="5000" />
</bean>
public class ReportJob {
  
  @Autowired
  @Qualifier("taskExecutor")
  private ThreadPoolTaskExecutor taskExecutor;
  
  public void startReport() throws IOException{
    taskExecutor.execute(); <- your thread to be executed here
  }
}

Main properties

maxPoolSize – The max number of threads in the pool

corePoolSize – The current size of thread pool

queueCapacity – If all threads are executing in corePoolSize and the size of corePoolSize is equal to maxPoolSize the task will be allocated in the queue until a thread to be free. If you exceed the queueCapacity the task will be ignored

Detect the standard time, the daylight saving time for the time zone

I was looking for a way how to detect the Dayligth Saving Time in JavaScript and I have found the following solution

if (timezonedetect.hasDaylightSavingTime()) {
  console.log('You have daylight saving time in your timezone');
} else {
  console.log('You DO NOT have daylight saving time in your timezone');
}

console.log('Your standard time zone offset in second is ' + jsk.tz.standardTime());
console.log('Your standard time zone offset is : ' + jsk.tz.standardTimeToString());

Visit the github project url to see the full documentation and download: https://github.com/dsimard/timezonedetect

How to generate a zip file from a List of File

public static void addToZipFile(File file, ZipOutputStream zos) throws FileNotFoundException, IOException {
  FileInputStream fis = new FileInputStream(file);
  ZipEntry zipEntry = new ZipEntry(file.getName());
  zos.putNextEntry(zipEntry);

  byte[] bytes = new byte[1024];
  int length;
  while ((length = fis.read(bytes)) >= 0) {
    zos.write(bytes, 0, length);
  }

  zos.closeEntry();
  fis.close();
}
FileOutputStream fos = new FileOutputStream(C:\myzipfile.zip);
ZipOutputStream zos = new ZipOutputStream(fos);

for(File f : filesToAdd){
  Util.addToZipFile(f, zos);
}

zos.close();
fos.close();

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=?????