07 December 2017

Very important notes about Spring @Transnational

Sprint @Transnational is being ignored in the following cases:

1. when the caller method is calling the @Transaction annotated method from the same class

2. When the Annotated method is not public

@Transnational by default don't rollback for Checked Exceptions


class A{
     void caller(){
            doInTransactionMethod(); // @Transnational is ignored
     }

    @Transnational // by default rollback for RuntimeExceptions
    public <return type> doInTransactionMethod(<params>){ // should be public as well
    }
}

The problem is, I keep forgetting about the above 3 simple rules, So I tried to writing down here to try not to forget about it

18 November 2017

Goobye Eclipse welcome Intellij IDEA

I used IntelliJ IDEA before 4 or so years ago when I was working with Android and then switched back to Eclipse. And I felt that I came back to the stone age.

What stopped me from continuing on IntelliJ is that I use IBM Jazz at work which is not supported well by our team. And everybody uses Eclipse so I decided to follow the crowd.

Eclipse is a nice Java IDE, but I have some behaviours that I don't like which drove me to migrate to IntelliJ IDEA.

Nowadays I wanted to create JAX-RS Rest application, but Eclipse insisting that this is an EJB project and keep adding ejbModule source-based structure, and at this point, I felt It is it. Eclipse I am breaking with you :P.

I am using the community edition from IntelliJ because I don't need the "Enterprise" features of an IDE (like Create new Servlet, or EJB, or deploy to JBoss or Tomcat), I just use shell scripts to do the deployment myself, and it works on both *nix and M$ Windows platforms :)

Still, I use Eclipse just to use the powerful plugin written for Jazz Source code management. (until I figure out how to use jazz from inside IntelliJ)

And for green-field projects, I use spring boot of course (When I have the option :) )

03 November 2017

Deploy your maven project to the public repository

1. update your maven to look like https://github.com/mhewedy/sftp-utils/blob/master/pom.xml by adding the following:


<name>sftp-utils</name>
<description>SFTP Utils</description>
<url>https://github.com/mhewedy/sftp-utils</url>

<licenses>
    <license>
        <name>Apache License Version 2.0</name>
        <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
    </license>
</licenses>

<developers>
    <developer>
        <name>Muhammad Hewedy(mhewedy)</name>
        <email>mhewedy@gmail.com</email>
        <organization>mhewedy</organization>
        <organizationUrl>https://github.com/mhewedy</organizationUrl>
    </developer>
</developers>

<scm>
    <connection>scm:git:git@github.com:mhewedy/sftp-utils.git</connection>
    <developerConnection>scm:git:git@github.com:mhewedy/sftp-utils.git</developerConnection>
    <url>git@github.com:mhewedy/sftp-utils.git</url>
</scm>


And

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <executions>
        <execution>
            <id>attach-javadocs</id>
            <goals>
                <goal>jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-source-plugin</artifactId>
    <executions>
        <execution>
            <id>attach-sources</id>
            <goals>
                <goal>jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-gpg-plugin</artifactId>
    <executions>
        <execution>
            <id>sign-artifacts</id>
            <phase>verify</phase>
            <goals>
                <goal>sign</goal>
            </goals>
        </execution>
    </executions>
</plugin>

<plugin>
    <groupId>org.sonatype.plugins</groupId>
    <artifactId>nexus-staging-maven-plugin</artifactId>
    <version>1.6.3</version>
    <extensions>true</extensions>
    <configuration>
        <serverId>ossrh</serverId>
        <nexusUrl>https://oss.sonatype.org/</nexusUrl>
        <autoReleaseAfterClose>true</autoReleaseAfterClose>
    </configuration>
</plugin>

And change the values according to your project

Then create a ticket like this: https://issues.sonatype.org/browse/OSSRH-35670

Then after it is resolved as fixed, then execute from the project directory:

mvn clean deploy

and check https://oss.sonatype.org/content/groups/staging/ and https://oss.sonatype.org/content/groups/public for the artifacts, for example:
https://oss.sonatype.org/content/groups/public/com/github/mhewedy/sftp-utils/


18 March 2017

Using spwrap inside spring transactions

spwrap is a little library that simplify calls to database stored procedures in java.

Read this introduction to talk an idea about spwrap before continue reading this post.

We have talked before about how to use spwrap in spring boot application.

Today we will talk about a new feature just release in version 0.0.18, which is spwrap now can participate in spring transactions.

spwrap itself doesn't allow spanning transaction across DAO method calls. but as part of 0.0.18, it will participate in spring Transactions if spwrap is used inside spring and there's an active transaction.

Suppose we have a spring project with Datasource transaction manager is enabled.

And we have  SupplierDAO which is a spwrap DAO defined like this:


public interface SupplierDAO {

    @StoredProc("insert_new_supplier")
    void insertSupplier(@Param(VARCHAR) String name);
}

And we have a domain object supplier and its spring-data-jpa repository

@Entity
public class Supplier {

    @Id    @GeneratedValue(strategy = AUTO)
    private Long id;

    @Column(unique = true)
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
// -- repository
public interface SupplierRepo extends JpaRepository<Supplier, Long> {
}

And here's the service class:

@Service
public class SupplierService {

    private SupplierDAO supplierDAO;
    private SupplierRepo supplierRepo;

    public SupplierService(SupplierDAO supplierDAO, SupplierRepo supplierRepo) {
        this.supplierDAO = supplierDAO;
        this.supplierRepo = supplierRepo;
    }

    @Transactional
    public void add2Suppliers(){
        final String supplierName = "Abdullah";

        supplierDAO.insertSupplier(supplierName);   // << will rolled-back

        Supplier s2 = new Supplier();
        s2.setName(supplierName);
        supplierRepo.save(s2);      // throws exception
    }

