Tag Archives: java

SpringBoot creating UserDetailsService authentication

There are plenty of online tutorials showing how to create database-based authentication for Spring. Some of them use SQL query to authenticate user and retrieve its roles, some use DAO… but none of them worked well for me and all of them had some major problems, even like SQL Injection. So, in this post I will explain my approach and present final solution with a database (MySQL), User and Role class and UserDetailsService implementation.

The goal is to create basic webpage with login form and signup form (which includes fields validation) that handles different roles. Then, you and me can use it as a template project.

This tutorial doesn’t include steps how to setup your IDE and build environment. We’re going straight to code, and I will try to avoid as much boilterplate as possible, so the code won’t include getters and setters. If you still write them by hand, time to learn about Lombok project (which I use here) or any other code generator.

Continue reading

Gradle – up-to-date and secure dependencies

Everyone knows it’s important to keep dependencies up to date. The risks of not updating them are very often high: you risk losing your data or data of your customers, being part of a botnet or simply getting hacked by script kiddies replacing your frontpage with something shameful.
Not everyone knows how easy it is to keep your dependencies up to date with gradle. Both gradle and maven have plugins to check for updates in your list of dependencies.

This post quickly shows how to use one of them in gradle and check if your dependencies have reported vulnerabilities.

First gradle plugin you want to check out is gradle-versions-plugin. It’s used only to find updates. Installation and usage is very simple. Just add this block to your build.gradle file

plugins {
    id 'com.github.ben-manes.versions' version '0.14.0'
}

Now, when you run:

./gradlew dependencyUpdates

You will get a list of available updates:

The second plugin you should use is dependency-check. It checks if current versions of dependencies you use were reported with a vulnerability to NVD.
Installation is again, really simple, just modify your build.gradle to include the following:

buildscript {
  repositories {
     mavenCentral()
  }
  dependencies {
     classpath 'org.owasp:dependency-check-gradle:1.4.5'
  }
}
 
apply plugin: 'org.owasp.dependencycheck'

and when ready, run:

./gradlew dependencyCheck

Unfortunately, this process is time consuming, the more dependencies you have, the longer break you can take now.

Be safe out there!

Adding user to Tomcat in Docker

When using official Tomcat server from Docker Hub you will face a problem with opening management UI, because there is no default login or password in that docker image, so the only app management site you can visit is this one:

And because Tomcat doesn’t have user management built-in like other container managers – it loads users and passwords from conf/tomcat-users.xml file, it makes it more complicated to start with Tomcat than with other container managers like Wildfly.

The Tomcat Docker image comes without nano, vi or vim… so you can’t easily edit that file, but hopefully it comes with.. sed. And that’s good enough to add new users and roles to the file! Remember the times when you didn’t see the file you were editing when you when typing, until vi came out of course?

Continue reading

Spring Boot – multi-database setup

To be able to access two databases in SpringBoot you must define two data sources. In my case I had one database for identity details of users, like username, name, email, address etc. and second database for everything else.

You have to define one @Configuration class for each database and each class will wired its own datasource to services (like JpaRepository or CrudRepository) to defined packages.

Continue reading

Setting up SonarQube for Android Gradle project to improve code quality

I’m working on a new Android project which I inherited. Well, I forked it because I didn’t feel welcomed to contribute to the project and I see a lot of places where improvements are needed.

