mvn add jar file to local repository

Did you ever want to put a local jar library file into your deployment jar file, but the library file is not available on public repository (or you don’t want to put it on public repository?)

One possible method is to add maven dependency with scope and systemPath property


But using scope and systemPath has a problem, that is when I run mvn package to build a package, the dependency will not be included, so running the application on another machine will always complain NoClassDefFoundError or ClassNotFoundException

So a better method is to use mvn install:install-file plugin

This will add AesZip.jar to your local maven repository. When running mvn package to create package, the dependent libraries will be included into the generated package

Spring disable transaction for method in transactional class


In Spring @Transactional  annotation can be used to indicate method should be run in transaction.

When @Transactional  is placed on method, this method will be run with transaction. And if it’s placed on a class, all methods of this class will run within transaction.


In MVC style application, we usually wrap business logic into a separate service class annotated with @Service  and @Transactional , so every method in this class will run within transaction. But how to disable transaction management for a specific single method in class which is annotated with @Transactional ?



Add following code before the method which you want to disable transaction management for.

Above code will tell Spring PlatformTransactionManager that transaction is not supported for this method, and transaction manager won’t create a new transaction if no transaction is existed.

And if a current transaction existed, exception will be thrown (An IllegalTransactionStateException with message “Existing transaction found for transaction marked with propagation ‘never'”).


java.lang.NoClassDefFoundError: java/util/Base64


In the following code, Base64 is used to encode AES encrypted data bytes to plain text for transfering via URL query parameter.


But when running this code on my coworker’s machine, following exception is thrown


It’s because that my execution environment is Java 8, but my coworker is using Java 7, and java.util.Base64 is introduced in Java 8.



To fix this issue, we can use Base64 class from Apache Commons Codec.

First add commons codec dependency to maven pom.xml file.

Next import Base64 class from commons-codec


Finally replace  Base64.getUrlEncoder().encodeToString to Base64.encodeBase64URLSafeString .

So the code will become like following



Method.invoke throws java.lang.IllegalArgumentException: wrong number of arguments


There is a private downloadFile method of ZhangyoobaoLeshuaMerchantRegister class, the method signature is like following

A unit test case for this method need be created, in this test case we need pass a null value as parameter to test whether this method can handle null parameter. But a private method cannot be accessed from the instance level. The solution is to use reflection to get the method, and set its accessiblity to public temporarily (by using the Method.setAccessible method).


First let’s see some code

Above Java code is the unit test case, it uses reflection to get the private method downloadFile of class ZhangyoobaoLeshuaMerchantRegister, and set the access level of this method to public, then call it with parameters. (Note that if setAccessible is not called to set method access level, Method.invoke will throw IllegalAccessException.)

But running this line  result = method.invoke(register, null);  will got following error

It’s because the second argument of Method.invoke() is Object...  (An Object[] array), its elements are arguments passed in to the method. Calling Method.invoke() with null as second argument is actually trying to call the method with no arguments, but downloadFile method requires one parameter, so it definitely raises IllegalArgumentException.



To fix this issue, change following line


This will pass null as first argument for downloadFile method. new Object[]{null}  is correspondding to the Object...  argument of Method.invoke(), it’s expanded like calling downloadFile(null) .


Hibernate Query unexpected token: INTERVAL

I’m trying to fetch inventories which is opened at last month, for traditional SQL DATE_SUB function should be used here for date calculation. So the HQL is like following


But following error appeared when running it in Hibernate QL Query Consonle in Intellij IDEA


Unfortunatelly the INTERVAL keyword is not supported in HQL.



An alternative is to calculate the date in Java and pass the result dates to HQL as parameters. The code is like following


Implementation code for DateUtil.getLastMonthFirstDay and DateUtil.getLastMonthLastDay




Spring Cloud Zuul Ribbon custom rule not working

I need a custom Rule which can route requests to different service according to weight option (actually I want to deploy an A/B test service and only small percent of user will hit it), the code is like following


And following is application.yml configuration file


Adding breakpoints at constructor of ZoneAwareLoadBalancer and DynamicServerListLoadBalancer, then access the Zuul service via browser and I found ZoneAwareLoadBalancer constructor breakpoint is reached first.

Inspect the value clientConfig->properties->NFLoadBalancerClassName, its value is still “”, and the passed in rule is not my configured rule as well.

This means my configuration didn’t work.


Even I changed the class name to an invalid value, there is no error


In Spring Cloud documentation, under Customizing the Ribbon Client using properties section, it’s saying

Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the Ribbon documentation.

Checking maven pom file I found it’s using 1.1.0


Changing them to 1.2.0 and run again, following exception is thrown


It’s because NFLoadBalancerRuleClassName is aaa, changing it to a valid name and try it again, it works now



Java HTML Encoding (HTML Entities)

Some XSS attacks can be prevented by using HTML Encoding.

HTML encoding function is built into many languages, In .NET WebUtility.HtmlEncode  can do it, in PHP we can use htmlentites  function, in Python cgi.escape  can be used.

But there is no built-in function to do HTML Encode (or HTML Entities) in Java.

We can use Apache Commons Lang library to do this work.


Above code will output following result using HTML Encoding



Note that not all XSS attacks can be prevented by HTML encoding (

Apache POI Sheet.getPhysicalNumberOfRows()

In the past I use following code to display first cell string of all rows.

But above code will be incorrect if there is empty row.


Following is explanation from POI official documentation


Returns the number of physically defined rows (NOT the number of rows in the sheet)

This method will ignore empty rows, e.g. if a sheet last row is at row 7, but second row is empty, getPhysicalNumberOfRows()  will return 6.



To get row count of a sheet (no matter the row is empty or not), we should use getLastRowNum()  method.

So above code can be changed to

Because getLastRowNum()  method returns 0-based row index, so we use i<=sheet.getLastRowNum()  as the loop condition.

Dom4j Writing File Not Working

Dom4j is a XML processing library which supports XPath, DOM, SAX,  JAXP. In this post we will see a problem that dom4j could not write document to file.


Following XML is sample data which we will save to file using dom4j.

To generate above XML and write it to file, following code will be used

Above code may generate an empty file with no content.


This is because the content is stored in buffer and not really written to file when calling write  method. To write to file, we should call flush  method or close  method.

So above code should be changed to



Hibernate ConstraintViolationException

In following code (a JUnit test method) I’m trying to delete specified users from database


But when running above code, I got following exception:

org.hibernate.exception.ConstraintViolationException: could not execute batch

at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.doExecuteBatch(
at org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.execute(
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.executeBatch(
at org.hibernate.engine.spi.ActionQueue.executeActions(
at org.hibernate.engine.spi.ActionQueue.executeActions(
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(
at org.hibernate.internal.SessionImpl.flush(
at com.dfweb.service.impl.SysUserServiceImplTest.testAddPermissions(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
at java.lang.reflect.Method.invoke(
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(
at org.junit.runners.model.FrameworkMethod.invokeExplosively(
at org.junit.internal.runners.statements.InvokeMethod.evaluate(
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(
at org.junit.runners.ParentRunner$
at org.junit.runners.ParentRunner$1.schedule(
at org.junit.runners.ParentRunner.runChildren(
at org.junit.runners.ParentRunner.access$000(
at org.junit.runners.ParentRunner$2.evaluate(
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(
at com.intellij.rt.execution.junit.JUnitStarter.main(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
at java.lang.reflect.Method.invoke(
at com.intellij.rt.execution.application.AppMain.main(
Caused by: java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails (db_df.permission_sys_user, CONSTRAINT FK_2l5pbq5juqkbrg6rtqes6w1el FOREIGN KEY (users_id) REFERENCES sys_user (id))
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(
at com.mysql.jdbc.PreparedStatement.executeBatch(
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(
… 41 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (db_df.permission_sys_user, CONSTRAINT FK_2l5pbq5juqkbrg6rtqes6w1el FOREIGN KEY (users_id) REFERENCES sys_user (id))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
at java.lang.reflect.Constructor.newInstance(
at com.mysql.jdbc.Util.handleNewInstance(
at com.mysql.jdbc.Util.getInstance(
at com.mysql.jdbc.SQLError.createSQLException(
at com.mysql.jdbc.MysqlIO.checkErrorPacket(
at com.mysql.jdbc.MysqlIO.checkErrorPacket(
at com.mysql.jdbc.MysqlIO.sendCommand(
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(
at com.mysql.jdbc.ConnectionImpl.execSQL(
at com.mysql.jdbc.PreparedStatement.executeInternal(
at com.mysql.jdbc.PreparedStatement.executeUpdate(
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(
… 44 more



This is because there is an RESTRICT reference for foreign key of permission_sys_user that references id column of sys_user table.

So deleting the SysUser entity and keep its related permissions in permission_sys_user table will break the foreign key constraint of permission_sys_user table (references sys_user table with default RESTRICT reference option).



Following is SysUser class related source code


One possible solution is to remove its related records in permission_sys_user table when deleting SysUser entity, so change SysUser to following will fix this issue:

Above code adds CascadeType.REMOVE  for ManyToMany  annotation’s cascade  attribute. This will make deleting SysUser entity will trigger deleting related Permission entities.