    public List<Supplier> listSuppliers(){
        return supplierRepo.findAll();
    }
}

Now because the supplierDAO.insertSupplier(supplierName) insert supplier with name "Abdullah", and supplierRepo.save(s2) insert supplier with the same name, then spring frameowkr will throw DataAccessException subclass and rollback the entire transaction.

Which meaning the stored procedure that is executed as a result of calling supplierDAO.insertSupplier(supplierName) will be rollbacked as well. Again, this is a new feature as part of spwrap 0.0.18. 

You can see the full example at github: https://github.com/mhewedy/spwrap-examples/tree/master/spring-boot-transactions-mysql Don't forget, if you like the spwrap library, don't forget to like the project page at github.

12 March 2017

Local port forward

How to connect on a remote service as if it is existed on your localhost

ssh -L <The New Port on your machine>:localhost:<The original port on the remote machine> <Remote machine user name>@<The remote machine>

Example for sql on a linux machine on port 1433:

ssh -L 1433:localhost:1433 username@my-linux-machine

http://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html

02 March 2017

Using spwrap with Spring boot

spwrap is a tiny framework to make stored procedures call from java code an easy and fun task.

I've written a couple of posts about it.

Today, I am gonna show you how to use it from spring boot project.

The main point I want to emphasis here is to register DAO interfaces as Spring Bean so that I would be reused across your application:

@Configuration
public class Config {

    @Autowired
    private DataSource dataSource;

    @Bean
    public DAO dao(){
        return new DAO.Builder(dataSource)
                .config(new spwrap.Config().useStatusFields(false))
                .build();
    }

    @Bean
    public CustomerDAO customerDAO(DAO dao){
        return dao.create(CustomerDAO.class);
    }
}
See the github page https://github.com/mhewedy/spwrap-examples/tree/master/spring-boot-mysql for the complete project.

Learn more: https://github.com/mhewedy/spwrap/wiki/Using-with-Spring-Boot-other-DI-frameworks
Thanks to stored-procedure-proxy at: https://github.com/marschall/stored-procedure-proxy/wiki/Object-Lifetime

28 February 2017

Using spwrap to simplify calling stored procedures from java

spwrap is a tiny framework to simplify the call to stored procedures from Java code.

In this post, I'll implement the Columbian coffee example from Java Tutorial at oracle.

This example uses mysql database to store coffee and suppliers data. see the install script at github.

The script installs 2 Tables: suppliers and coffees fill them with data and create 3 stored procedures: 
show_suppliers: To list all coffee names with supplier names (takes no parameters and return as result set)
get_supplier_of_coffee: To get a supplier name of coffee (takes 1 input parameter and return 1 output parameter)
raise_price: To raise the price of coffee (take 3 input parameters and return 1 output parameter)
Note: the original  raise_price stored procedure take 2 input parameters and 1 in/out parameter, but spwrap doesn't support INOUT parameters, so I split it into 1 input and 1 output parameter.

We will use spwrap to simplify the call to these 3 stored procedures.

First, We need to Create a Java interface to represent these 3 stored procedures:
public interface ColumbianDAO {

    @StoredProc("SHOW_SUPPLIERS")
    List<SupplierCoffee> showSuppliers();

    @Scalar(VARCHAR)
    @StoredProc("GET_SUPPLIER_OF_COFFEE")
    String getSupplierOfCoffee(@Param(VARCHAR) String coffeeName);

    @Scalar(NUMERIC)
    @StoredProc("RAISE_PRICE")
    BigDecimal raisePrice(@Param(VARCHAR)String coffeeName,
                          @Param(FLOAT)float maximumPercentage,
                          @Param(NUMERIC) BigDecimal newPrice);
}
The interface contains 3 methods to represent the 3 stored procedures, the annotation @StoredProc uses to mark method as a stored procedure.

The annotation @Scalar to represent the return type of stored procedure so that the output parameter mapped correctly to the method return type.

For the stored procedures that return its result as result set, you need to provide result set mapper to map the result set object to your domain object (SupplierCoffee), here's the mappers implementation:
public class SupplierCoffee implements ResultSetMapper<SupplierCoffee> {
    private String supplierName, coffeeName;

    @Override
    public SupplierCoffee map(Result<?> result) {
        // convert the result into SupplierCoffee        
        SupplierCoffee supplierCoffee = new SupplierCoffee();
        supplierCoffee.supplierName = result.getString(1);
        supplierCoffee.coffeeName = result.getString(2);
        return supplierCoffee;
    }

    @Override
    public String toString() {
        return "SupplierCoffee{" +
                "supplierName='" + supplierName + '\'' +
                ", coffeeName='" + coffeeName + '\'' +
                '}';
    }
}
And now you can call the stored procedures using the following code:
DAO dao = new DAO.Builder("jdbc:mysql://localhost:3306/columbian", "root", "")
        .config(new Config().useStatusFields(false))
        .build();

ColumbianDAO columbianDAO = dao.create(ColumbianDAO.class);

List<SupplierCoffee> supplierCoffees = columbianDAO.showSuppliers();
supplierCoffees.forEach(System.out::println);

String coffee = "Colombian";
String supplier = columbianDAO.getSupplierOfCoffee(coffee);
System.out.printf("Supplier of the coffee '%s' is '%s'\n", coffee, supplier);

BigDecimal newPrice = columbianDAO.raisePrice(coffee, 0.10f, BigDecimal.valueOf(19.99));
System.out.printf("new price of '%s' is '%s'\n", coffee, newPrice);
Download the complete source code of the complete example at github.

If you want to know more about spwrap visit the project page at github.  If you like the project, please start it at github :)