First, I need to improve the codebase. Previous developers didn’t care about any Java coding guidelines from Oracle, Google, CERT or even Android. Some of the problems I have to solve now are:

  • inconsistent style
  • catch (Exception e){}
  • catch(Throwable e){}
  • ArrayList<Object> list = new ArrayList<String>()
  • complex methods – if {switch {for {if {else {}}}}
  • new Thread().start()

To quickly start clean-up and identify those problems, different static code analysis tools can be used; one of them is SonarQube.

Continue reading

[Java] – Regular expression to match IPv4 address

I saw such question on SO. There was no solution with RegEx so… I was bored I think.

public static boolean isValid(String ip) {
    boolean isvalid;
 
    isvalid = ip.matches(
            "(([0-9]|[0-9]{0,2}|1[0-9]*{0,2}|2[0-5][0-5]|0{0,3}).){3}" +
             "([0-9]|[0-9]{0,2}|1[0-9]*{0,2}|2[0-5][0-5]|0{0,3})"
    );
 
    return isvalid;
}

Continue reading

[Java] regular expression to match emails and domains works with gTLD

Recently we got many new top-level domains like .international, .berlin etc, so older regular expressions are no longer valid.
Below you can see a list of valid domains; an address may contain . (dot), – (minus) and .subdomain (domain may contain many sub-domains). A domain must end with a letter, it cannot be . (dot) or a number.

  • site.international
  • site.international.com
  • site.ac.uk
  • site.org
  • site.babia-gora.pl
  • site.pl

Email address may contain a delimiter like – or + and . (dot), it might contain numbers and for sure contain letters. Below is a list of valid email addresses:

  • info9@agilob.net
  • in-fo@site.international
  • in.fo@site.ac.uk
  • in+fo@site.babia-gora.pl
  • 1in-+fo2@site.babia-gora.pl

A regular expression to match gTLD domains can look like this:

^[A-Za-z0-9][A-Za-z0-9/.-]*\.*[A-Za-z]$

and regular expression to match emails in domains above like this:

[A-Za-z0-9-+/.]*@^[A-Za-z0-9][A-Za-z0-9/.-]*\.*[A-Za-z]$

Code to test those regexpes:

package regexp;
 
import java.util.ArrayList;
 
public class RegExpMatcher {
 
    public static void main(String[] args) {
        ArrayList domains = new ArrayList<>();
        domains.add("site.international");
        domains.add("site.international.com");
        domains.add("site.ac.uk");
        domains.add("site.org");
        domains.add("site.babia-gora.pl");
        domains.add("site.pl");
 
        boolean matches;
        System.out.println("Matching domains: ");
 
        for (int i = 0; i < domains.size(); i++) {
            matches = domains.get(i).matches("^[A-Za-z0-9][A-Za-z0-9.-]*\.*[A-Za-z]$");
            if (matches == true) {
                System.out.println(domains.get(i) + " matches");
            } else {
                System.err.println(domains.get(i) + " doesn't match");
            }
        }
 
        System.out.println("nnMatching email addresses: ");
 
        ArrayList emails = new ArrayList&lt;&gt;();
        emails.add("info9@agilob.net");
        emails.add("in-fo@site.international");
        emails.add("in.fo@site.ac.uk");
        emails.add("in+fo@site.babia-gora.pl");
        emails.add("1in-+fo2@site.babia-gora.pl");
 
        for (int i = 0; i < emails.size(); i++) {
            matches = emails.get(i).matches("[A-Za-z0-9-+.]*@[A-Za-z0-9][A-Za-z0-9.-]*\.*[A-Za-z]$");
            if (matches == true) {
                System.out.println(emails.get(i) + " matches");
            } else {
                System.err.println(emails.get(i) + " doesn't match");
            }
        }
    }
}

Output:

Matching domains: 
site.international matches
site.international.com matches
site.ac.uk matches
site.org matches
site.babia-gora.pl matches
site.pl matches


Matching email addresses: 
info9@agilob.net matches
in-fo@site.international matches
in.fo@site.ac.uk matches
in+fo@site.babia-gora.pl matches
1in-+fo2@site.babia-gora.pl matches

Solution to SQLException: No suitable driver found for jdbc:mysql

Just a quick fix.

Instead of:

Connection con = null;
 
String url = "jdbc:mysql://localhost:3306/mysql";
String user = "user";
String password = "password";
con = DriverManager.getConnection(url, user, password);

You should have:

Connection con = null;
 
String url = "jdbc:mysql://localhost:3306/mysql";
String user = "user";
String password = "password";
 
try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
    System.err.println(ex.getMessage());
}
con = DriverManager.getConnection(url, user, password);

Continue reading

AberPizza in Java

AberPizza – simple cash register for small pizzerias. Application made as a first year, second semester assignment.

Application has a built-in database of products and prices, can add those product to an order, give discount in GBP or in percentage of the whole order.

Bills are stored in XML files and can be loaded into the application to print receipt.

Continue reading

[pl] Learn IT online – zestaw kursów do nauki informatyki

[pl] Gynvael Coldwind prowadzi swoje kursy na YT. RE, debugging, Asm, programowanie OO widziane z niska. Czekam na OpenGL.

[pl] javastart.pl Kurs Javy, wstęp do programowania w Javie na Android i co nieco JEE. Autor ma dobre nawyki pisania w OO.

Continue reading

No suitable driver found for jdbc:mysql

Miałem dzisiaj bardzo dziwny problem z NetBeans7.2 z próbą stworzenia połączenia z bazą danych MySQL.

Zaczęło się od niedoczytanej dokumentacji… czyli zamiast:

            Connection con = null;
 
            String url = "jdbc:mysql://localhost:3306/mysql";
            String user = "user";
            String password = "password";
            con = DriverManager.getConnection(url, user, password);

Continue reading