Monthly Archives: September 2018

All about the skill of programming

Yes, this will be the post where we dissect the skill of programming. Recently I came across a lot of beginner’s questions from friends and families who want to get into programming. But also if I want to go back in time and want to give advice to 10 years younger me, what advice would I give? How would I approach programming skills differently compared to what I did?

Before I move forward, if you want to read design patterns, you can visit that link.

Why does programming matter?

Most of us are not born programmers or smart enough to gauge our ability to sit in front of a computer for hours and write something in a completely foreign language to mankind. Programming is definitely not foreign anymore, but there are still a lot of people in the world, who don’t know anything about how computers work. They want to use computers, but don’t care about how computers operate.

I will not cover how computers work in this topic, but want to remind everyone that when we designed computers back in 50s and 60s, one purpose was that it could help us to solve some of the complex problems we face. Computers have exceeded the expectations and there is a speculation that in near future, all mundane jobs will be replaced by artificial intelligence. Artificial intelligence is only possible when the programming continues to evolve and it has been. There are lot of curious people in our world and this mere mortal is one of them. For me, it was curiosity that drove towards computers and slowly i embraced the internals and ideas about computer. It was fascinating always. To answer the question, in short, to continually evolve as mankind, we need technology and technology is the fastest evolving paradigm which is majorly based on programming.

What’s your purpose for programming?

You don’t really need a purpose to program. I started with programming mundane algebraic functions . It was continuous improvement from that moment to solve some of the complex mathematics problems to engineering problems to real world business problems. Despite all that, there are lot of system level problems in computers that need attention. You can even choose a purpose of fun. Lot of programmers started programming for fun and built some of the coolest games. No purpose is still a purpose till the time you allocate certain time to improve your skill. It’s been 15 years from the time I have graduated from college, but I have not stopped programming and I am no where close to say that I am the best. You will never be the best, you will continually improve and that’s the aim you should have. Learn from all sources.

How to learn the skill of programming?

This is a broad topic. Learning how to learn itself covers lot of intricacies. How to learn programming. I will try to narrow down discussion about this in few steps

  1. Learn basic syntax, but not all of the syntax. You will learn this over the time.
  2. Learn programming principles, mostly object oriented principles.
  3. Find out common patterns and study them. In software engineering, we follow lot of design patterns and they get used all the time while designing any application.
  4. Find out common libraries in the language that you want to learn.
  5. If you are learning Java, definitely read Effective JavaClean code and Refactoring.
  6. Try pair programming where you work with another programmer.
  7. Read, read and read lots of code – bad code to good code both.
  8. Fall in love with learning to program, process over results.
  9. If you take up a project, start with MVP (Minimum Viable Product), get feedback from peers/customers and then improve on the product you are building. While following this process, you will improve your programming as well. You will hit road blocks, that will challenge you to find out the solution on your own. Balance long term process (learning programming) with short term goals (projects that you will work on).
  10. If you work with senior programmers, get a feedback for your code.

Resources for programming

  1. Solve problems on HackerRank
  2. Free code camp – Freecodecamp
  3. Participate in hackathons
  4. Write blogs about your insights

Conclusion

In this post, I tried to simplify a process about how to learn programming, and how to improve the skill of programming. I hope this post helps all those who are on the fence about programming to take up programming.

A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

Introduction

Hibernate is an ORM provider. ORM is an object-relationship mapper. Hibernate Persistent class takes the values from the Java class attributes and persists them in the database.

Problem Statement

So recently I came across an interesting issue while working on hibernate persistence. I had an object certificate which had a child collection object certificateProperties. While updating an object that refers to certificate, it keeps throwing an error as below:

A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: com.betterjavacode.model.Certificate.certificateProperties; nested exception is org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: com.infor.security.sts.config.model.Certificate.certificateProperties
 at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333)
 at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
 at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:765)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:734)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:518)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
 at com.sun.proxy.$Proxy213.save(Unknown Source)

It was surprising to see this error randomly popping up. I was wondering if I missed orphanRemoval tag on my object certificate for certificateProperties, but it was there. So definitely it was not the issue. Also to remember, I was using cascade = CascadeType.ALL for cascading persistence of certificate.

Solution

Now if you notice, hibernate gives enough information about the error to notice what is happening. Hibernate is complaining that it is not able to track the change for the child collection object certificateProperties while it is getting set in the parent object certificate. Hibernate requires that parent object owns a child collection object completely.

To fix this issue, the solution was simple

Old Code

    public void setCertificateProperties(Set<CertificateProperty> certificateProperties)
    {
        this.certificateProperties = certificateProperties; 
    }

Solution Code
    private Set<CertificateProperty> certificateProperties = new HashSet<>();

    public void setCertificateProperties(Set<CertificateProperty> certificateProperties)
    {
        this.certificateProperties.addAll(certificateProperties);
    }

 

Conclusion

We showed how hibernate can handle the persistence in the cascade operation. If you enjoyed this post, please subscribe to my blog here.

Spring Boot Actuator

In this post, we will look at how we can use the spring boot actuator to add some metrics related endpoints in Spring Boot based microservice or application. Spring boot helps to monitor your production-ready application by offering a number of metrics related endpoints.

What do you need:

  • Java 8
  • Spring Boot
  • IntelliJ
  • Gradle

What are Spring boot actuator endpoints?

I will not be showing how to create a Spring boot REST in this article. You can refer my post to create a REST API based on Spring boot here.

As Spring documentation says – “Spring boot actuator let you monitor and interact with your application.” The endpoints that we will be discussing, are built in Spring Boot. Of course, the first question that comes to mind, is how do we activate these endpoints and what different endpoints are available there for what purposes.

How to activate actuator endpoints?

To activate these endpoints in a gradle-based project, we have to add the following dependency

dependencies {
  compile("org.springframework.boot:spring-boot-starter-actuator")
}

If you are using maven, this will be like below:

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
</dependencies>

All the actuator endpoints are enabled by default.

  • auditevents – Audit events of your application
  • info– Displays information about your application – you can customize to show version information.
  • health – application’s health status
  • metrics – various metrics information of application
  • loggers – Displays and modifies configured loggers
  • logfile – Shows the contents of the log file
  • httptrace – Displays HTTP trace info for the last 100 HTTP request/response
  • env – Displays current environment information
  • flyway – Shows Flyway database migrations details
  • liquidbase – Shows details of liquibase database migrations
  • shutdown – Allows to shut down the application gracefully
  • mappings– Displays a list of all @RequestMapping paths
  • scheduledtasks – Displays the scheduled tasks in the application
  • threaddump – Performs a thread dump
  • headdump – Returns JVM head dump

Another way these endpoints can be enabled or disabled, is to add properties in application.properties as shown below:

management.endpoint.health.enabled=true

Running the spring boot application with actuator

Once we have added the required spring-boot-starter-actuator dependency, we can build our application. There is still one more change we need to add in our gradle build file to get application version information.

springBoot{
     buildInfo()
}

If you are using maven, this can be added as below:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>build-info</goal>
            </goals>
        </execution>
    </executions>
</plugin>

If you want to add some additional properties, add following properties in application.properties as below:

info.app.name = Reusable-Rest-Module
info.app.version = 0.1.0-SNAPSHOT
management.security.enabled=false

Now once you build the application and run it, this will give us following results:

Healthcheck metrics using Spring Boot Actuator

http://localhost:8080/health

Info Metrics using Spring Boot Actuator

http://localhost:8080/info

Logging metrics using Spring Boot Actuator

http://localhost:8080/loggers

Conclusion

In this post, we showed how we can use Spring Boot Actuator to get different metrics data for your spring boot based service.