Skip to main content

Posts

Showing posts from 2018

Sending Form data to a backend REST API using Axios

This need is incredibly common and useful, and hopefully will save you a lot of time when doing server side calls from your UI application (or even non UI clients like NodeJS applications) Example here is to send a POST request to an endoint /api/item/new (which will create a new item in the database). We will just assume tbhe backend is already setup (it's not relevant to this article). All we need to know is that we can do a POST /api/item/new and send it form data with two pieces of info     name, filter So, if you have a node.js application (I was using Vue-cli generated project, but it does not matter), install 'axios' (a most popular tool to make server calls these days) npm i axios --save OR yarn add axios (my preferred method) Now, in your service JS file (which is generally when I keep all my api calls) do something like this createNew ( name , filter ) { let formData = new FormData (); formData . append ( "name" ,

Setting up a nice dev/prod workflow for Vue-CLI frontend apps using Spring backend

My current recipe which works not bad is setup spring at localhost:8082, vue-cli app on localhost:8080 setup proxy in devServer for webpack to point all /api calls to localhost:8082. So now any calls made from vue application to /api will be sent to the spring application at /api setup spring api endpoints at /api add a 'buildx' npm task to do the usual "vue-cli build && copy " over to spring src/main/resources/static area, mine usually looks like this in package.json "buildx" : "vue-cli-service build && copyfiles -u 1 dist/* dist/**/* ../build/resources/main/public && copyfiles -u 1 dist/* dist/**/* ../src/main/resources/public -V" ,   I usually copy to both build/ and src area, since build makes restart instantliy work in spring side, and src/ area makes bundle available in spring jar file created using bootJar task, for deployment setup devtools on spring to autorestart I can dev/test using jus

Authenticating Spring Boot based application against secure LDAP/AD server

Authenticating against an Active Directory setup is quite common in organizations using Spring Boot / Spring Security can be a pain if you don't know exactly the requirements. I needed to add auth in my web app and secure some but not all endpoints of the application. My story was, I needed Spring security to authenticate against my company LDAP server which uses Active Directory I started by using the standard LDAP guide such as this which are all over the Internet, https://spring.io/guides/gs/authenticating-ldap/ and was able to setup the basic framework However, only test level LDAP auth was working for me, when I tried to auth against the company LDAP secure server, I had to resolve a few issues After 1 week and working with several devs at the company, I finally found why it was not working and the fix was easy Since I spent a week or so resolving this, I wanted to write this up in case someone finds this useful. Here is what I did (it was easy until the fourth

Use Service objects along with your controllers in Spring boot to cleanup code and testing

If you have Spring controller that uses repository objects, it can become a bit messy to write tests with mocks that have to mock various repository object methods like save() etc. Instead, you can use Here is an example controller that uses repository objects: @RestController public class StateManagerController { public StateManagerController(XRepository aRepository, YRespository yRepo) {   } public void aMethod() { // use xRepo, yRepo : e.g., xRepo.save() , yRepo.delete() etc. } ... } To test methods of this controller that use the repository objects, you will likely have to mock each repository collaborator object. Then you can get into lots of mocking details that make your tests ugly. Instead, I find that using the following pattern greatly simplifies both your code and tests. It's very simple but works great. 1. In your controller, only inject/depend on @Service objects. Don't use repository objects directly 2. Test your con

Using actuator in Spring boot to analyze and monitor your application

Intro Spring boot offers a wonderful module called the actuator. It is somewhat similar to the tools offered by Rails or other frameworks to get a better view of your application. Basically when you enable it, you can browse to a url which by default is at /actuator (but can be configured), where you will find very interesting pieces of information about your Spring boot application. For example, if you built a MVC webapp where you wrote a number of @Controller or @RestController classes, then going to /actuator/mappings will list your endpoints along with which controller method serve which endpoint etc. But there is a whole lot more in actuator you will find useful. In this article, I will show you how to use it in your application, and also how to only enable it in your development profile. I would assume that you don't want soething like this enabled in your production deployment. We will use Spring profiles for this. Setup I am assuming you have a working Spri

Using custom conditional logic to enable/disable Spring components

If you have a Spring component and you don't want it to load, you can use Spring's predefined conditionals as much as possible. For example, @Component   @ConditionalOnNotWebApplication   public class SchedulerEntryPoint implements ApplicationRunner { ...  } This will not load your component when running in non web application mode. Such as you may want to start the application but without any of the web framework using SpringApplicationBuilder. But sometimes you want to use custom conditions. It's pretty easy to do so, just use something like this @Component @Conditional (SchedulerCheck. class ) public class SchedulerEntryPoint implements ApplicationRunner { public static class SchedulerCheck implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return System. getProperty ( "scheduler" ) !=

Autoreloading your UI pages in the browser with each build, while developing web apps in Spring boot

I had been working on a simple gradle project where I use Spring boot to develop the backend and REST API using Spring data REST and Frontend using Vue.js + spring boot thymeleaf. Spring boot's controllers will handle the routing and all frontend work can be done in the html pages. I will post these other pieces separately. If you have done this, you may know that you can load your .html pages using Spring Boot's Thymeleaf rendering engine which comes configured by default. As long as you place them under src/main/resources/templates (default location for renderable templates) But once that page is rendered you can use any frontend framework on it. In my case, I am using Vue.js as the frontend framework (more on this in other posts) So if you have a spring boot project setup, you can install the spring boot devtools to your project. Once you do that, by default it will reload your spring boot application whenever your source code changes. However, normally your htm

A simple recipe to use grunt watch to setup simple autorun workflow while developing any type of project

It is great to have a tool that watches changes and reruns code (like tests or server code etc) as you are saving your files. This idea here of course works great with any Node project but hey, even if you are not coding in Node (or even in language other than JS), you can still use this idea, it's very generic and will work for just about any type of project if you just set this basic setup once. While there are many approaches to doing this depending on the project type (like webpack's watch which is super-powerful for web projects, nodemon  for server restart cases, chokidar etc), my current favorite for a generic  method that will work with any type of project is based on grunt-watch. So read on! I setup this simple repository with a simple readme guide on how to do this. https://github.com/binodpanta/node-examples/tree/master/gruntwatch I think it will save you a lot of time when working on NodeJS projects. Even if you don't use Grunt for your actual develop

Using a Java stream (Java 8+) to convert List collection into primitive data type arrays

You need to convert an ArrayList<Integer> to int, similar case for others like Long > long. Prior to Java 8, you would have to try something like int[] myarray =   ll.toArray(new Integer[size]); But this will fail to compile! So it forces you to use Integer[] instead of int[]. However, you may have client code that expect int[] and not Integer[]. So the only other way would be to iterate over the list and convert to array the traditional way by adding element by element. Fine, but not elegant. I discovered that the stream based method above works even for primitive data types like int. So converting an array list of integers to an array is quite straightforward with a mapToInt () intermediate Intstream (or LongStream for long) as follows ArrayList<Integer>  ll  =  new  ArrayList<Integer>();       int[] myarray =  ll .stream().mapToInt( c  ->  c ).toArray(); The c-> c is just a lamda that says return the value c for each value in the str